【问题标题】:Plot with a normal and a reversed y axis使用正常和反转的 y 轴绘图
【发布时间】:2021-02-11 12:20:12
【问题描述】:

我有包含每日降水和排放数据的数据集。现在我想在一个情节中绘制所有内容。所有数据集的长度均为 61,因此它们可以共享相同的 x 轴。放电数据应以“正常”方式绘制,这意味着 y 轴从底部开始并放置在左侧。降水数据应“从上往下”绘制,即 y 轴颠倒并放在右侧。

以下是一些可重现的最小示例的代码:

precipitation <- runif(61, min=0, max=25)
discharge <- runif(61, min=370, max=2610)

结果应大致如下所示:

有人知道如何实现这一目标吗?

编辑:感谢帕斯卡的回答暗示 ggplot2 的使用。

我自己也找到了一种使用 Base R 的方法,以防将来它可以帮助任何人:

precipitation <- runif(61, min=0, max=25)
discharge <- runif(61, min=370, max=2610)

# plot with Base R
par(mar = c(5, 5, 3, 5), xpd = TRUE)
plot(precipitation, type= "l", ylim= c(0,80), ylab= "Precipitation [mm/day]", main= "Comparison", 
     xlab= "Day", col= "blue") 
par(new = TRUE)
plot(discharge, type= "l", xaxt = "n", ylim= rev(c(0,5000)), yaxt = "n", ylab = "", xlab = "", col= "red", lty= 2)
axis(side = 4)
mtext("Discharge [m³/s]", side = 4, line = 3)

ggplot2 的方式当然看起来有点花哨。

【问题讨论】:

标签: r


【解决方案1】:

ggplot2 可用于绘制带有第二个倒轴的图。必须在scale_y_continuous() 中指定sec.axis。我正在对您的数据使用转换 ((100-x)*100) 并将其也应用于轴,以便它适合。这可以更改为任何数字。

ggplot() +
geom_line(aes(y=precipitation, x=1:61), col="orange") + 
geom_line(aes(y=100-discharge/100, x=1:61), col="blue") +
scale_y_continuous(name="rain", sec.axis=sec_axis(~(100-.)*100, name= "discharge"))

【讨论】:

    猜你喜欢
    • 2021-12-02
    • 1970-01-01
    • 1970-01-01
    • 2020-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-08
    • 1970-01-01
    相关资源
    最近更新 更多