【问题标题】:How to add the legend to combo plot?如何将图例添加到组合图中?
【发布时间】:2019-12-10 22:24:16
【问题描述】:

这是数据集:

d <- tribble(
  ~priceseg,   ~price_n, ~zet_n, ~zet_n2,
     "(0,1]",     16,      2,      24,      
     "(1,3]",     33,      3,      38,
     "(3,5]",     33,      2,      25,
     "(5,6]",     17,      1,      13,
)

感谢@d.b,这是可视化

ggplot(d) +
  geom_col(aes(x = priceseg, y = price_n), fill = ("#F1948A"), colour="black", size = 0.6) +
  geom_line(data = d, mapping = aes(x = priceseg, y = zet_n2, group = 1), colour = "#154360", size = 1) +
  geom_label(data = d, mapping = aes(x = priceseg, y = price_n, label = price_n), nudge_y = -0.6)

现在,我想在可视化中添加条形图和线条的图例,如下所示:Combined line & bar geoms: How to generate proper legend?

另外,我想在 geom_label 中添加 %。

但不知何故,我无法实现它。有什么帮助吗?

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    这是一个选项

    # Calculate percentage and add as column to `d`
    d <- transform(d, perc = sprintf("%2.1f%%", price_n / sum(price_n) * 100))
    
    # Plot
    ggplot(d, aes(x = priceseg)) +
      geom_col(aes(y = price_n, fill = "bar_data"), colour = "black", size = 0.6) +
      geom_line(aes(y = zet_n2, group = 1, colour = "line_data"), size = 1) +
      scale_fill_manual("", values = "#F1948A") +
      scale_colour_manual("", values = "#154360") +
      geom_label(aes(y = price_n, label = perc), nudge_y = -0.6) +
      theme(
          legend.key = element_blank(),
          legend.title = element_blank(),
          legend.box = "horizontal")
    

    您可以通过更改字符串"bar_data""line_data" 来调整填充和颜色“标签”。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-02
      • 1970-01-01
      • 1970-01-01
      • 2021-08-17
      • 1970-01-01
      • 2022-10-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多