Search code examples
rplotlines

Do I always need lines() with plot()?


When I use plot() to plot a time serious variable, it only shows dots. I use second code, lines(), to link all the dots. Is this really necessary? Or I did something wrong...

The data is as following. I use the plot() and lines() to draw the graph to see the trend.

YYYYMM<-c("200907","200908","200909","200910","200911","200912","201001","201002","201003","201004","201005","201006","201007","201008","201009","201010","201011","201012","201101","201102","201103","201104","201105","201106")
a<-c(1158,1455,1134,1371,1352,1277,1408,1270,1000,1462,1419,0,0,0,0,0,0,0,0,0,0,0,0,0)
a_number_trend<-data.frame(YYYYMM,a)
a_number_trend

plot(a_number_trend$YYYYMM,a_number_trend$a,las=2,type="l",col="blue")
lines(a_number_trend$YYYYMM,a_number_trend$a,las=2,type="l",col="blue")

The plot is like this at beginning. enter image description here

Then become this. enter image description here

But I want the line only without the short bar. Or to change the short bars into points.


Solution

  • Convert your YYYYMM column to an actual R ?Date object. Then you can get everything lining up properly:

    a_number_trend$date <- as.Date(
      paste0(a_number_trend$YYYYMM,"01"),
      format="%Y%m%d"
    )
    
    plot(a ~ date, data=a_number_trend, type="l", xaxt="n", ann=FALSE)
    

    The below axis is not stricly necessary (remove xaxt="n" above if you want the default Date axis calculations instead).

    axis.Date(
      1,
      at=seq(min(a_number_trend$date), max(a_number_trend$date), by="1 month"),
      format="%Y%m",
      las=2
    )