r - ggplot2 分组直方图条

标签 r 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)

Error in layout_base(data, vars, drop = drop) : At least one layer must contain all variables used for facetting.

将组彼此隔开也一样好。

我该怎么做?有人可以帮助我吗?

最佳答案

您需要删除 :

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

这将为您提供以下情节:

enter image description here

当你想改善剧情时,在facet_wrap部分包含scales = "free_x"。这摆脱了 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")

这会给你:

enter image description here

如果你想要宽度相等的条,最好在 facet_grid 中使用 space 参数:

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")

这给出:

enter image description here

关于r - ggplot2 分组直方图条,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31834273/

相关文章:

image - R:哪个热图/图像可以获得没有任何树状图的行排序图?

r - 使用 PBSMapping 和 Shapefiles 帮助在 R 中绘制地理数据

r - R 中的交互式散点图,叠加/悬停摘要/工具提示作为用户提供的绘图功能

R/ggplot 2 - 使用 Facet_grid 和 geom histogram/errorbar 处理不均匀的组大小

r - 如何找到到最近的非重叠元素的距离?

r - 如何添加微型绘图并并排重复多个绘图?

excel - 从 Excel 工作表制作 .RData 文件

r - ggplot2:在不影响限制的情况下添加几何图形

r - ggplot2多线样条平滑

r - 如何将 geom_sf 生成的 map 放在 ggmap 生成的栅格之上