为分组条形图创建辅助x轴

时间:2017-05-11 21:41:15

标签: r ggplot2

我正在使用ggplot创建一个条形图,并且我试图按年创建一个“辅助”x轴。我下面的代码将复制我想要创建的内容:

library('ggplot2')

d1 <- structure(list(year = c(2010L, 2010L, 2010L, 2011L, 2011L, 2011L, 
                              2011L, 2012L, 2012L, 2012L, 2012L, 2013L, 2013L, 2013L, 2013L, 
                              2014L, 2014L, 2014L, 2014L, 2015L, 2015L, 2015L, 2015L, 2016L, 
                              2016L, 2016L, 2016L), 
                     group = c("Group 1", "Group 2", "Group 4", 
                              "Group 1", "Group 2", "Group 3", "Group 4", "Group 1", "Group 2", 
                              "Group 3", "Group 4", "Group 1", "Group 2", "Group 3", "Group 4", 
                              "Group 1", "Group 2", "Group 3", "Group 4", "Group 1", "Group 2", 
                              "Group 3", "Group 4", "Group 1", "Group 2", "Group 3", "Group 4"), 
                     count = c(111L, 216L, 22L, 125L, 231L, 22L, 57L, 126L, 256L, 
                               22L, 70L, 137L, 302L, 41L, 81L, 132L, 299L, 30L, 108L, 140L, 
                               337L, 22L, 95L, 168L, 383L, 31L, 96L)), 
                .Names = c("year", "group", "count"), 
                row.names = c(3L, 4L, 5L, 17L, 18L, 19L, 20L, 32L, 
                              33L, 34L, 35L, 47L, 48L, 49L, 50L, 62L, 63L, 64L, 65L, 77L, 78L, 
                              79L, 80L, 92L, 93L, 94L, 95L), 
                class = "data.frame")

ggplot(d1, aes(x = group, y = count, group = year, fill = group)) +
  geom_bar(stat = 'identity', position = 'dodge', color = 'black') +
  scale_y_continuous(breaks = seq(0, 400, 25),
                     limits = c(-20, 400)) +
  geom_text(aes(x = group, y = 0, group = year, label = year), 
            position = position_dodge(width = .92), size = 4, angle = -90, hjust = -.1) +
  guides(fill = FALSE)

现在,当我创建单个图形时,这对于我的目的来说效果很好,但是我正在尝试将这样的图形合并到一个闪亮的应用程序中,其中数据范围非常广泛,并且只需将y下限设置为 - 像我在这个例子中所做的那样,并不是一种有效的方式来显示酒吧下面的年份。

有没有办法复制我在这里做的事情而不必使用geom_text来解决它?

1 个答案:

答案 0 :(得分:1)

根据您所描述的内容。我想你正在寻找刻面的情节。

要创建分面图,您可以使用facet_wrap,facet_grid。此代码段应该可以完成类似的操作,而无需使用geom_text

ggplot(d1, aes(x=year,y=count,fill=group)) + 
  geom_bar(stat = 'identity', position = 'dodge', color = 'black') +
  facet_wrap(~group) + 
  guides(fill = FALSE) + 
  scale_y_continuous(breaks = seq(0, 400, 25),
                     limits = c(-20, 400))

enter image description here