gpt4 book ai didi

r - 在ggplot2中的条形之间绘制百分比线

转载 作者:行者123 更新时间:2023-12-02 00:13:28 24 4
gpt4 key购买 nike

我有一个条形图,我还想包括一些显示它们之间百分比差异的线条,如下图所示:

enter image description here

图中的线条只是为了说明我理想中想要的东西。

有人可以帮我解决这个问题吗?

这是复制图形的数据框:

structure(list(shares = c(0.39, 3.04, 9.32, 22.29, 64.97, 0.01, 
0.11, 5.83, 21.4, 72.64), quantile = structure(c(4L, 1L, 2L,
3L, 5L, 4L, 1L, 2L, 3L, 5L), .Label = c("2nd Quantile", "3rd Quantile",
"4nd Quantile", "Poorest 20%", "Richest 20%"), class = "factor"),
case = structure(c(1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L
), .Label = c("No Debt", "With Debt"), class = "factor")), row.names = c(NA,
-10L), class = "data.frame")

这是我用来制作条形图的代码:

ggplot(df_cum, aes(fill = case , quantile, shares)) + geom_bar(position =
"dodge", stat = "identity") +
scale_x_discrete(limits = c(
"Poorest 20%",
"2nd Quantile",
"3rd Quantile",
"4nd Quantile",
"Richest 20%"
)) +
theme_minimal()

最佳答案

您的数据未更改:

library(tidyverse)
df_cum<-structure(list(shares = c(0.39, 3.04, 9.32, 22.29, 64.97, 0.01,0.11, 5.83, 21.4, 72.64),
quantile = structure(c(4L, 1L, 2L, 3L, 5L, 4L, 1L, 2L, 3L, 5L),
.Label = c("2nd Quantile", "3rd Quantile", "4nd Quantile", "Poorest 20%", "Richest 20%"), class = "factor"),
case = structure(c(1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L), .Label = c("No Debt", "With Debt"), class = "factor")), row.names = c(NA, -10L), class = "data.frame")

你的图表没有改变:

p <- ggplot(df_cum, aes(fill = case , quantile, shares)) + 
geom_bar(position = "dodge", stat = "identity") +
scale_x_discrete(limits = c("Poorest 20%", "2nd Quantile", "3rd Quantile", "4nd Quantile", "Richest 20%")) +
theme_minimal()

我使用了水平误差条来解决这个问题。这是我的解决方案:

y = rep(c(3, 5, 13, 25, 75),2)
x = rep(c(1:5), 2)
label = rep(c("-3%", "-5%", "-2%", "-1%", "10%"), 2)
p1 <- p + geom_text(x=x, y=y+2, label=label)
p1 + geom_errorbarh(aes(xmax = (x + 0.3), xmin = (x - 0.3), y = y), height = 0.5)

现在,你得到:
enter image description here

您也可以根据需要同时调整高度和宽度。

关于r - 在ggplot2中的条形之间绘制百分比线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57939555/

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