How to modify the color of data using multiple variables

548 Views Asked by At

So I'm trying to work with some data where I am comparing countries and years on a scatterplot of income vs. infant_mortality across different African regions. I know how to use the color function in ggplot to differentiate based on region - what I'd like to do is then change the brightness or darkness of those various regional colors based on year i.e. if points from countries in Southern Africa are blue, then can those points from 1970 be dark blue and those from 2010 be light blue? Right now I'm doing region by color and year by shape, but I think if I could vary it by darkness/lightness of base color that would be more intuitive visually. Below is the code I'm working with:

library(dplyr)
library(ggplot2)
library(dslabs)
data(gapminder)

gapminderfirst <- gapminder %>% filter(continent == "Africa" & year %in% c(1970, 2010) & !is.na(gdp) & !is.na(population) & !is.na(infant_mortality)) %>% mutate(dollars_per_day = gdp/population/365)

gapminderfirst$year <- cut(gapminderfirst$year, breaks=c(1950, 2000, 2100), labels=c('1970', '2010'))

gapminderfirst %>% ggplot(aes(dollars_per_day, infant_mortality, color = region, shape = country)) + scale_x_continuous(trans = "log2") + geom_point(size = 3) + geom_text(nudge_x = 0.2) + theme(legend.position = c(0.8, 0.8), legend.key.size = unit(0.25, "cm"))
1

There are 1 best solutions below

0
Allan Cameron On

If you want something a bit more sophisticated than using the alpha scale, you can use the ggnewscale package to create a different color scale for 1970 and 2010.

First, let us define some matching light and dark colors:

base_colors <- scales::hue_pal()(5)
dark_colors <- colorspace::darken(base_colors, 0.3)
lite_colors <- colorspace::lighten(base_colors, 0.3)

And the plotting code would be something like this:

gapminderfirst %>% 
  filter(year == "1970") %>%
  ggplot(aes(dollars_per_day, infant_mortality, color = region)) + 
  geom_point(size = 3) + 
  scale_color_manual(values = dark_colors, name = "1970") +
  ggnewscale::new_scale_color() +
  geom_point(data = filter(gapminderfirst, year == "2010"),
            aes(color = region), size = 3) + 
  scale_color_manual(values = lite_colors, name = "2010") +
  scale_x_continuous(trans = "log2") + 
  theme(legend.position = c(0.8, 0.8), 
        legend.key.size = unit(0.25, "cm")) +
  theme_minimal(base_size = 16)

enter image description here