Home > Back-end >  ggplot2 custom scale color labels
ggplot2 custom scale color labels

Time:07-12

I have

norm.values<-data.frame(x=rnorm(100), y=rnorm(100), col=rnorm(100), size=sample(c(1,2,3), 100, replace = T))

ggplot(norm.values , aes(x=x, color=col, y=y))   
  geom_point(aes(shape=factor(size)), size=3 )   
  scale_color_gradient2(low="blue",mid="blue", high="red")   
  xlab("chi lab")   
  ylab("psi lab")  
  labs(color = "Kolor Lab" ) 
  labs(shape = "Size Lab", size=20)  
  theme_classic()  
  theme(axis.text=element_text(size=14), axis.title=element_text(size=16), legend.text=element_text(size=18), strip.text.x = element_text(size = 14), strip.text.y = element_text(size = 14),  legend.title =   element_text(size = 18))

In the color legend Kolor Lab I would like the label for red to be >2instead of 2 . Is this possible?

CodePudding user response:

Yes, you can use the labels argument in your color scale. Just make sure you have a matching breaks argument too.

ggplot(norm.values, aes(x, y, color = col))   
  geom_point(aes(shape = factor(size)), size = 3)   
  scale_color_gradient2(low = "blue", mid = "blue", high = "red",
                        breaks = seq(-2, 2), labels = c(-2, -1, 0, 1, ">2"))  
  labs(shape = "Size Lab", x = "chi lab", y = "psi lab", color = "Kolor")  
  theme_classic(base_size = 16)  
  theme(legend.text = element_text(size = 18, hjust = 1))

enter image description here

CodePudding user response:

Just add the breaks and labels argument of scale_color_gradient2:

ggplot(norm.values , aes(x=x, color=col, y=y))   
  geom_point(aes(shape=factor(size)), size=3 )   
  scale_color_gradient2(low="blue",mid="blue", high="red",
                       breaks=c(2,1,0,-1,-2),
                       labels = c(">2", "1", "0", "-1", "-2")) 
  xlab("chi lab")   
  ylab("psi lab")  
  labs(color = "Kolor Lab" ) 
  labs(shape = "Size Lab", size=20)  
  theme_classic()  
  theme(axis.text=element_text(size=14), axis.title=element_text(size=16), legend.text=element_text(size=18), strip.text.x = element_text(size = 14), strip.text.y = element_text(size = 14),  legend.title =   element_text(size = 18))


enter image description here

  • Related