Home > front end >  How can I change legend labels in ggplot?
How can I change legend labels in ggplot?

Time:02-18

I am trying to change Control to 0%Shade in a ggplot legend. Any advice on how to do this without it disagreeing with all other plot settings?

Predictive Plot

pred_plot <- ggplot(pred, aes(x, predicted, color=group, fill=group))  
  geom_line()   geom_ribbon(aes(ymin = conf.low, ymax = conf.high), alpha = 0.1, colour=NA)  
  labs(x = 'Ambient Temp (C)', y = "Predicted Deer Use")  
  scale_x_continuous(breaks = round(seq(min(pred$x), max(pred$x), by = 5),1), labels=scales::label_number(accuracy = 1))   
  theme(axis.text=element_text(size=30, colour='black'),axis.title=element_text(size=30,face="bold"))  
  theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
        panel.background = element_blank(), axis.line = element_line(colour = "black")) 
  theme(legend.position="bottom", legend.box = "horizontal", legend.title = element_blank(), legend.key = element_blank(),
        legend.key.size = unit(4, 'cm'),legend.text = element_text(size=20))   
  transition_reveal(x) 

CodePudding user response:

You can do that via the labels= argument in a scale_color_*() function by supplying a named vector. Here's an example:

library(ggplot2)

set.seed(1235)
df <- data.frame(x=1:10, y=1:10, z = sample(c("Control", "B", "C"), size=10, replace=TRUE))

df$z <- factor(df$z, levels=c("Control", "B", "C"))  # setting level order

p <- ggplot(df, aes(x,y, color=z))   geom_point(size=4)
p

enter image description here

To change the name of "Control" totally "in plot code", I'll use scale_color_hue(labels=...). Note that by default, ggplot2 uses an evenly-spaced hue scaling, so this keeps the colors themselves the same. Using a named vector is not required, but a good idea to ensure you don't have mixing up of names/labels:

p   scale_color_hue(labels=c("Control" = "A", "B"="B", "C"="C"))

enter image description here

  • Related