Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Grab both legend colors and legend labels from a data frame

I have already read specify legend colors and labels from columns of data frame, but for this linked question, the colors are not pre-specified as in the one I am asking here.

In this data frame, I have prespecified colors and labels for the legend:

library(ggplot2)

set.seed(30)

df <- data.frame(
  x = runif(5000),
  y = runif(5000),
  color = sample(x = c("#E41A1C", "#377EB8", "#4DAF4A", "#984EA3"),
                 size = 5000,
                 replace = TRUE)
)

df <- within(df, {
  legend_label <- NA
  legend_label[color == "#E41A1C"] <- "A"
  legend_label[color == "#377EB8"] <- "B"
  legend_label[color == "#4DAF4A"] <- "C"
  legend_label[color == "#984EA3"] <- "D"
})

ggplot(df, aes(x = x, y = y, color = color)) + 
  geom_point() + 
  scale_color_identity(guide = guide_legend())

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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)
  
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading