ggplot2折线图问题:出现倾斜直线而非预期折线图
ggplot2生成倾斜直线而非预期折线图问题解决
我用R的ggplot2创建折线图时,生成的图表显示倾斜直线,而非预期的折线图。
使用的代码:
aws_plot <- df_aws_atm %>% ggplot(aes(x=Month, y=values, color=variables, group=1)) + geom_line(linewidth=0.5) + scale_color_manual(values = c("P"="black","E"="blue","C"="green", "WVSC"="red")) + # scale_y_continuous(limits = c(-50, 1500)) + scale_x_discrete(expand = c(0.02, 0)) + ggtitle("Atmospheric Water Balance") + xlab("Month") + ylab("mm") + theme_bw()
使用的数据:
> dput(df_aws_atm) structure(list(Month = structure(c(1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L, 5L, 5L, 5L, 5L, 6L, 6L, 6L, 6L, 7L, 7L, 7L, 7L, 8L, 8L, 8L, 8L, 9L, 9L, 9L, 9L, 10L, 10L, 10L, 10L, 11L, 11L, 11L, 11L, 12L, 12L, 12L, 12L), levels = c("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"), class = "factor"), variables = structure(c(1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L), levels = c("P", "E", "C", "WVSC"), class = "factor"), values = c(61.6012042725641, 19.4143472506923, 41.107596204, -1.07926081812821, 61.0211111110256, -5.24147855594872, 66.7437418039231, 0.48115213725641, 80.6383290582051, 7.16041454266667, 76.3176395729744, 2.83972504705128, 100.314478631795, 69.3612280245385, 34.7814502373077, 3.82819962705128, 112.722914529231, 92.58926418, 27.2810184358718, 7.14736808612821, 105.177636751538, 110.168340093846, 2.30605669376923, 7.2967600354359, 99.9483119687179, 126.626434667949, -22.3589573936923, 4.31916530276923, 87.8823653871795, 112.96183799, -26.497900053, -1.41842745128205, 80.9593547017949, 79.0862466384615, -5.19606537007692, -7.06917343351282, 84.362542735641, 48.421970115641, 28.3443924478205, -7.5961801698718, 82.4711452974359, 13.4414487457436, 63.4596880341795, -5.57000852123077, 70.4012179492308, 8.49156181276923, 58.8562424521282, -3.05341368164103)), row.names = c(NA, -48L), class = c("tbl_df", "tbl", "data.frame")) >
问题原因
代码中设置了group=1,这会将所有不同variables类别的数据强制归为同一组,ggplot会按数据行的顺序连接所有点,最终形成倾斜的直线,而非每个类别单独的折线。
解决方案
去掉aes中的group=1参数,或者将其替换为group=variables。因为color=variables已经会让ggplot自动按variables分组,默认将同一类别的点连接成折线。
修改后的代码:
aws_plot <- df_aws_atm %>% ggplot(aes(x=Month, y=values, color=variables)) + geom_line(linewidth=0.5) + scale_color_manual(values = c("P"="black","E"="blue","C"="green", "WVSC"="red")) + # scale_y_continuous(limits = c(-50, 1500)) + scale_x_discrete(expand = c(0.02, 0)) + ggtitle("大气水平衡") + xlab("月份") + ylab("毫米") + theme_bw()
说明
你的数据是标准的长格式,每个月份对应4个变量的数值,完全符合多类别折线图的绘制要求。修改分组设置后,就能得到分别对应P、E、C、WVSC的4条折线。
内容的提问来源于stack exchange,提问作者Mukhtar Abdi
相关产品推荐
相关产品推荐

