【问题标题】:Grouping on the x axis in ggplot2在ggplot2中的x轴上分组
【发布时间】:2017-05-29 16:49:39
【问题描述】:

在 ggplot 中,我想在 x 轴上创建子类别,如下所示:

中提出的解决方案 Multirow axis labels with nested grouping variables 不工作。

【问题讨论】:

  • 他们怎么不工作?你尝试过什么,它输出了什么?

标签: r ggplot2 charts axis-labels


【解决方案1】:

更新到 ggplot2 的 2.2.0 或更高版本。然后您可以使用facet_wrap 的更多功能来构建您正在寻找的图形。这是一个例子:

library(ggplot2)
packageVersion("ggplot2")
# [1] ‘2.2.1’

dat <-
  data.frame(category = c("A", "A", "B", "B", "C", "C"),
             subcat   = c("S1", "S2", "S1", "S2", "S1", "S2"),
             value    = c(73, 57, 7, 23, 51, 87))

ggplot(data = dat) +
  aes(x = subcat, y = value, fill = subcat) +
  geom_bar(stat = "identity", width = 1) +
  geom_text(mapping = aes(label = paste0(value, "%")), vjust = -0.5) +
  facet_wrap( ~ category, strip.position = "bottom", scales = "free_x") +
  theme(panel.spacing = unit(0, "lines"),
        strip.background = element_blank(),
        strip.placement = "outside") +
  xlab("x-axis label")

【讨论】:

    【解决方案2】:

    下面提供了将直方图与ggplot 组合在一起的示例(我将“子类别”解释为因子type 的值。诀窍是在geom_bar() 中同时使用stat = "identity"position = "dodge" .

    df <- data.frame(class = c("A", "B", "C", "A", "C", "B", "C", "A", "B"), 
                      type = c("alpha", "beta", "gamma", "gamma", "beta", "gamma", "alpha", "beta", "alpha"), 
                      value = c(100, 200, 300, 50, 60, 120, 400, 300, 160))
    
    ggplot(df, aes(class, value, fill = type)) + geom_bar(stat = "identity", position = "dodge")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-07-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多