• python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Facebook Twitter Instagram
Devs Fixed
  • python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Devs Fixed
Home ยป Resolved: Grab both legend colors and legend labels from a data frame

Resolved: Grab both legend colors and legend labels from a data frame

0
By Isaac Tonny on 17/06/2022 Issue
Share
Facebook Twitter LinkedIn

Question:

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()) [/code]

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?

Answer:

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) [/code]

If you have better answer, please add a comment about this, thank you!

ggplot2 r
Share. Facebook Twitter LinkedIn

Related Posts

Resolved: significance letter above bar graphic in wrong order

01/04/2023

Resolved: VBA – Applying border around the areas with value/text

01/04/2023

Resolved: How can I implement a function depending on picked up items?

01/04/2023

Leave A Reply

© 2023 DEVSFIX.COM

Type above and press Enter to search. Press Esc to cancel.