Facet grid in R

Viewed 36

I'm trying to reproduce a plot by using the gapminder data. I'm getting an error Error: Discrete value supplied to continuous scale

Below is my code:

my_gapminder <- gapminder %>%
  # filter observations were the country is either Africa, Asia or Europe
  filter(continent %in% c("Africa", "Asia", "Europe")) %>%
  # compute mean country population per continent and year
  group_by(continent, year) %>%
  summarize(mean_pop = mean(pop)) %>%
  ungroup() %>%
  # compute population growth as relative difference to continent population
  # in 1958
  group_by(continent) %>%
  mutate(rel_pop_growth = (mean_pop - mean_pop[1]) / mean_pop[1]) %>%
  ungroup()
ggplot(my_gapminder, aes(x = continent, y = rel_pop_growth, fill = continent)) +
  # add barchart geom
  geom_col() +
  # divide data into subplots by continent
  facet_wrap(~ continent, nrow = 1) +
  # label y-axis text in percentage format
  scale_y_continuous(labels = scales::percent) +
  # add continuous fill color scale from gray to purple
  scale_fill_continuous(low = "gray80", high = "purple4") +
  # remove fill colorbar
  guides(colour = FALSE) +
  # add y-axis and plot titles
  labs(x = NULL, y = "Avg. Population Growth",
       title = "Avg. Population Growth per Continent, 1958-2007")

Would like to know the corrections.

Desired plot

enter image description here

1 Answers

I think your x-axis should be year and fill should be rel_pop_growth to get the plot similar to your desired plot.

library(gapminder)
library(ggplot2)

ggplot(my_gapminder, aes(x = year, y = rel_pop_growth, fill = rel_pop_growth)) +
  # add barchart geom
  geom_col() +
  # divide data into subplots by continent
  facet_wrap(~ continent, nrow = 1) +
  # label y-axis text in percentage format
  scale_y_continuous(labels = scales::percent) +
  # add continuous fill color scale from gray to purple
  scale_fill_continuous(low = "gray80", high = "purple4") +
  # remove fill colorbar
  guides(fill = FALSE) +
  # add y-axis and plot titles
  labs(x = NULL, y = "Avg. Population Growth",
       title = "Avg. Population Growth per Continent, 1958-2007")

enter image description here

Related