0
votes

I have a time series where I would to visualise a percentage variabel and count variable. I would like the count plot to be bigger than the percentage plot. Putting the two plots together using ggpubr works, the problem is that x-axis does not align between the plots which makes it hard for a comparison. Any solution or workaround?

Example

    library(tidyverse)
    library(lubridate)
    library(scales)
    library(ggpubr)

    df <- data.frame(date       = rep(seq(ymd('2015-01-01'), ymd('2018-01-01'), by = '1 month'), 2),
                     percentage = c(runif(37, 0.6, 1), runif(37, 0.5, 0.9)),
                     count      = c(runif(74, 1000000000, 2000000000)),
                     id         = c(rep('A', 37), rep('B', 37)))


    p1 <- ggplot(df, aes(x = date, y = percentage, col = id)) + 
      geom_line() +
      scale_y_continuous(labels = percent)

    p2 <- ggplot(df, aes(x = date, y = count, col = id)) + 
      geom_line() +
      scale_y_continuous(labels = comma)

    ggarrange(p1, p2, nrow = 2, common.legend = TRUE, legend = 'right', heights = c(4, 1))
2

2 Answers

0
votes

Well you did ask for a workaround. This is a workaround to get you where you need to go quickly!

First, I made a labeling function that pads the percent with spaces on the left. It's actually a function that returns a function, which will be handy in your ggplot2 code.

label_fun <- function(width) {
  function(x) str_pad(percent(x), width, side = "left")
}

And then you can tinker with exactly what width you need to use, but it looks like this in the ggplot2 code itself:

p1 <- ggplot(df, aes(x = date, y = percentage, col = id)) + 
  geom_line() +
  scale_y_continuous(labels = label_fun(18))

(Everything else was the same.)

As a starting point, I checked the max length of your other labels:

nchar(comma(max(df$count))) # 13

That wasn't enough space, though, only because different characters are different widths (e.g. commas are super narrow obviously). So I tinkered from there. Using a function to make a function in this way made it super easy and fast to tinker. See results below.

enter image description here

0
votes

Apprentently, it just required one more argument

ggarrange(p1, p2, nrow = 2, common.legend = TRUE, legend = 'right', heights = c(4, 1), align = 'v')