我正在尝试创建一个气候图,其中温度为线条,降水为条形图。由于每月气温低于零,降水量条(从零开始)很高。
\n\n我希望它们处于温度曲线的最低水平(第一个 y 轴上的 -25 左右),第二个 y 轴此时显示 0。有没有办法移动数据以适应?
\n\n#build data frame with temperature and precipitation data\ndf <- as.data.frame(c("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"))\ncolnames(df) <- c("month")\ndf$month <- factor(df$month, levels = month.abb)\ndf$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)\ndf$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)\n\n#plot with ggplot2\nlibrary(ggplot2)\n\nggplot(data = df, mapping = aes(x = month, y = celsius, group = 1)) + \ngeom_bar(mapping = aes(y = prec_mm/2), stat = "identity", color="blue", fill="blue", width = 0.5) + \n geom_line(color="red", size=1.5) + \n scale_y_continuous("Temperature [\xc2\xb0C]", \n sec.axis = sec_axis(~ . *2, name = "Precipitation [mm]")\n )\nRun Code Online (Sandbox Code Playgroud)\n\n\n
如果我很好地理解你的问题,你想重新调整轴的比例,将第二个比例与第一个比例的零值对齐。去做这个:
\n\n这是您按照上述内容改编的 MWE:
\n\n#build data frame with temperature and precipitation data\ndf <- as.data.frame(c("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"))\ncolnames(df) <- c("month")\ndf$month <- factor(temp_churchill$month, levels = month.abb)\ndf$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)\ndf$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)\n\n#plot with ggplot2\nlibrary(ggplot2)\n\nggplot(data = df, mapping = aes(x = month, y = prec_mm, group = 1)) + \n geom_bar(stat = "identity", color="blue", fill="blue", width = 0.5) + \n geom_line(mapping = aes(y = celsius+30), color="red", size=1.5) + # Scale data to match desired scale\n scale_y_continuous("Precipitation [mm]", \n sec.axis = sec_axis(~ . -30, name = "Temperature [\xc2\xb0C]") # Reverse transformation to match data\n )\nRun Code Online (Sandbox Code Playgroud)\n\n\n
| 归档时间: |
|
| 查看次数: |
5545 次 |
| 最近记录: |