首页 > 解决方案 > ggplot2中的分组条形图

问题描述

我想复制这个图(在组之间进行分面) 条形图 (分面如中完成)在 此处输入图像描述 这是我的尝试:

library (ggplot2)
data<- data.frame(
  d = rep(LETTERS[21:26], 10),
  val = rnorm (60),
  c = rep(LETTERS[1:10], each = 6)
)

ggplot(data, aes(c, val)) + 
 geom_bar(stat = 'identity', aes(fill = val), position = "dodge") +
 facet_grid(data[, 1] ~ .)

并且图表是垂直排列的,而不是躲避的位置。我应该怎么办?

提前谢谢你。

标签: rggplot2bar-chart

解决方案


我觉得你不需要facet_grid(),随便填'd'

ggplot(data, aes(c, val)) +
  geom_bar(stat = 'identity', aes(fill = d), position = "dodge")

在此处输入图像描述


根据 OP 的评论,我们也可以使用facet_grid(cols = vars(d)).

ggplot(data, aes(c, val)) + 
  geom_bar(stat = 'identity', aes(fill = val), position = "dodge") +
  facet_grid(cols = vars(d)) # or facet_grid(. ~ d)

在此处输入图像描述


推荐阅读