1

I do not like the colors in my chart that the code below produces.

How do I adapt the code, in order to change the array of colors used within the chart?

ggplot(Rating, aes(x = Function, y = Freq, fill = Rating)) + 
  ggtitle("Test")  + 
  labs(x="Function", y = "Rating") +
  geom_col() +
  theme_bw()
Richard Telford
  • 9,558
  • 6
  • 38
  • 51
Jed
  • 331
  • 2
  • 11
  • Hello Jed, welcom to SO. You will certainly attract more people to look at your question, if you deliver a [minimal, reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example/5963610#5963610). You will find solutions to your question at many places, one could be [here](http://www.sthda.com/english/wiki/ggplot2-colors-how-to-change-colors-automatically-and-manually) – MarBlo Jul 18 '20 at 11:31
  • 1
    You might find it useful to look at the `scale_fill_*()` functions, for example `scale_fill_distiller()`. – teunbrand Jul 18 '20 at 11:31

1 Answers1

2

This is quite a general question, so there are quite a few answers, here. Generally, you change the colors used in the plot via one of the scale_*_** functions, where * is the aesthetic (color, fill, etc), and ** is the type or method for creating the scale. Some of these include:

  • manual for manually defining stuff
  • brewer to use one of the predefined Brewer color palettes
  • discrete for discrete scales
  • gradient, gradient2 or gradientn to define color gradients (you give some set number of colors and a gradient is created to apply to a continuous variable for the aesthetic).
  • viridis to use the viridis scales. There are discrete and continuous versions here, so you typically need to specify
  • and many others... like distiller, fermenter, and various others that come with RColorBrewer.

Here's some examples below to get you started. Here's a default plot:

p <- ggplot(mtcars, aes(x=factor(carb), y=mpg)) + geom_col(aes(fill=factor(carb)))
p

enter image description here

Example applying one of the Brewer scales:

p + scale_fill_brewer(palette='Set1')

enter image description here

Example using a viridis scale:

p + scale_fill_viridis_d()

enter image description here

Example using a manually-defined scale: Note here you specify using scale_fill_manual(values=...). The values= argument must be sent a vector or list of colors which are at least the same number as the number of levels for your variable assigned to the fill= aesthetic. You can also pass a named vector to explicitly define which color is applied to individual factor levels. Here I'm just showing you the lovely colors of the rainbow:

p + scale_fill_manual(values=rainbow(6))

enter image description here

chemdork123
  • 12,369
  • 2
  • 16
  • 32