An alternative approach (not necessarily better than the previous answers!) is to use the viridis
package. As explained here, it allows for a variety of color gradients that are based on more than two colors.
The package is pretty easy to use - you just need to replace the ggplot2
scale fill function (e.g., scale_fill_gradient(low = "skyblue", high = "dodgerblue4")
) with the equivalent viridis
function.
So, change the code for this plot:
ggplot(mtcars, aes(wt*1000, mpg)) +
geom_point(size = 4, aes(colour = hp)) +
xlab("Weight (pounds)") + ylab("Miles per gallon (MPG)") + labs(color='Horse power') +
scale_x_continuous(limits = c(1000, 6000),
breaks = c(seq(1000,6000,1000)),
labels = c("1,000", "2,000", "3,000", "4,000", "5,000", "6,000")) +
scale_fill_gradient(low = "skyblue", high = "dodgerblue4") +
theme_classic()
Which produces:

To this, which uses viridis
:
ggplot(mtcars, aes(wt*1000, mpg)) +
geom_point(size = 4, aes(colour = factor(cyl))) +
xlab("Weight (pounds)") + ylab("Miles per gallon (MPG)") + labs(color='Number\nof cylinders') +
scale_x_continuous(limits = c(1000, 6000),
breaks = c(seq(1000,6000,1000)),
labels = c("1,000", "2,000", "3,000", "4,000", "5,000", "6,000")) +
scale_color_viridis(discrete = TRUE) +
theme_classic()
The only difference is in the second to last line: scale_color_viridis(discrete = TRUE)
.
This is the plot that is produced using viridis
:

Hoping someone finds this useful, as its the solution I ended up using after coming to this question.