简体   繁体   中英

Split axis plot in ggplot2

I just found this plot in Factfulness (book by Hans Rosling and his children). I find the aestetics of the split quite appealing.

在此处输入图像描述

While it's possible to make something similar using geom_rect() , it's a quite different look. Another approach would be to use cowplot or patchwork but quite tricky. Here's as far as I got trying to replicate the top part with

gapminder %>% 
  filter(year==1997, gdpPercap<16000) %>%
  ggplot(aes(gdpPercap, y=lifeExp, size=pop)) +
  geom_point(alpha=0.5)+
  scale_x_log10()+
  ggthemes::theme_base()+
  theme(legend.position = "none",
        plot.background = element_blank(),
        plot.margin = unit(c(0.5, 0, 0, 0), "cm")) -> P1

gapminder %>% 
  filter(year==1997, gdpPercap>16000) %>%
  ggplot(aes(gdpPercap, y=lifeExp, size=pop)) +
  geom_point(alpha=0.5)+
  scale_x_log10()+
  ggthemes::theme_base()+
  theme(legend.position = "none",
        axis.title.y = element_blank(),
        axis.ticks.y = element_blank(),
        axis.text.y = element_blank(),
        plot.background = element_blank(),
        plot.margin = unit(c(0.5, 0.5, 0, 0), "cm"),
        axis.title.x = element_blank()) -> P2

cowplot::plot_grid(P1, P2, rel_widths = c(2,1), labels = NULL,
                   align = "h")

在此处输入图像描述

I think al the rest of the text and highlights are possible with existing packages. I am wondering what's the way to get a common x axis (the right side should display the ticks according to the ). Ideally, the x axis title would be centered but that might be too much to ask. I can also move it inside as text.

There are problems with axes, as you can see in the plot with y ticks. I wonder if facets would be a better approach. I am also not sure if the point sizes is wrongly calculated because I filter the data first.

在此处输入图像描述

Here is a solution using facets. You can solve the x-axis breaks problem by precomputing the breaks using the scale package's log10 break calculator. You could use a mutate() in the pipeline to make a new variable that splits the facets.

library(tidyverse)
library(gapminder)

breaks <- scales::log10_trans()$breaks(range(gapminder$gdpPercap), n = 6)

gapminder %>% 
  filter(year==1997) %>%
  mutate(facet = factor(ifelse(gdpPercap > 16000, "High", "Low"),
                        levels = c("Low", "High"))) %>%
  ggplot(aes(gdpPercap, y=lifeExp, size=pop)) +
  geom_point(alpha=0.5)+
  scale_x_log10(breaks = breaks)+
  ggthemes::theme_base()+
  facet_grid(~ facet, 
             scales = "free_x", space = "free_x") +
  ggtitle("My title") +
  theme(legend.position = "none",
        plot.title = element_text(hjust = 0.5),
        plot.background = element_blank())

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM