簡體   English   中英

在 ggplot2 中的 x 軸上分組

[英]Grouping on the x axis in ggplot2

在 ggplot 中,我想在 x 軸上創建子類別,如下所示:

在此處輸入圖片說明

帶有嵌套分組變量的多軸標簽中提供的解決方案不起作用。

更新到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")

在此處輸入圖片說明

下面提供了將直方圖與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")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM