gpt4 book ai didi

r - ggplot2 分组直方图条

转载 作者:行者123 更新时间:2023-12-02 04:18:46 25 4
gpt4 key购买 nike

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

这是数据集的一部分:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com