ktmbiome
ktmbiome

Reputation: 183

ggplot2 : Color One Category Separately

I'm generating a scatterplot in which one of my categories is an "Other" category. I would like the other categories in my factor variable to be whatever color they are, but the "Other" category to be in gray. When I try to use the scale_color_manual() function, it gives me the error that I have too few categories. The example below uses the iris data.

data(iris)
p1 <- ggplot(iris, aes(x=Sepal.Length,y=Sepal.Width,color=Species)) + geom_point()
p1
p2 <- p1 + scale_color_manual(values=c("virginica"="gray"))
p2

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

Is it possible to just change the color of one category, regardless of the other values in the factor? I'd rather not select colors for all three categories, as the data that I'm actually working with has 30-40 categories, one of which is consistently "Other".

Upvotes: 3

Views: 2118

Answers (1)

HubertL
HubertL

Reputation: 19544

based on this post you can get ggplot colors with this function:

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

So in your case :

cols = gg_color_hue(length(levels(iris$Species)))

Then you reprogramm the color you want to change and use it for your plot:

cols[levels(iris$Species)=="virginica"]="gray"
p2 <- p1 + scale_color_manual(values=cols)

enter image description here

Upvotes: 3

Related Questions