Changing ggplot colors with scale_color_brewer

Bruno Ponne ● 22 Feb 2023


  • Medium
  • R
  • 5 min

What you will learn

  • Learn to transform data from wide to long format with tidyr;
  • Be able to choose a different color palette with RColorBrewer;

Table of Contents


Introduction


‘War is over, if you want it, war is over, now’

John Lennon


Ever visited a webpage with clashing colors or poor text contrast? You’re not alone! Choosing the perfect color palette for data visualizations can be complex.


Fortunately R offers you several libraries made by professional designers that offer excellent color palettes for you. In this lesson, you will learn about one of these libraries, the RColorBrewer package. To make things more interesting, we’ll use data from the military expenses of leading capitalist countries during the Cold War era. Let’s paint your data story!




Data source

Data used in this lesson is available on the World Bank website.





Coding the past: change colors in ggplot with RColorBrewer

1. Importing data into R


Download the data file here and load the libraries we will need, according to the code below. To read the data, use the R function read_csv(). Additionally, we are only interested in the five first rows and in columns 3 and 5 to 36. They are selected with [1:5, c(3, 5:36)].


content_copy Copy

library(readr)
library(tidyr)
library(dplyr)
library(ggplot2)
library(RColorBrewer)

military <- read_csv('military.csv')[1:5, c(3, 5:36)]




2. How to use pivot_longer?


If you take a look at the dataframe you just loaded, you will see that it has one column for each year. To use ggplot your data has to be tidy. According to Hadley Wickham, in a tidy dataframe:


  1. Each variable must have its own column;
  2. Each observation must have its own row;
  3. Each value must have its own cell;
tips_and_updates  
Learn more about tidy data and how to transform a dataframe from wide to long format here.


To make our data tidy, we will transform all the year columns in one variable called “year” and we will also transfer the values contained in these columns to a single new variable called “expense”. Note the syntax of the pivot_longer function. The first argument is the dataframe we want to transform, the second are the columns we would like to treat. Finally, names_to indicates the name of the new column that will receive the years and values_to indicates the name of the new column that will receive the values of the year columns.


Conversion of an R dataframe from wide to long format with pivot_longer

Illustration created by the Author


The mutate function makes two adjustments in the new long dataset. First, it eliminates the second part of the year names, e.g., [YR1960]. Second, it rounds the expenses values to two decimal places.


Finally, we change the names of the columns (variables) in our dataset.


content_copy Copy

military_long <- pivot_longer(military, 
                              '1960 [YR1960]':'1991 [YR1991]', 
                              names_to = 'year', 
                              values_to = 'expense') %>%
  mutate(year = substr(year, 1, 4), expense = round(expense, 2))

names(military_long) <- c('country', 'year', 'expense')




3. Using scale_color_brewer to improve your plots’ colors


To see all the colors palettes the RColorBrewer offers, use the following code:


content_copy Copy

par(mar=c(3,4,2,2))
display.brewer.all()


RColorBrewer available palettes



We will be using palette Set1 in our line plot. To set it, add the layer scale_color_brewer(palette = 'Set1'). Note that we also set the x-axis to have labels every 4 years with scale_x_discrete(breaks = seq(1960, 1990, by=4)). Color and group aesthetics were mapped to countries so that each country has a different color.


content_copy Copy

ggplot(data = military_long, aes(x = year, y = expense, group = country, color = country))+
  geom_line(size = 1)+
  scale_x_discrete(breaks = seq(1960, 1990, by=4))+
  scale_color_brewer(palette = 'Set1')+
  xlab('Year')+
  ylab('Military expenditure (% of GDP)')+
  ggtitle('Military Expenses of the Main Capitalist Economies',
          subtitle = '1960 - 1991')


plot using RColorBrewer palette





4. Adding a theme to the plot


To customize our plot, we will use the ggplot theme developed in the lesson ‘Climate data visualization’. Small adjustments were made to adapt the theme to this plot. For instance, the legend position was set to be at the bottom of the plot and its title was deleted.


content_copy Copy

ggplot(data = military_long, aes(x = year, y = expense, group = country,color = country))+
geom_line(size = 1)+
scale_x_discrete(breaks = seq(1960, 1990, by=4))+
scale_color_brewer(palette = 'Set1')+
  xlab('Year')+
  ylab('Military expenditure (% of GDP)')+
  ggtitle('Military Expenses of the Main Capitalist Economies',
          subtitle = '1960 - 1991')+
  theme_bw()+
  guides(color = guide_legend(title=''))+
  theme(text=element_text(color = 'white'),
            # Changes panel, plot and legend background to dark gray:
            panel.background = element_rect(fill = '#2E3031'),
            plot.background = element_rect(fill = '#2E3031'),
            legend.background = element_rect(fill='#2E3031'),
            legend.key = element_rect(fill = '#2E3031'),
            # Changes legend texts color to white:
            legend.text =  element_text(color = 'white'),
            legend.title = element_text(color = 'white'),
            # Changes color of plot border to white:
            panel.border = element_rect(color = 'white'),
            # Eliminates grids:
            panel.grid.minor = element_blank(),
            panel.grid.major = element_blank(),
            # Changes color of axis texts to white
            axis.text.x = element_text(color = 'white'),
            axis.text.y = element_text(color = 'white'),
            axis.title.x = element_text(color= 'white'),
            axis.title.y = element_text(color= 'white'),
            # Changes axis ticks color to white
            axis.ticks.y = element_line(color = 'white'),
            axis.ticks.x = element_line(color = 'white'),
            legend.position = "bottom")


Plot with new theme and color selected with scale_color_brewer


Feel free to test other color palettes and check the one you like the most!




Conclusions

  • You can transform your dataframe from wide to long format using pivot_longer;
  • RColorBrewer offers color palettes to make your plots more effective and beautiful.



Comments

There are currently no comments on this article, be the first to add one below

Add a Comment

If you are looking for a response to your comment, either leave your email address or check back on this page periodically.