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="") + ...
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With