简体   繁体   中英

Drawing percentage lines between bars in ggplot2

I have a bar chart which I want also to include some lines that show the percentage difference between them as in the following figure:

在此处输入图片说明

The lines in the figure are drawn just to make my point of what I ideally want.

Can someone help me with this?

Here is the dataframe to replicate the figure:

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

And here is my code used to make the bar plot:

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

Your data unchanged:

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

Your graph unchanged:

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

I used the horizontal error bar to do the trick. Here is my solution:

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) 

Now, you get:
在此处输入图片说明

You can also adjust both height and width if you like.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM