Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ggplot2: Changing the color for a single value

Tags:

r

ggplot2

I'm trying to create a line plot with ggplot and I want to set the color for one of the values as black and leave the rest to default. I need to create multiple line plots with this code, and only the values (here "A") stays the same across all the plots.

My problem: I managed it somehow, but my problem now is, that the value is not beeing displayed in the legend with the others anymore. How can I make it appear there again?

mydata <- data.frame("Letter" = c("A", "B", "C", "D", "A", "B", "C", "D", "A", "B", "C", "D",
"A", "B", "C", "D"), "Month" = c("Jan", "Jan", "Jan", "Jan", "Feb", "Feb", "Feb", "Feb",
"Mar", "Mar", "Mar", "Mar", "Apr", "Apr", "Apr", "Apr"), "Number" = c(1, 2, 3, 4, 4, 5, 1, 3,
6, 4, 2, 4, 1, 2, 5, 7))

This plot is how I would like it, but "A" is not beeing displayed in the legend.

ggplot(data = mydata, aes(x = Month, y = Number, colour = Letter, group = Letter))
+ theme(legend.position="bottom", legend.title = element_blank())
+ geom_line(data=subset(mydata, Letter == "A"), colour="black", size = 1)
+ geom_line(data=subset(mydata, Letter != "A"), size = 1)
+ geom_point(data=subset(mydata, Letter == "A"), colour="black", size = 1.5)
+ geom_point(data=subset(mydata, Letter != "A"), size = 1.5)

"A" is beeing displayed in the legend, but it's line / dots is not black.

ggplot(data = mydata, aes(x = Month, y = Number, colour = Letter, group = Letter))
+ theme(legend.position="bottom", legend.title = element_blank())
+ geom_line()
+ geom_point(size = 1.5)

Does anybody know how to solve this?

like image 337
Hurlikus Avatar asked Apr 27 '26 09:04

Hurlikus


1 Answers

#show the three colors of the ggplot default
library(scales)
show_col(hue_pal()(3))

#set colors
group.colors <- c(A = "#000000", B = "#F8766D", C = "#00BA38", D = "#619CFF" )

#plot
library( ggplot2)
ggplot(data = mydata, aes(x = Month, y = Number, colour = Letter, group = Letter)) + 
  theme(legend.position="bottom", legend.title = element_blank()) +
  geom_line( data = mydata, size = 1 ) + 
  geom_point(data = mydata, size = 1.5 ) +
  scale_colour_manual( values= group.colors )  # <-- set the chosen colors

enter image description here

like image 188
Wimpel Avatar answered Apr 30 '26 00:04

Wimpel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!