R中利用ggplot2做双轴图

以下代码实现利用ggplot2做双轴图的功能

# 构建数据
Date <- seq(from=as.Date("2015-01-01"), to=as.Date("2015-12-01"), by="month")
Consumers <- c(100,80,120,153,200,188,220,322,300,321,282,304)
Amount <- c(1000,840,1458,1844,2045,2000,2548,5081,5000,5200,4800,4971)
df1 <- data.frame(Date=Date, Consumers=Consumers,Amount=Amount)

# 加载包
library(ggplot2)
p <- ggplot(df1, aes(x = Date))

# consumer的折线图
p <- p + geom_line(aes(y = Consumers, color = "Consumers"))

# amount的点图
p <- p + geom_point(aes(y = Amount/20, color = "Amount"))


p <- p + scale_y_continuous(sec.axis = sec_axis(~. *20, name = "Amount"))
# notice the first augment, trans in sec_axis
p <- p + scale_color_manual(values = c("red", "blue"))
p <- p + theme(axis.title.y = element_text(size = 13))
p 

以下是成图效果

其中重点命令是

sec.axis = sec_axis(~. *20, name = "Amount")

sec.axis指的是第二个轴,sec_axis指的是第二轴的定制命令。

推荐阅读更多精彩内容