1

我正在为以下数据创建时间序列图:

#  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 - 所以很明显,只有那些月份的数据)。

4

1 回答 1

1

一种补救措施是强制month_1afactor并将观察结果按年份分组,如下所示:

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进入aes()ggplot()比您的方法更惯用的内部。您可以使用breaks参数 inscale_x_discrete()手动设置中断,请参阅?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")

在此处输入图像描述

于 2021-03-11T12:25:53.367 回答