r - R - 带有ggplot2的climograph:更改降水值以适合第二轴
问题描述
我正在尝试创建一个以温度为线、降水为条形图的气候图。由于每月温度低于零,降水条(从零开始)很高。
我希望它们处于温度曲线的最低水平(在第一个 y 轴上约为 -25),第二个 y 轴此时显示为 0。有没有办法移动数据以适应?
#build data frame with temperature and precipitation data
df <- as.data.frame(c("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"))
colnames(df) <- c("month")
df$month <- factor(df$month, levels = month.abb)
df$celsius <- c(-26.0, -24.5, -18.9, -9.8, -1.0, 7.0, 12.7, 12.3, 6.4, -1.2, -12.7, -21.9)
df$prec_mm <- c(18.7, 16.6, 18.1, 23.6, 30.0, 44.2, 59.8, 69.4, 69.9, 48.4, 35.5, 18.4)
#plot with ggplot2
library(ggplot2)
ggplot(data = df, mapping = aes(x = month, y = celsius, group = 1)) +
geom_bar(mapping = aes(y = prec_mm/2), stat = "identity", color="blue", fill="blue", width = 0.5) +
geom_line(color="red", size=1.5) +
scale_y_continuous("Temperature [°C]",
sec.axis = sec_axis(~ . *2, name = "Precipitation [mm]")
)
解决方案
如果我很好地理解了您的问题,您想重新调整轴以将第二个比例与第一个比例的零值对齐。去做这个:
- 首先缩放数据以使所有温度测量结果为正。
- 调整次轴刻度以匹配调整。
这是您的 MWE 如前所述改编:
#build data frame with temperature and precipitation data
df <- as.data.frame(c("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"))
colnames(df) <- c("month")
df$month <- factor(temp_churchill$month, levels = month.abb)
df$celsius <- c(-26.0, -24.5, -18.9, -9.8, -1.0, 7.0, 12.7, 12.3, 6.4, -1.2, -12.7, -21.9)
df$prec_mm <- c(18.7, 16.6, 18.1, 23.6, 30.0, 44.2, 59.8, 69.4, 69.9, 48.4, 35.5, 18.4)
#plot with ggplot2
library(ggplot2)
ggplot(data = df, mapping = aes(x = month, y = prec_mm, group = 1)) +
geom_bar(stat = "identity", color="blue", fill="blue", width = 0.5) +
geom_line(mapping = aes(y = celsius+30), color="red", size=1.5) + # Scale data to match desired scale
scale_y_continuous("Precipitation [mm]",
sec.axis = sec_axis(~ . -30, name = "Temperature [°C]") # Reverse transformation to match data
)
推荐阅读
- python - 大熊猫在大熊猫的两列之间找到共同值的索引
- sql - 触发器函数(INSTEAD OF DELETE ON 视图)无法从查询 [POSTGRESQL] 中选择值
- html - 防止卡片在卡片组中展开
- amazon-web-services - 推送到 ECR 时的 Docker 映像大小与本地不同
- r - 如何绘制时间数据
- javascript - 对象作为Javascript中的函数参数
- amazon-cognito - 如何使用 Terraform 创建 AWS Cognito 用户
- c# - HelixToolkit 和 3d 绘图
- apache-camel - 何时在骆驼 DSL 中使用 end() 和 endChoice()
- time-complexity - 计算递归算法的时间复杂度