如何用R创建条形图

时间:2015-12-11 23:23:52

标签: r

我是一个R菜鸟,并试图找出我希望将是一个简单的问题。我正在尝试使用下面的数据创建条形图,其中Moth位于y轴上,Visits(2014)和Visits(2015)是条形图,Trials(2014)和Trials(2015)是折线图。我意识到这在Excel中是一项微不足道的任务,但是我想了解这是如何在R中完成的。

Month ; Visits (2014) ; Visits (2015) ; Trials (2014) ; Trials (2015)
Jan ;  675 ; 835  ; 31  ; 41
Feb ; 620 ; 895   ; 30  ; 41
Mar ; 713 ; 1,117 ; 33  ; 46
Apr ; 634 ; 964   ; 29  ; 41
May ; 617 ; 968   ; 30  ; 42
Jun ; 626 ; 1,120 ; 30  ; 46
Jul ; 668 ; 961   ; 31  ; 46
Aug ; 650 ; 1,109 ; 32  ; 46
Sep ; 744 ; 1,207 ; 33  ; 48
Oct ; 792 ; 1,167 ; 34  ; 45
Nov ; 710 ; 1,142 ; 32  ; 41
Dec ; 746 ;       ; 30  ;

提前致谢!

2 个答案:

答案 0 :(得分:1)

首先,melt您的数据

library(data.table)

DT <- melt.data.table(DT)

然后使用ggplot2,图表很容易制作

library(ggplot2)

ggplot(DT, aes(x = Month, y = X1)) + 
    stat_bin(aes(fill = X1))

答案 1 :(得分:1)

以下是您的数据已清理并且已使用2015年12月的补偿值。一旦数据被R读入内存,dput()函数会为数据框df生成此数据。

structure(list(Month = structure(c(5L, 4L, 8L, 1L, 9L, 7L, 6L, 
2L, 12L, 11L, 10L, 3L, 5L, 4L, 8L, 1L, 9L, 7L, 6L, 2L, 12L, 11L, 
10L, 3L), .Label = c("Apr ", "Aug ", "Dec ", "Feb ", "Jan ", 
"Jul ", "Jun ", "Mar ", "May ", "Nov ", "Oct ", "Sep "), class = "factor"), 
    Year = c(2015, 2015, 2015, 2015, 2015, 2015, 2015, 2015, 
    2015, 2015, 2015, 2015, 2014, 2014, 2014, 2014, 2014, 2014, 
    2014, 2014, 2014, 2014, 2014, 2014), Visits = c(835, 895, 
    1117, 964, 968, 1120, 961, 1109, 1207, 1167, 1142, 1000, 
    675, 620, 713, 634, 617, 626, 668, 650, 744, 792, 710, 746
    ), Trials = c(41, 41, 46, 41, 42, 46, 46, 46, 48, 45, 41, 
    40, 31, 30, 33, 29, 30, 30, 31, 32, 33, 34, 32, 30)), .Names = c("Month", 
"Year", "Visits", "Trials"), row.names = c(NA, -24L), class = "data.frame")

下一步是将数据框融合成适合绘图的长格式。

library(reshape2)
df.m <- melt(df, id.vars = c("Year", "Month"))         # put the data frame in long form

最后,情节可以通过多种方式完成,但是这一年将这些年分解为两个小组。情节图像在这里被挤压。

library(ggplot2)
ggplot(df.m, aes(x = Month, y = value, fill = variable)) +
  geom_bar(stat = "identity", width = 0.7, position = "dodge") +
  geom_text(aes(label = value), vjust = .4, position=position_dodge(width=0.8)) + 
  theme_bw() +
  labs(x = "", y = "Number", title = "Two-Year Comparison of Visits and Trials") +
  theme(axis.ticks= element_blank()) +
  theme(plot.title = element_text(face = "bold", size = 11)) +
  scale_y_continuous(label = NULL, expand = c(0, 0)) +
  scale_fill_discrete(name="") +
  theme(legend.position = "bottom") +
  facet_wrap(~ Year)

enter image description here