首页 > 解决方案 > 如何使用 ggplot2 创建具有多个 y 轴(≥ 3)的折线图?

问题描述

有什么方法可以使用 ggplot2 创建具有多个(≥ 3)y 轴的折线图?我设法使用基本图形来制作它。有什么方法可以使用 ggplot2 做到这一点?

library(WDI)
c_name <- "PHL"
st <- 2000
en <- 2017

gdp <- WDI(country = c_name, indicator = "SL.GDP.PCAP.EM.KD", start = st, end = en, extra = FALSE, cache = NULL)
life.exp <- WDI(country = c_name, indicator = "SP.DYN.LE00.IN", start = st, end = en, extra = FALSE, cache = NULL)
health.exp <- WDI(country = c_name, indicator = "SH.XPD.CHEX.PC.CD", start = st, end = en, extra = FALSE, cache = NULL)

tab <- cbind(gdp, life.exp, health.exp)[,c("year", "SL.GDP.PCAP.EM.KD", "SP.DYN.LE00.IN", "SH.XPD.CHEX.PC.CD")]
names(tab) <- c("year","gdp", "life.exp", "health.exp")

plot(tab$year, tab$gdp, type="l", xlab="year", ylab="", bty="n")
par(new=TRUE, mgp = c(0, 3, 2)) 
plot(tab$year, tab$life.exp, type="l", xlab="", ylab="", bty="n", col="blue", axes=F)
axis(2, col="blue", col.axis="blue")
par(new=TRUE, mgp = c(0, -2, -3))
plot(tab$year, tab$health.exp, type="l", xlab="", ylab="", bty="n", col="red", axes=F)
axis(2, col="red", col.axis="red")
legend(2001, max(tab$health.exp, na.rm=T), legend=c("GDP per capita (constant 2011 PPP$)", "Life expectancy at birth (years)", "Current health expenditure per capita (current US$)"), col=c("black", "blue", "red"), lty=1, cex=0.8)

标签: rggplot2

解决方案


推荐阅读