ggplot 时间序列:弄乱了具有缺失值的数据的 x 轴
ggplot time series: messed up x axis for data with missing values
我正在为以下数据创建时间序列图:
# Creating data set
year <- c(rep(2018,4), rep(2019,4), rep(2020,4))
month_1 <- c(2, 3, 7, 8, 6, 10, 11, 12, 5, 7, 8, 12)
avg_dlt_calc <- c(10, 20, 11, 21, 13, 7, 10, 15, 9, 14, 16, 32)
data_to_plot <- data.frame(cbind(year,month_1,avg_dlt_calc ))
ggplot(data_to_plot, aes(x = month_1)) +
geom_line(aes(y = avg_dlt_calc), size = 0.5) +
scale_x_discrete(name = "months", limits = data_with_avg$month_1) +
facet_grid(~year, scales = "free")
我对情节本身没意见,但 x 轴标签搞砸了:
我该如何解决?
没有缺失月份的标签是可以的(例如,2018 年只有 2、3、7、8 - 所以很明显,只有那些月份的数据)。
补救措施是将 month_1
强制为 factor
并按年份对观察结果进行分组,如下所示:
ggplot(data_to_plot, aes(x = as.factor(month_1), y = avg_dlt_calc, group = year)) +
geom_line(size = 0.5) +
scale_x_discrete(name = "months") +
facet_grid(~year, scales = "free")
请注意,我已将 y = avg_dlt_calc
移到 ggplot()
中的 aes()
中,这比您的方法更惯用。您可以使用 scale_x_discrete()
中的 breaks
参数来手动设置中断,请参阅 ?scale_x_discrete
。
我觉得x轴固定加点更适合传达数据只在某段时间可用的信息:
ggplot(data_to_plot, aes(x = as.factor(month_1), y = avg_dlt_calc, group = year)) +
geom_line(size = 0.5) +
geom_point() +
scale_x_discrete(name = "months") +
facet_grid(~year, scales = "free_y")
我正在为以下数据创建时间序列图:
# Creating data set
year <- c(rep(2018,4), rep(2019,4), rep(2020,4))
month_1 <- c(2, 3, 7, 8, 6, 10, 11, 12, 5, 7, 8, 12)
avg_dlt_calc <- c(10, 20, 11, 21, 13, 7, 10, 15, 9, 14, 16, 32)
data_to_plot <- data.frame(cbind(year,month_1,avg_dlt_calc ))
ggplot(data_to_plot, aes(x = month_1)) +
geom_line(aes(y = avg_dlt_calc), size = 0.5) +
scale_x_discrete(name = "months", limits = data_with_avg$month_1) +
facet_grid(~year, scales = "free")
我对情节本身没意见,但 x 轴标签搞砸了:
我该如何解决?
没有缺失月份的标签是可以的(例如,2018 年只有 2、3、7、8 - 所以很明显,只有那些月份的数据)。
补救措施是将 month_1
强制为 factor
并按年份对观察结果进行分组,如下所示:
ggplot(data_to_plot, aes(x = as.factor(month_1), y = avg_dlt_calc, group = year)) +
geom_line(size = 0.5) +
scale_x_discrete(name = "months") +
facet_grid(~year, scales = "free")
请注意,我已将 y = avg_dlt_calc
移到 ggplot()
中的 aes()
中,这比您的方法更惯用。您可以使用 scale_x_discrete()
中的 breaks
参数来手动设置中断,请参阅 ?scale_x_discrete
。
我觉得x轴固定加点更适合传达数据只在某段时间可用的信息:
ggplot(data_to_plot, aes(x = as.factor(month_1), y = avg_dlt_calc, group = year)) +
geom_line(size = 0.5) +
geom_point() +
scale_x_discrete(name = "months") +
facet_grid(~year, scales = "free_y")