ggplot2分组直方图条形图

瓦伦蒂娜

我在对直方图的条进行分组时遇到一些问题。

这是数据集的一部分:

data <- structure(list(Color = structure(c(1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L), .Label = c("blue", "red"), class = "factor"),
                       Group = structure(c(1L, 1L, 2L, 2L, 3L, 3L, 3L, 3L), .Label = c("Group1", "Group2", "Group3"), class = "factor"),
                       ID = structure(1:8, .Label = c("A1", "A2", "B1", "B2", "C1", "C2", "D1", "D2"), class = "factor"), 
                       Value = c(194L, 1446L, 0L, 17L, 77L, 2565L, 223L, 61L)), 
                  .Names = c("Color", "Group", "ID", "Value"), class = "data.frame", row.names = c(NA, -8L))

我建立直方图如下:

ggplot(data, aes(ID, Value)) + geom_bar(aes(fill = Color), position = "dodge", stat="identity") + scale_fill_manual(values=c("Blue", "Red"))

现在,我将通过变量Group对直方图的条进行分组,但是我发现使用facet_wrap无法实现:

ggplot(data, aes(ID, Value)) + geom_bar(aes(fill = Color), position = "dodge", stat="identity") + scale_fill_manual(values=c("Blue", "Red")) + facet_wrap(. ~ Group)

layout_base中的错误(数据,vars,drop = drop):至少一层必须包含用于构面的所有变量。

将组彼此隔开也是很好的。

我怎样才能做到这一点?有人可以帮我吗?

贾普

您需要删除.

ggplot(data, aes(ID, Value)) + 
  geom_bar(aes(fill = Color), position = "dodge", stat="identity") + 
  scale_fill_manual(values=c("Blue", "Red")) + 
  facet_wrap( ~ Group)

这将为您提供以下情节:

在此处输入图片说明

当您要改善绘图时,请包括scales = "free_x"facet_wrap零件中。这消除了x轴上不必要的值:

ggplot(data, aes(ID, Value)) + 
  geom_bar(aes(fill = Color), position = "dodge", stat="identity") + 
  scale_fill_manual(values=c("Blue", "Red")) + 
  facet_wrap( ~ Group, scales = "free_x")

这将为您提供:

在此处输入图片说明

如果您想要等宽的条,则最好在中使用space参数facet_grid

ggplot(data, aes(ID, Value)) + 
  geom_bar(aes(fill = Color), position = "dodge", stat="identity") + 
  scale_fill_manual(values=c("Blue", "Red")) + 
  facet_grid(. ~ Group, scales = "free_x", space = "free_x")

这给出了:

在此处输入图片说明

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章