Reputation: 397
I ran a simulation for some populations. Now I want to plot the change of particular characteristics of these population over time as a line plot. The common x axis shows the number of generation
Below is a minimum working example for my R code so far (dummy data):
require(ggplot2)
set.seed(3)
x <- 99:0
y <- 0.5+cumsum(rnorm(100, 0, 0.01))
xy <- data.frame(x,y)
ggplot(data=xy, aes(x=x, y=y)) +
geom_line() +
xlab("Generation number") +
ylab("Character")
However, now I'd like to add a second x axis which gives the number of years before present (BP), assuming that the average generation time is 22.5 years. Thus, the value for the lowest generation number will have the highest value in the 2nd axis and vice versa. Any idea how I could acchieve this?
Thanks a lot in advance for your suggestions and help!
Upvotes: 0
Views: 66
Reputation: 397
Ok, thanks to @sambold. Here's my solution based on her/his suggestion:
ggplot(data=xy, aes(x=x, y=y)) +
geom_line() +
scale_x_continuous(sec.axis=(~.*-22.5+2250)) +
xlab("Generation number") +
ylab("Character")
Upvotes: 0
Reputation: 817
If you just want to add a second x axis, then use sec.axis in scale_x_continuous ... you could also add some calculations there ...
ggplot(data=xy, aes(x=x, y=y)) +
geom_line() +
scale_x_continuous(sec.axis=(~.+5)) +
xlab("Generation number") +
ylab("Character")
Upvotes: 1