首页 > 解决方案 > R用辅助轴绘制数据系列

问题描述

我想绘制一个有 4 列的数据框:

Quarters <-  c("Q1","Q2","Q3")
Series1 <- c("1%","2%","3%")
Series2 <- c("4%","5%","6%")
Series3 <- c("1000","2000","3000")

df <- data.frame(Quarters,Series1,Series2,Series3)

四分之一作为 x 轴,Series1 和 Series2 作为左 y 轴,Series3 作为右 y 轴和图例。

我已经看到了一些使用 scale_y_continues 的 ggplot 解决方案,但是辅助 (y) 轴必须是主轴的倍数。我不想要,因为数据将是动态的,并且该比率可能不会在所有情况下都保持不变。

任何解决方案我可以如何去创建这个?也许 ggplot 不是要走的路?

标签: rggplot2

解决方案


我不知道 ggplot2,但您可以par(new = T)在 R 中使用在另一个图形之上绘制图形。如果您从第一个图中删除右轴并在第二个图中手动添加它应该看起来不错。

Quarters <-  c(1,2,3)
Series1 <- c(0.01,0.02,0.03)
Series2 <- c(0.04,0.05,0.06)
Series3 <- c(1000,2000,3000)

par(mar = c(5,5,2,5)) # Leaves some space for the second axis

plot(Quarters,Series1,type="l",ylim=c(0,0.1))
lines(Quarters,Series2,col="red")

par(new=T)
plot(Quarters,Series3,type="l",axes=F, xlab=NA, ylab=NA,col="blue") # Removes axis and labels so they don't overlap
axis(side = 4) # Adds secondary axis

这对你有用吗?更多信息在这里


推荐阅读