Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot to display same colors for factor levels [duplicate]

Tags:

r

ggplot2

How can I get ggplot to always utilize the same color mapping for a factor. For instance:

library(ggplot)

## Filter for visual simplification
diamonds2 <- diamonds[1:10,]
ggplot(diamonds2, aes(carat, price, color = cut)) + geom_point()

## Now filtering removes some levels of cut
diamonds3 <- diamonds[1:5,]
ggplot(diamonds3, aes(carat, price, color = cut)) + geom_point()

In the first scatterplot factor level "Fair" is red. In the second graph the factor level "Good" became red. I want the mapping to be preserved regardless of whether the filtering removes factor levels so that "Fair" is always mapped to red and so on.

In reality my ggplot is a lot more complex. My original factor has 11 levels.

MyPalette <- c("#5DD0B9", "#E1E7E9", "#1f78b4", "#a6cee3",  "#de77ae", "#c51b7d", "#8e0152", "#6a3d9a", "#fbdf6f", "#ff7f00", "#fff99")

which I refer to in ggplot

... scale_fill_manual(values = MyPalette, name="") + ...

plot1 plot2

like image 681
Thomas Speidel Avatar asked Dec 18 '22 19:12

Thomas Speidel


1 Answers

Just use a named vector for MyPalette and scale_colour_manual():

MyPalette <- c(Fair = "#5DD0B9", Good = "#E1E7E9", "Very Good" = "#1f78b4", Premium =  "#a6cee3", Ideal = "#de77ae")

ggplot(diamonds2, aes(carat, price, color = cut)) + geom_point() +
  scale_colour_manual(values = MyPalette)

ggplot(diamonds3, aes(carat, price, color = cut)) + geom_point() +
  scale_colour_manual(values = MyPalette)

enter image description here

enter image description here

like image 199
Stibu Avatar answered Mar 24 '23 18:03

Stibu