简体   繁体   中英

How to add secondary x-axis using R ggplot2?

I have a sample dataset as below:

date = c("2013-10-01", "2013-10-08", "2013-10-15", "2013-10-22", "2013-10-29", "2013-11-05")
rain = c( 0.0, 41.8,  6.4,  8.8,  2.0, 38.2)
df = data.frame(as.Date(date), rain)

for (i in seq(NROW(df))) {df$day[i] = as.integer(difftime(df$as.Date.date.[i], df$as.Date.date.[1]))+1}
# Calculate days after the first day '2013-10-01'

I try to plot rain against date (as the primary x-axis) and day (as the secondary x-axis).

I tried

ggplot(data = df, aes(x = as.Date.date., y = rain)) + 
     geom_line(color = "#000000") +
     scale_x_date(date_labels = "%b", sec.axis = sec_axis(.~ df$day)) 

But it seems to recognise the day as the date format instead of integers.

Then I tried

ggplot(data = df, aes(x = as.Date.date., y = rain)) + 
     geom_line(color = "#000000") +
     scale_x_date(date_labels = "%b") + scale_x_continuous(df$day) 

But it shows up

Scale for 'x' is already present. Adding another scale for 'x', which will replace the existing scale.
Error in as.Date.numeric(value) : 'origin' must be supplied

Is there another way to do this?

Looks like it is because you have only one data point in each facet. If you remove the facet_grid and edit the scale_x_date as follows, the line shows up:

  ggplot(data = df, aes(x = as.Date.date., y = rain)) + 
  geom_line(color = "#000000") +
  scale_x_date(date_labels = waiver()) +
    theme_bw() +
    theme(strip.placement = "outside",
        strip.background = element_rect(fill=NA,colour="grey50"),
        panel.spacing=unit(0,"cm"))

在此处输入图像描述

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