Using custom colors.
Welcome to Day 27
By now, I hope you’re confident enough to try new geoms and feel comfortable with the ones we’ve explored so far in this series. Today, we’ll take a step further by learning how to customize colors beyond the default options in R.
Our goal? To go beyond the basics and make your plots stand out! By Jumping Off Default Colors
Let’s start with the default color scheme in a box plot:
library(tidyverse)
library(palmerpenguins)
penguins %>%
drop_na(sex) %>%
ggplot(aes(x = species, y = body_mass_g, fill = sex)) +
geom_boxplot() +
theme_classic()
In this code, we get the default color palette for the sex
groups. Now, suppose we want to use specific colors. Recently, someone asked me how to do this, and it’s quite simple with just one line of code:
penguins %>%
drop_na(sex) %>%
ggplot(aes(x = species, y = body_mass_g, fill = sex)) +
geom_boxplot() +
scale_fill_manual(values = c("darkgreen", "maroon")) +
theme_classic()
Adding Custom Colors: Notice that I specified two colors wrapped in quotes and placed them inside c()
for the values argument in scale_fill_manual()
. This overrides the default colors, giving us control over the palette.
You can use named colors (like “darkgreen” and “maroon”) or hex codes (e.g., “#1b7837”). To find color names, consult the R color list, or search for hex codes using Google.
c()
When using more than one color, combine them in c()
, which stands for “concatenate.
” It’s a commonly used function in R for combining elements, and it’s essential when setting multiple colors.
Even if you’re using a single custom color, you must include it within the values
argument to apply it.
Be sure to match the number of colors to the number of groups in your data. For instance, in this example, we dropped any NA values for sex, so we have two groups (male and female) and only need two colors. However, if we grouped by island (which has three categories), we’d need three colors. If you try it with only two colors, you’ll get an error indicating the mismatch.
That’s it for today! Try customizing colors in your plots, experiment with different combinations, and let me know how it goes.
For attribution, please cite this work as
Soundararajan (2024, Oct. 27). My R Space: Day 27 of viz with me. Retrieved from https://github.com/soundarya24/SoundBlog/posts/2024-10-27-day-27-of-viz-with-me/
BibTeX citation
@misc{soundararajan2024day, author = {Soundararajan, Soundarya}, title = {My R Space: Day 27 of viz with me}, url = {https://github.com/soundarya24/SoundBlog/posts/2024-10-27-day-27-of-viz-with-me/}, year = {2024} }