geom_text_repel 和 geom_point 的颜色图例

Color legend with geom_text_repel and geom_point

如何为图例标签旁边的点着色? 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)

您需要在 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)

您也可以尝试使用数据框中的颜色从 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()

输出: