ggplot绘制折线图为空但散点图正常,如何解决?
问题描述
我有如下两列格式的数据:
year_month avg <chr> <dbl> 1 2015-07 9470. 2 2015-08 12113. 3 2015-09 13532. 4 2015-10 11129. 5 2015-11 12550. 6 2015-12 10830. 7 2016-01 12835. 8 2016-02 11907. 9 2016-03 12799. 10 2016-04 12437. 11 2016-05 11860. 12 2016-06 11521.
使用以下ggplot代码绘制折线图时得到空白图表:
ggplot(data=time_series_yr,aes(x=year_month))+ geom_line(aes(y=avg))
但使用geom_point()绘制散点图时能正常显示:
ggplot(data=time_series_yr,aes(x=year_month))+ geom_point(aes(y=avg))
请问如何正常生成折线图?
解决方案
问题核心是year_month为字符类型(<chr>),geom_line()无法识别离散字符的时间顺序,不会自动按时间逻辑连接点,导致折线图空白。只需将字符型时间转换为日期/时间类型即可解决:
方法1:使用lubridate包(推荐)
# 先安装并加载lubridate包 install.packages("lubridate") library(lubridate) library(ggplot2) # 将year_month转换为日期类型 time_series_yr$year_month <- ym(time_series_yr$year_month) # 绘制折线图 ggplot(data=time_series_yr,aes(x=year_month))+ geom_line(aes(y=avg))
方法2:使用基础R
library(ggplot2) # 补全日期后转换为Date类型 time_series_yr$year_month <- as.Date(paste0(time_series_yr$year_month, "-01")) # 绘制折线图 ggplot(data=time_series_yr,aes(x=year_month))+ geom_line(aes(y=avg))
转换后ggplot会自动识别时间序列的顺序,不仅能正常显示折线,还能支持时间轴的刻度调整。
内容的提问来源于stack exchange,提问作者azinsera
相关产品推荐
相关产品推荐

