ggplot时间序列:混淆了x轴以获取缺少值的数据 [英] ggplot time series: messed up x axis for data with missing values

查看:51
本文介绍了ggplot时间序列:混淆了x轴以获取缺少值的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am creating time series plot for the following data:

#  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轴标签弄乱了:

I am ok with the plot itself, but x-axis labels are messed up:

我该如何解决?

没有丢失月份的标签是可以的(例如,对于2018年,只有2,3,7,8-因此很明显,只有那些月份的数据).

It is ok not to have labels for missing months (for example, for 2018 it will be only 2,3,7,8 - so it will be clear, that there is data only for those months).

推荐答案

一种补救方法是将 month_1 强制为 factor 并按年份将观察结果分组,如下所示:

A remedy is to coerce month_1 to a factor and group the observations by year like so:

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 .

Note that I've moved y = avg_dlt_calc inside aes() in ggplot() which is more idiomatic than your approach. You may use the breaks argument in scale_x_discrete() to set breaks manually, see ?scale_x_discrete.

我认为固定的x轴和加点更适合传达仅在某些时间段内可用数据的信息:

I think a fixed x-axis and adding points is more suitable for conveying the information that data is only available for some periods:

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")

这篇关于ggplot时间序列:混淆了x轴以获取缺少值的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆