根据另一个变量的值在r中创建直方图

时间:2014-06-17 06:18:06

标签: r

我有一个小的2变量数据框:

month <- c("january","february","march","april","may")
data <- c(10,20,30,20,10)
df <- data.frame(month = month, data = data)

看起来像这样:

     month data
1  january   10
2 february   20
3    march   30
4    april   20
5      may   10

我想基于这些数据制作直方图,其中列表示每个月的“数据”值,即x轴“1月”标记的“10”列,“20” “二月”标志栏等。

我该怎么做? 我用“hist”函数尝试了各种各样的东西 - 无济于事。

3 个答案:

答案 0 :(得分:1)

以基地R:

barplot(dt$data, names.arg=dt$month)

enter image description here

答案 1 :(得分:1)

如果你想要好的图形,你可以像ggplot2一样做这个

library(ggplot2)
month <- c("january","february","march","april","may")
month <- factor(month,levels=month,ordered=TRUE)
data <- c(10,20,30,20,10)
df <- data.frame(month = month, data = data)
p<-ggplot(df,aes(month,data,fill=month))+geom_bar(stat="identity")
p <- p+theme_bw()+theme(legend.position="none")
p

答案 2 :(得分:0)

使用barp {plotrix}:

month <- c("january","february","march","april","may")
data <- c(10,20,30,20,10)

library(plotrix)
barp(data, names.arg=month)

enter image description here

相关问题