【问题标题】:ggplot2无法为图例图标着色
【发布时间】:2022-01-08 20:05:41
【问题描述】:

我正在尝试使用 ggplot2 使用数据框 (df) 中的值制作某种时间线。我已经成功地按照我想要的方式绘制数据(不同颜色的线段以这个确切的顺序连接 x 标记,即从左到右:'early'、'unknown'、'late'、'sub ')。数据框中的startpointendpoint 列用于定义点和线段的位置。

问题是图例没有显示“x”图标的颜色,它们只是灰色。我尝试添加 scale_color_manual()scale_fill_manual() 命令,但它们似乎没有改变任何东西。当我将形状更改为shape = 21 时,图例会显示正确的颜色,但是,我真的希望形状为4(x 图标)。我不在乎图例的形状,但scale_shape_manual() 再次没有改变图例的任何内容。 我还尝试在ggplot()geom_segment() 和/或geom_point()aes() 参数内部和外部放置不同的color 参数。

如何使图例中的图标显示正确的颜色?

下面我添加了一段代码来重现问题。

library(ggplot2)
library(RColorBrewer)

## Define dataframe
df <- data.frame(Var = c("sub","late","unknown","early"),
                 Time = c(10,267,0,1256),
                 Endpoint = c(1533,1523,1256,1256),
                 Startpoint = c(1523,1256,1256,0))
colorscheme <- RColorBrewer::brewer.pal(9, "Set1")[c(1,4,2,3)]

## Make plot
  ggplot(df, aes(x="", y=Endpoint, fill=Var), color =colorscheme) +
  geom_segment( aes(x="", xend="", y=Startpoint, yend=Endpoint), color = colorscheme) +
  geom_point(aes(x="", y=Endpoint),size=5, shape=4 , color = colorscheme) +
  coord_flip()

提前感谢您的任何建议!

【问题讨论】:

    标签: r ggplot2 colors legend rscript


    【解决方案1】:

    您应该使用color 而不是fill。要从图例中删除线,请使用guides(color = guide_legend(override.aes = list(linetype = 0))) 或在geom_segment 中使用show.legend = F

    此外,ggplot 中传递的参数之后不需要重复。

    ggplot(df, aes(x="", y=Endpoint, color=Var), colorscheme) +
      geom_segment(aes(xend="", y=Startpoint, yend=Endpoint)) +
      geom_point(size=5, shape=4) +
      coord_flip() +
      guides(color = guide_legend(override.aes = list(linetype = 0)))
    
     #or
    
    ggplot(df, aes(x="", y=Endpoint, color=Var), colorscheme) +
      geom_segment(aes(xend="", y=Startpoint, yend=Endpoint)) +
      geom_point(size=5, shape=4) +
      coord_flip()
    

    【讨论】:

      【解决方案2】:

      试试这个:

      ggplot(df, aes(x = "", y = Endpoint, color = Var), colorscheme) +
        geom_segment(aes(x = "", xend = "", y = Startpoint, yend = Endpoint), show.legend = FALSE) +
        geom_point(aes(x = "", y = Endpoint), size = 5, shape = 4) +
        coord_flip()
      

      这样图例将只显示 X

      【讨论】:

        猜你喜欢
        • 2023-03-24
        • 1970-01-01
        • 1970-01-01
        • 2014-07-06
        • 2021-10-29
        • 2021-10-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多