我在对直方图的条形图进行分组时遇到了一些问题。
这是数据集的一部分:
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(data,vars,drop = drop)出错: 至少一个图层必须包含用于构面的所有变量。
将这些组彼此隔开就好了。
我该怎么做?有人可以帮帮我吗?
答案 0 :(得分:4)
您需要删除.
:
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")
这给出了: