假设我有以下数据集:
第一个是月度数据:
library (ggplot2)
val <- runif(48, -5,5)
dt <- seq(as.Date("2010/1/1"), by = "month", length.out = 48)
dat <- data.frame(cbind(val, as.Date(dt)))
ggplot(dat, aes(dt, val,fill=val)) + geom_bar(stat = 'identity')
第二个是具有不同y尺度的年度数据:
val2 <- runif(4,50,70)
dt2 <- seq(2010,2014)
dat2 <- data.frame(cbind(val2, dt2))
是否可以在此图上叠加第二个数据集,两个y轴但一个 x轴?
答案 0 :(得分:1)
You can do it, even with two separate data frames, but the result is likely to be misleading and difficult to interpret.
library(tidyverse)
library(lubridate)
set.seed(2)
val <- runif(48, -5,5)
dt <- seq(as.Date("2010/1/1"), by = "month", length.out = 48)
dat <- data.frame(val, dt=as.Date(dt))
val2 <- runif(5,50,70)
dt2 <- seq(2010,2014)
dat2 <- data.frame(val2, dt2)
ggplot() +
geom_bar(data=dat, aes(dt, val,fill=val), stat = 'identity') +
geom_line(data=dat2 %>% mutate(dt2 = ymd(paste0(dt2,"06-30"))),
aes(dt2, val2/10), colour="red") +
scale_y_continuous(sec.axis=sec_axis(~.*10, name="val2")) +
theme(axis.text.y.right=element_text(colour="red"),
axis.title.y.right=element_text(colour="red"),
axis.text.y=element_text(colour="#346D9D"),
axis.title.y=element_text(colour="#346D9D"),
axis.title.x=element_blank(),
legend.position="bottom")