Search code examples
rggplot2time-seriesx-axis

ggplot time series: messed up x axis - 2


This is modified version of this question.

I need to create time series plot for 2 lines 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)
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")+

But x-axis looks wrong: enter image description here

If to plot data without this line:

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

Then x-axis will still be messy: enter image description here

I am setting limits for x-axis, but looks like it is not working.
How can I fix it?


Solution

  • I've skipped some lines and features of your plot, but in essence, this is what needs to be changed:

    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)
    

    In your code, you used limits = data_to_plot$month_1, but ggplot2 only used the 2 first elements of month_1 - it did not interpret it as a set of acceptable values.