【问题标题】:Drawing percentage lines between bars in ggplot2在ggplot2中的条之间绘制百分比线
【发布时间】:2019-09-15 08:30:25
【问题描述】:

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

图中的线条只是为了说明我的理想状态。

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

这里是复制图的数据框:

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

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    您的数据未更改:

    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) 
    

    现在,您会收到:

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

    【讨论】:

    • 太棒了。如果你能帮忙,还有一件事。如何将百分比的文本字体更改为 Times New Roman?我使用了 'text =element_text(family="Times New Roman" ', 'in theme()' 但没有用。
    猜你喜欢
    • 2012-07-14
    • 1970-01-01
    • 2020-02-11
    • 2014-04-09
    • 1970-01-01
    • 2016-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多