r - 如何用ggplot2缩放第二个轴,第二个轴有负值

标签 r ggplot2

当我绘制次要 y 轴时,数据集中的负值低于其他绘制的数据。我试图让两个数据集都从相同的基线开始,但轴刻度不同。

我已经尝试缩放数据,但无法实现我的目标。我对 ggplot2 包不是很有经验。通过显示的代码,我相信我正在绘制与降水量相同的温度数据。

# Enter climate data to be graphed
month <- month.abb[c(1,2,3,4,5,6,7,8,9,10,11,12)]
month <- ordered(month, month.abb)
aveT <- c(-2.7, -0.9, 3.1, 7.3, 11.9, 15.7, 20.2, 19.8, 14.4, 7.6, 1.2, -3.6)
precip <- c(46.2, 30.5, 23.9, 21.1, 41.1, 40.1, 26.7, 21.6, 24.6, 22.4, 36.6, 38.6)

#Set the dataframe
df <- data.frame(month, aveT, precip)

#Graph precipitation data as bar graph
g <- ggplot(df) 
g <- g + geom_bar(aes(x=month, y=precip), stat="identity", fill="blue", color="black") + theme_bw() + theme(panel.grid = element_blank())
g <- g + ylim(0, 50)

#Add Temperature data
g <- g + geom_line(aes(x=month, y=aveT, group=1), color="red", size=1.5)
g <- g + scale_y_continuous(sec.axis = sec_axis(~.*1, name = "Temperature (C)"))

结果是温度线图的负值低于降水条形图值。我想让主轴从 0 到 50,从 -5 到 25,但从相同的位置开始。

resulting graph

最佳答案

设置辅助比例不会改变您创建的第二条线。您需要转换数据,然后通过执行逆转换来绘制和调整次轴。

对于以下示例,我们希望从 y 限制 0 => 50 到 -5 => 20。为此,我们将 y 轴值转换为 aveT = y/2 - 5 以获得 aveT 的新值。要转换原始 aveT 数据点,我们必须进行逆变换:y = (aveT + 5) * 2。所以代码应该是这样的:

g <- g + geom_line(aes(x=month, y=(aveT + 5) *2 , group=1), color="red", size=1.5)
g <- g + scale_y_continuous(sec.axis = sec_axis(~./2-5, name = "Temperature (C)"))

enter image description here

关于r - 如何用ggplot2缩放第二个轴,第二个轴有负值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54612136/

相关文章:

r - 防止 spData::world 国家环绕 map /裁剪 map 区域

r - SVM 在 R 中具有相同输入和参数的不同结果

r - 避免全局变量

r - ggmap 缺少背景图(使用 pdf 设备时除外)

r - 如何使用 ggarrange() 或类似方法手动调整合并图的高度

r - ggplot 辅助 y 轴使用 sec_axis 显示 z 分数

r - 如何从本质上非数字的原始数据创建邻接矩阵

r - 在 R 函数中调用 data.frame 列?

r - 不考虑堆叠区域 (ggplot2) 和 NA

r - ggplot2:具有自定义 y 限制的 geom_bar