【问题标题】:Color legend with geom_text_repel and geom_point带有 geom_text_repel 和 geom_point 的颜色图例
【发布时间】:2020-09-23 15:55:36
【问题描述】:

如何为图例标签旁边的点着色? scale_color_manual 或 scale_fill_manual 不起作用。另外,如何将图例中的点更改为正方形?谢谢

set.seed(1)
library(ggplot2)
library(ggrepel)
df <- data.frame(n=runif(8),y=1:8,l=letters[1:8],col=palette.colors(8))

p_vol <- ggplot(df, aes(n, y, label = l)) +
  geom_point(aes(fill=l),color = df$col) +
  geom_text_repel(col=df$col)+theme_classic()
print(p_vol)

【问题讨论】:

    标签: r ggplot2 legend ggrepel geom-point


    【解决方案1】:

    您需要在geom_point() 的审美调用中包含颜色参数,设置为color = l。然后您可以使用scale_color_manual 来使用所需的颜色。

    p_vol <- ggplot(df, aes(n, y, label = l)) +
      geom_point(aes(fill=l, color = l)) +
      geom_text_repel(col=df$col) +
      theme_classic() +
      scale_color_manual(values = df$col)
    

    【讨论】:

    • 不建议在ggplot内调用带有df$的列。建议将col 列重命名为colors 或其他一些非参数。
    【解决方案2】:

    您也可以尝试使用数据框中的颜色从aes() 启用fill。这里的代码,我使用了不同的颜色,因为我对你曾经有颜色的函数palette.colors 没有足够的了解。还使用scale_fill_identity() 直接从数据中的变量中获取颜色(那些在fill 中定义)。代码如下:

    set.seed(1)
    library(ggplot2)
    library(ggrepel)
    library(RColorBrewer)
    df <- data.frame(n=runif(8),y=1:8,l=letters[1:8],col=rainbow(8))
    #Plot
    ggplot(df, aes(n, y, label = l,color=l,fill=col)) +
      geom_point() +
      geom_text_repel(show.legend = F)+theme_classic()+
      scale_fill_identity()
    

    输出:

    【讨论】:

    • 我发现填充不是必需的,实际上 scale_fill_identity() 即使没有填充也使用标准的ggplot颜色,而不是数据框中的颜色
    猜你喜欢
    • 1970-01-01
    • 2022-01-02
    • 1970-01-01
    • 2022-06-22
    • 2011-05-12
    • 2021-06-26
    • 2020-07-20
    • 2018-02-15
    • 1970-01-01
    相关资源
    最近更新 更多