Home > Software engineering >  Plotting years with decimals in R ggplot
Plotting years with decimals in R ggplot

Time:03-24

I am plotting years across two decades using ggplot.I have a situation where due to how the data for the years was taken, the datapoints are really halfway through the year so to be accurate, I labeled the years with a .5 at the end. In addition, I also have one single datapoint that was taken in early 2005 so it's labeled as 2005.22 so the years look like : 2005.22, 2005.5,2006.5,2007.5,2008.5,2009.5,2010.5,2011.5,2012.5. Since I am technically missing data for 2005-2005.21, I want the plot to start at 2005 with no line showing until 2005.22 and then breaking every 2 years starting at 2005.5,2007.5 and so on... I've been using the following to plot geom_line for the years but I do not know how to get the above result. I was able to get the limits to start at 2005 but with the datapoint starting at 2005.22, it just plots like 2005.22,2007.22....below is what I am using to properly plot and break the years.

scale_x_continuous(
      name = "year",
      breaks = seq(c(2005, 2012.5), by=2),
      expand = c(0,0)) 
    coord_cartesian(xlim = c(2005, 2012.5))```

CodePudding user response:

It's a little hard for me to understand what exactly you want the plot to look like (especially in terms of the labels), but does this do what you're looking for? You can add 2005 to the front of the breaks sequence, which places it in front without disrupting the rest of the sequence.

library(ggplot2)

d <- data.frame(x=c(2005.22, 2005.5,2006.5,2007.5,2008.5,2009.5,2010.5,2011.5,2012.5), 
                y=runif(9,-1,1))

ggplot(d, aes(x,y))  
  geom_line()  
  scale_x_continuous(breaks=c(2005, seq(2005.5, 2012.5,2)))

enter image description here

  • Related