【发布时间】:2019-11-25 08:46:51
【问题描述】:
我想使用 2 个 y 轴将 2 个 ts 对象分别绘制为条形和线。我怎样才能在 ggplot 中做到这一点?
我有 2 个 ts-objects:一个是变量的值,另一个是年变化。数据为月度数据。我想将两个 ts 对象绘制成一个图形,值作为线,增长率作为条形。为此,我需要一个辅助 y 轴,因为这两个变量的比例非常不同。
我通常使用 ts.plot 绘制 ts 对象,它可以轻松容纳辅助 y 轴,但我无法绘制条形图,只能绘制线条。
使用 ggplot,我在纠结如何使用 ts-object... 使用 autoplot,我可以生成绘图和辅助轴,但后者似乎真的独立于我的数据。在下面的示例中,如何让线条和条形重叠?
# REPRODUCIBLE EXAMPLE
library(ggplot2)
library(ggfortify) # to use autoplot
library(seasonal) # to get the example ts data AirPassengers
library(dplyr) # to use the pipe-operator
# Genereate year-on-year change
YearOverYear <- function (x,periodsPerYear){
if(NROW(x)<=periodsPerYear){
stop("too few rows")
}
else{
indexes<-1:(NROW(x) - periodsPerYear)
return(c(rep(NA,periodsPerYear), (x[indexes+periodsPerYear]- x[indexes]) / x[indexes]))
}
}
AirPassengers.gr <- YearOverYear(AirPassengers, 12) %>%
ts(., start = start(AirPassengers), frequency = 12)
p <- autoplot(AirPassengers, ts.geom = 'line', ts.colour = 'dodgerblue')
autoplot(AirPassengers.gr*100, ts.geom = 'bar', ts.colour = 'red', p=p) +
scale_y_continuous(sec.axis = sec_axis(~./1))
【问题讨论】:
标签: r ggplot2 time-series yaxis