Home > Software design >  Grab both legend colors and legend labels from a data frame
Grab both legend colors and legend labels from a data frame

Time:06-17

I have already read enter image description here

I would like to change the legend labels so that they are A, B, C, and D according to how they are in the data frame. How do I do this?

CodePudding user response:

You're still setting up your data the way you would in base plotting. Your data.frame should just have the factor you want to have colors for, with the correct levels already there. Then use a scale to change the colors palette, separate from the data itself.

Here is the ggplot way:

library(ggplot2)

set.seed(30)

df <- data.frame(
  x = runif(5000),
  y = runif(5000),
  color = sample(x = c('A', 'B', 'C', 'D'),
                 size = 5000,
                 replace = TRUE)
)

my_colors <- c(A = "#E41A1C", B = "#377EB8", C = "#4DAF4A", D = "#984EA3")

ggplot(df, aes(x = x, y = y, color = color))   
  geom_point()  
  scale_color_manual(values = my_colors)
  
  • Related