Hurlikus
Hurlikus

Reputation: 419

Ggplot2: how to set color for a single value and leave the others to auto color

I use line graphs that I made with the ggplot2 package. My question now: How can I define a color for a single value and leave the rest to "auto color"?

The graph I'm talking about: Graph (link to imgur)

What I want is for the "Summe" to be black and for the rest to stay the same.

The code for the graph:

ggplot(data = ICU_Cephalosporine_SU_Per100PatientDays_norest_nototal_long, aes(x = Monat, y = `SUs pro 100 Pflegetage`, colour = `API`, group = API)) + geom_line(size = 1) + geom_point(size = 2)

What I have tried to add:

+ scale_colour_manual(values = c(name = "Summe", values = "#000000"))

and

+ scale_colour_manual(values = c("Summe" = "#E08214"))

The first resultet in the error:

Error: Insufficient values in manual scale. 4 needed but only 2 provided.

And the second one:

Error: Insufficient values in manual scale. 4 needed but only 1 provided.

I'm not able to find the solution, does anybody have an idea how I'm able to do this?

EDIT: I created some sample data and applied my new findings so far:

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


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)

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)

My new problem is, that now "A" is not beeing displayed in the legend anymore. Why? The data was subset after the aes()?!

Upvotes: 5

Views: 2323

Answers (1)

Erich Neuwirth
Erich Neuwirth

Reputation: 1031

This is the standard palette ggplot uses (from this answer)

gg_color_hue <- function(n) {
  hues = seq(15, 375, length = n + 1)
  hcl(h = hues, l = 65, c = 100)[1:n]
}

You can do something like

pal <- gg_color_hue(4)
pal[4] <- "#E08214"
ggplot(...) +
   ... +
   scale_color_manual(values=pal)

Upvotes: 2

Related Questions