gpt4 book ai didi

r - 将水平线添加到 R 中 ggplot2 中的堆叠条形图,并在图例中显示

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

我有一个堆叠的条形图,类似于下面的示例。

我想在每个条形上添加一组或两组水平线(指定颜色和线型),每个条形的值不同,并将它们添加到图例中。

Titanic.df <- as.data.frame(Titanic)

Titanic.ag <- aggregate( Freq ~ Sex + Class + Age, data=Titanic.df, sum, subset = Survived == "Yes")

bars <- rep(c(0.5, NA, 0.7, NA, 0.6, NA, 0.9, NA), 2)

ggplot(Titanic.ag, aes(x = Class, y = Freq, fill = Sex)) +
geom_bar(position = "fill", stat = "identity") +
facet_grid(~Age) +
geom_errorbar(aes(y = bars, ymin = bars, ymax = bars, col = "Ref1")) +
scale_fill_manual(values = c("darkgreen", "darkblue") ) +
labs(col = "Reference",
fill= "",
y = "Proportion",
x = "Class")

titanic stacked bar plot with horizontal lines

我已经尝试按照几个问题的建议使用 geom_errorbar() ,但我遇到了两件事:

如果我为误差线添加一个值向量,那么 ggplot 期望与数据帧中的长度相同(例如 Titanic.ag 中的 16),但只有 8 个条形,因为它们堆叠在一起。这就是我在 bars 中使用 NA 的原因以上。
有替代方案吗?

更重要的是,我想控制颜色和线型,但是如果我将这些添加到 geom_bar() 中,我将失去我的图例。例如
  geom_errorbar(aes(y = bars, ymin=bars, ymax=bars,  col = "Ref1"), col = "red", linetype = 2)

geom_segment() 是替代方案吗?

编辑错别字,澄清水平线的不同值。

最佳答案

我不完全确定你需要这个但是。个人 geom_abline调用让您轻松自定义每条线路。

ggplot(Titanic.ag, aes(x = Class, y = Freq, fill = Sex)) + 
geom_bar(position = "fill", stat = "identity") +
facet_grid(~Age) +
geom_abline(slope=0, intercept=0.5, col = "red",lty=2) +
geom_abline(slope=0, intercept=0.75, col = "lightblue",lty=2) +
scale_fill_manual(values = c("darkgreen", "darkblue") ) +
labs(col = "Reference",
fill= "",
y = "Proportion",
x = "Class")

产生这个情节

enter image description here

另外,也许 this可以帮助标签。

更新

好的,现在我明白了......使用相同方法的快速近似是使用多个条形向量和误差条调用。这有点累人,但可能会起作用,而 data.frame 可能不起作用,因为您希望每个条形都自定义多次。此外,考虑到 NA 已被删除,因此它们无法正常工作......也许使用大于 1 的数字并将 ylim 调整为 1,这样它们就不会显示
bars1 <- rep(c(0.5, NA, 0.7, NA, 0.6, NA, 0.9, NA), 2)
bars2 <- rep(c(NA, 0.9, 0.1, 0.1, NA, NA, NA, 0.5), 2)
bars3 <- rep(c(0.1, NA, NA, NA, NA, NA, NA, 0.1), 2)

ggplot(Titanic.ag, aes(x = Class, y = Freq, fill = Sex)) +
geom_bar(position = "fill", stat = "identity") +
facet_grid(~Age) +
geom_errorbar(aes(y = bars1, ymin = bars1, ymax = bars1), color="Orange",lty=2) +
geom_errorbar(aes(y=bars2,ymin=bars2,ymax=bars2),color="White",lty=2)+
geom_errorbar(aes(y=bars3,ymin=bars3,ymax=bars3),color="Purple",lty=2)+
scale_fill_manual(values = c("darkgreen", "darkblue") ) +
labs(col = "Reference",
fill= "",
y = "Proportion",
x = "Class")

enter image description here

关于r - 将水平线添加到 R 中 ggplot2 中的堆叠条形图,并在图例中显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35759681/

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