Home > Mobile >  Specifiy which date is labelled first on x-axis
Specifiy which date is labelled first on x-axis

Time:04-25

I have the following data:

structure(list(Month = structure(c(17744, 17775, 17805, 17836, 
17866, 17897, 17928, 17956, 17987, 18017, 18048, 18078, 18109, 
18140, 18170, 18201, 18231, 18262, 18293, 18322, 18353, 18383
), class = "Date"), Return = c(0.1, 0.4, 0.5, 0.2, -0.5, 0.2, 
4, 0.3, 0.1, 0.4, 0.5, 0.2, -0.5, 0.2, 4, 0.3, 0.4, -0.5, 0.2, 
0.3, 0.4, -0.5), Rating = c("1", "1", "NA", "5", "3", "NA", "3", 
"4", "4", "NA", "5", "5", "NA", "1", "1", "1", "1", "1", "2", 
"2", "2", "2")), row.names = c(NA, -22L), class = "data.frame")

I want to plot the data with "Month" on the x-axis and "Return" on the y-axis. First I make some adjustments to my data:

library(data.table)
library(magrittr)
library(ggplot2)
library(zoo)

Data <- Data %>%
  mutate(Rating = fifelse(is.na(Rating),"NA",as.character(Rating)))

Data$Month <- as.Date(as.yearmon(Data$Month, format="%Y-%m") )

Then I use the following code:

ggplot(Data, aes(x=`Month`, y=`Return`, group=`Rating`, fill=`Rating`, color=`Rating`))   
  geom_line(size=1)  
  scale_color_brewer(palette="Paired")  
  scale_x_date(date_breaks ="6 months", date_labels = "%Y-%m")

Then I have some space between the y-axis and the lines of the graphs. I then run the following code that eliminates the space (included expand=c(0,0)):

ggplot(Data, aes(x=`Month`, y=`Return`, group=`Rating`, fill=`Rating`, color=`Rating`))   
  geom_line(size=1)  
  scale_color_brewer(palette="Paired")  
  scale_x_date(date_breaks ="6 months", date_labels = "%Y-%m", expand=c(0,0))

However, when I add expand=c(0,0) on the x-axis the first date that is shown also changes and moves very close to the y-axis which I don't like. Now 2018-08 is the first month being on the x-axis. However, before it was 2018-12 which I prefer. How can I change that so I have 2018-12 again being the first month on the x-axis being labelled.

CodePudding user response:

AsI mentioned in my comment, if you want specific breaks then IMHO you are better off with explicitly setting the breaks using the breaks argument.

Moreover, be aware that you have convert character strings to dates using as.Date. From the error message you mentioned in your comment I would guess that you have missed that:

library(ggplot2)

ggplot(Data, aes(x = `Month`, y = `Return`, group = `Rating`, fill = `Rating`, color = `Rating`))  
  geom_line(size = 1)  
  scale_color_brewer(palette = "Paired")  
  scale_x_date(breaks = seq.Date(as.Date("2018-12-01"), as.Date("2020-12-01"), by = "6 months"), 
               date_labels = "%Y-%m", expand = c(0.005, 0))

  • Related