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