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

时间:2019-09-14 21:56:21

标签: r ggplot2

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

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

1 个答案:

答案 0 :(得分:4)

您的数据保持不变:

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

如果愿意,还可以调整高度和宽度。