0

这是这个 问题的修改版本。

我需要为以下数据创建 2 行的时间序列图:

#  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)
avg_dlt_standard <- c(rep(9,12))
data_to_plot <- data.frame(cbind(year,month_1,avg_dlt_calc,avg_dlt_standard ))

data_to_plot$month_1 <- factor(data_to_plot$month_1, levels=unique(data_to_plot$month_1))

ggplot(data_to_plot,aes(x = as.factor(month_1))) +
  geom_line(aes(y = avg_dlt_calc, group = year, colour = "DLT Calculated"), size = 0.5) +
  geom_line(aes(y = avg_dlt_standard, group = year, colour = "DLT standard"), size = 0.5) +
  geom_point(aes(y = avg_dlt_calc, colour = "DLT Calculated")) +
  scale_x_discrete(name = "months", limits = data_to_plot$month_1) +
  facet_grid(~year, scales = "free")+
  
  scale_color_manual(name="", 
                     labels = c("DLT Calculated",
                                "DLT standard"),
                     
                     values = c( "blue",
                                 "red")) +
  theme(legend.position="top",
        legend.text = element_text(size = 8))
s = data_to_plot$month_1) +
  facet_grid(~year, scales = "free")+

x-axis看起来不对: 在此处输入图像描述

如果要绘制没有这条线的数据:

data_to_plot$month_1 <- factor(data_to_plot$month_1, levels=unique(data_to_plot$month_1))

然后x-axis 仍然会很乱: 在此处输入图像描述

我正在为 设置限制x-axis,但看起来它不起作用。
我该如何解决?

4

1 回答 1

1

我跳过了你的情节的一些线条和特征,但本质上,这是需要改变的:

ggplot(data_to_plot, aes(x=month_1))+  # no as.factor
 geom_point(aes(y=avg_dlt_calc)) +
 geom_line(aes(y=avg_dlt_calc))  +
 geom_line(aes(y=avg_dlt_standard), colour='red') +
 scale_x_continuous(breaks=1:12, limits=c(1,2)) + # do *not* use scale_x_discrete,
 # your x-axis is *continuous*; use breaks-argument to set the ticks.
 # note, limits should only have 2 values - upper and lower limit. 
 facet_grid(~year)

在您的代码中,您使用limits = data_to_plot$month_1了 ,但 ggplot2 仅使用了 2 个第一个元素month_1- 它没有将其解释为一组可接受的值。

于 2021-03-12T13:26:57.247 回答