绘制条形图

时间:2014-04-07 00:37:14

标签: r

我有一个数据集如下: (10,75) (20,80) (50,85) (100,92)

如何在R中绘制条形图?我在网上看到了很多例子,但没有一个符合这个简单的情况。感谢

2 个答案:

答案 0 :(得分:2)

试试这个:

data1=rbind(c(10,20,50,100),c(75,80,85,92))
barplot(data1, beside=TRUE, col=c("blue", "red"))

答案 1 :(得分:1)

作为替代方案,您始终可以使用ggplot2库。由于数据的形成方式,您还应该使用reshape2库来区分变量。在这种情况下,它有点复杂,但总的来说,你会得到更漂亮的条形图。

library(ggplot2)
library(reshape2)
#id variable tells what row number is used
data1=as.data.frame(cbind(id=1:4,var1=c(10,20,50,100),var2=c(75,80,85,92)))
#melt will create a row for each variable of each row, except it saves the id as a separate variable that's on every row
data1=melt(data1,id.vars='id')
#ggplot tells what data set is used and which variables do what
#geom_bar tells what type of plot should be used and certain options for the plot 
ggplot(data1,aes(x=id,y=value,fill=variable))+geom_bar(stat='identity',position='dodge')

enter image description here