[英]Grouping on the x axis in ggplot2
更新到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.