Lena
Lena

Reputation: 41

How do you spread out a specific part of the x-axis in ggplot2?

I have a dataframe:

df <- data.frame(tw = rep(c(1:30), each = 3),
                 name = rep(c("spec1", "spec2", "spec3"), each = 1),
                 id = rep(c(1:10), each = 90),
                 value = sample(x = 0:100, size = 900, replace = TRUE))

Where tw (time window) represents units of time, but they are not evenly spaced. From tw 1:25 is every 500 years, whereas from tw 26 - 30 is every ~ 1500 years.

At the moment I'm plotting it like this:

library(ggplot2)
ggplot() + 
  geom_line(data=df, aes(x=tw, y=value, group=interaction(id, name), colour=name),  alpha = .15) +
  scale_x_reverse(breaks = scales::pretty_breaks(n = 15)) +
  scale_colour_manual(values = c("#ffa644", "#30460a", "#E64056")) +
  geom_vline(xintercept = 25, ) +
  ylab("Percentage (%)") + 
  xlab("Time") +
  labs(colour = "Taxa")  +
  theme_bw()

I'd like tws 26:30 (before the intercept line) to be spaced further apart than 1:25 along the x axis, to represent the longer time gap. I've tried to draw an example below.

example

I tried:

scale_x_reverse(breaks = c(29, 27, 25:1))

but this didn't have the effect of spreading the graph, it just skipped out numbering tws 28 and 26.

Upvotes: 4

Views: 542

Answers (1)

Allan Cameron
Allan Cameron

Reputation: 174278

You can either set up a transform for the axis, or you can do it manually by manipulating your data and axis. I'll demonstrate the latter approach here.

Essentially, if tw is larger than 25, then subtract 25 from tw, multiply by 3 and add 25 back on. Do the same when you are creating the axis breaks. However, when you are creating the axis labels, reverse this process. If the label is going to be higher than 25, subtract 25, divide by 3 and add 25 back on to the displayed value.

library(ggplot2)

ggplot() + 
  geom_line(data = df, alpha = 0.15,
            aes(x = ifelse(tw > 25, 25 + (tw - 25) * 3, tw), y = value,
                group = interaction(id, name), col = name)) +
  scale_colour_manual(values = c("#ffa644", "#30460a", "#E64056")) +
  geom_vline(xintercept = 25, ) +
  ylab("Percentage (%)") + 
  scale_x_reverse(labels = ~ifelse(.x > 25, (.x - 25)/3 + 25, .x),
                  name = "Time", breaks = c(2*(0:12)-1, (25:30 - 25)*3 + 25)) +
  labs(colour = "Taxa")  +
  theme_bw()

enter image description here

Upvotes: 2

Related Questions