user7280624
user7280624

Reputation: 15

Color legend with geom_text_repel and geom_point

how can be colored the dots next to the legend labels? scale_color_manual or scale_fill_manual do not work. Also how can I change the dots in the legend to squares? Thanks

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)

enter image description here

Upvotes: 0

Views: 1047

Answers (2)

Duck
Duck

Reputation: 39613

Also you can try enabling fill from aes() using the colors you have in your dataframe. Here the code, I have used different colors because I do not have enough knowledge about the function palette.colors you used to have the colors. Also using scale_fill_identity() takes the colors directly from the variable in your data (Those defined in fill). Here the code:

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()

Output:

enter image description here

Upvotes: 1

bradisbrad
bradisbrad

Reputation: 131

You're going to need to include the color argument within the aesthetic call in geom_point(), setting color = l. Then you can use scale_color_manual to use the desired colors.

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)

Upvotes: 1

Related Questions