【问题标题】:Legend for Dumb bell plot哑铃情节的传说
【发布时间】:2021-06-02 08:41:24
【问题描述】:

我正在尝试为我的哑铃情节创建一个简单的图例,但找不到方法。有没有办法这样做或手动创建图例?

我的代码如下:

data %>% 
  ggplot(aes(y = industry,
             x = retrenchment_in_year,
             xend = mean_retrenchment)) +  
  geom_dumbbell(size = 1,
                size_x = 2,
                size_xend = 2,
                colour = "black", 
                colour_x = "red", 
                colour_xend = "green")

Dumb bell plot

我只是想指出图例中的绿点和红点代表什么。

【问题讨论】:

    标签: r ggplot2 legend


    【解决方案1】:

    问题在于geom_dumbbell 没有映射到color 美学。因此,没有颜色图例。手动添加图例的一种选择是

    1. 添加两个空的geom_point 层,一个用于左点,一个用于右点
    2. color 美学上映射,它会自动给出一个图例
    3. 通过scale_color_manual设置颜色和/或图例标签

    由于您没有提供示例数据,我使用了来自 ?geom_dumbell 的示例:

    df <- data.frame(trt=LETTERS[1:5], l=c(20, 40, 10, 30, 50), r=c(70, 50, 30, 60, 80))
    
    library(ggalt)
    
    ggplot(df, aes(y=trt, x=l, xend=r)) + 
      geom_dumbbell(size=3, color="#e3e2e1", 
                    colour_x = "#5b8124", colour_xend = "#bad744",
                    dot_guide=TRUE, dot_guide_size=0.25) +
      geom_point(aes(l, NA, color = "x"), na.rm = TRUE) +
      geom_point(aes(r, NA, color = "xend"), na.rm = TRUE) +
      scale_color_manual(values = c(x = "#5b8124", xend = "#bad744"), labels = c(x = "x", xend = "xend")) +
      labs(x=NULL, y=NULL) +
      theme_minimal() +
      theme(panel.grid.major.x=element_line(size=0.05)) +
      theme(panel.grid.major.y=element_blank())
    

    reprex package (v2.0.0) 于 2021 年 6 月 2 日创建

    【讨论】:

    • 太棒了!它完美地工作!非常感谢您,很抱歉没有在问题中提供示例数据,这对所有这些来说仍然是新的。边走边学!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-06-10
    • 1970-01-01
    • 1970-01-01
    • 2020-01-18
    • 2019-08-28
    • 2018-07-08
    相关资源
    最近更新 更多