R中ggplot2中的分组条形图

Grouped barplot in ggplot2 in R

我想制作一个分组条形图。我的数据示例如下:

site code  year month gear total value
678490     2012 3     GL   13882
678490     2012 4     GL   50942
678490     2012 5     GL   54973
678490     2012 6     GL   63938
678490     2012 7     GL   23825
678490     2012 8     GL   8195
678490     2012 9     GL   14859
678490     2012 9     RT   3225
678490     2012 10    GL   981
678490     2012 10    RT   19074
678490     2012 11    SD   106384
678490     2012 11    RT   2828
678490     2012 12    GL   107167
678490     2012 12    RT   4514

有 17 个站点代码选项、四年选项、十二个月选项和四个齿轮选项。

我要制作的是每年每个站点的图,显示每个齿轮每个月的 'total value',作为一个条。

到目前为止,我已经成功地制作了一个特定于站点和年份的图,但是总值显示在每个月的一个条中,而不是每个月分成单独的条(不能在第一个 post!)

但是第 9、10、11 和 12 个月使用了两个齿轮,所以我希望这几个月有两个柱状图。

我正在使用以下代码:

ggplot(subset(cdata, year %in% c("2012") & site code %in% c("678490")), 
        aes(x = factor(month), y = total value)) + 
        geom_bar(stat = "identity") +
        labs(x = "Month", y = "Total value")

如有任何帮助,我们将不胜感激。

如果你想为每个 gear 单独的条形图,那么你应该将 fill=gear 添加到 geom_bar 中的 aes:

ggplot(cdata[cdata$year==2012 & cdata$sitecode==678490,],
       aes(x = factor(month), y = totalvalue, fill=gear)) + 
  geom_bar(stat = "identity", position="dodge") +
  labs(x = "Month", y = "Total value")

这给出:

如果你想为每个站点、每年制作一个图,显示每个齿轮的 'total value',每个月,作为一个条,你可以使用 facet_grid。例如:

ggplot(cdata, aes(x = factor(month), y = totalvalue, fill=gear)) + 
  geom_bar(stat = "identity", position="dodge") +
  labs(x = "Month", y = "Total value") +
  facet_grid(sitecode ~ year)

这给出:

一些补充意见:

  • 最好不要在列名中使用空格(在上面的代码中我删除了空格)
  • 在您的问题中添加一个示例,以说明您所面临的问题。在这种情况下,最好给出一个示例数据集,其中包含多个站点代码和多个年份。

因此我编了一些数据:

df1 <- read.table(text="sitecode  year month gear totalvalue
678490     2012 3     GL   13882
678490     2012 4     GL   50942
678490     2012 5     GL   54973
678490     2012 6     GL   63938
678490     2012 7     GL   23825
678490     2012 8     GL   8195
678490     2012 9     GL   14859
678490     2012 9     RT   3225
678490     2012 10    GL   981
678490     2012 10    RT   19074
678490     2012 11    SD   106384
678490     2012 11    RT   2828
678490     2012 12    GL   107167
678490     2012 12    RT   4514", header= TRUE)

df2 <- df1
df2$sitecode <- 7849
df2$year <- 2013
df3 <- df1
df3$sitecode <- 7849
df4 <- df1
df4$year <- 2013

cdata <- rbind(df1,df2,df3,df4)