0

I have (x,y) data where x = months(Jan 2020-March 2021) and y = values,

I am plotting all of these on the same graph, just by there months, I would like to distingush between the years by changing the color of the x label months (jan 2020- dec 2020) to be the color blue and the data labeled Jan 2021 - March 2021 to be labeled green.

I would also like to have a legend that shows the year 2020 is blue on the x axis and 2021 is green.

example of data would be :

data:

dates = seq.Date(from =as.Date("01/01/2020", "%d/%m/%Y"), 
                 to=as.Date("01/03/2021", "%d/%m/%Y"), by="month")

y = c(1:1:15)
df = data.frame(dates,y)

when plotting, would like x axis label df$dates[1:12] to be the color blue and df$dates[13:15] to be color green

aosmith
  • 34,856
  • 9
  • 84
  • 118
AJ Jebelli
  • 101
  • 6

1 Answers1

2

One option to achieve your desired result would be to make use of the ggtext package which allows for styling of labels and theme elements via markdown or HTML.

As you offered no information about the type of chart you are trying to achieve I went for a bar chart:

dates = seq.Date(from =as.Date("01/01/2020", "%d/%m/%Y"), 
                 to=as.Date("01/03/2021", "%d/%m/%Y"), by="month")

y = c(1:1:15)
df = data.frame(dates,y)

mylabs <- function(x) {
  cols <- ifelse(lubridate::year(x) == 2020, "blue", "green")
  glue::glue("<span style = 'color: {cols}'>{format(x, '%b %Y')}</span>")
}

library(ggplot2)
library(ggtext)
library(lubridate)

ggplot(df, aes(dates, y, fill = lubridate::year(dates) == 2020)) +
  geom_col() +
  scale_x_date(date_breaks = "1 month", 
               labels = mylabs, 
               guide = guide_axis(n.dodge = 2),
               expand = c(.01, .01)) +
  scale_fill_manual(values = c("TRUE" = "grey", "FALSE" = "grey"),
                    labels = c("TRUE" = 2020, "FALSE" = 2021)) +
  theme(axis.text.x = ggtext::element_markdown()) +
  labs(fill = NULL, x = NULL, y = NULL) +
  guides(fill = guide_legend(override.aes = list(fill = c("blue", "green"))))

stefan
  • 90,330
  • 6
  • 25
  • 51