R中的条形图,每个项目有2个条形图

时间:2017-10-10 12:01:12

标签: r ggplot2

我想要条形图和ggplot2(在R中)。我想每个月有两个酒吧。

monthyear = c('January 2015', 'February 2015', 'March 2016', 
             'April 2016', 'May 2016', 'June 2016', 'July 2016', 
             'January 2017', 'Februrary 2017', 
             'August 2017', 'September 2017', 'October 2017')

c_report = c(742, 3420, 4263, 5147, 6255, 93872, 2323, 
             4677, 9398, 2112, 1000, 7890)

o_report = c(30185, 33894, 33642, 29439, 27879 ,52347, 
              4578, 3639, 10000, 48781, 64484, 5020)

df = data.frame(monthyear, c_report, o_report)

ggplot(data = df , aes(x=c_report, y = o_report, fill = monthyear) ) + 
  geom_bar(stat="identity", position="dodge")

以下是上述代码的图表。

enter image description here

但我希望图表如下所示。

enter image description here

1 个答案:

答案 0 :(得分:1)

您需要重新整形数据以绘制分组条形图。

enter image description here

library(reshape2)
library(ggplot2)

data.m <- melt(df, id.vars='dateyear')

ggplot(data.m, aes(dateyear, value)) +   
  geom_bar(aes(fill = variable), position = "dodge", stat="identity") + theme(axis.text.x = element_text(angle = 90, hjust = 1))