0

I would like to colours the background of a ggplot. It's almost described here: link, but there are some issued that make my idea just not work. First, my data looks like this:

# airquality
rects = data.frame(start = seq(0, 200, 50), end = seq(50, 250, 50), level = c ("good", "moderate", "unhealthy for sensitive groups", " unhealty", "very unhealth"))

I would like to make a background for some airquality-data. This data has timestamps. So the x-axis would run from sys.Date()-90 to sys.Date(). The y-axis has some levels of no2-concentration, that I'd like to give some colours. My approach is the following

datemin = as.Date(sys.Date() - 90)
datemax = as.Date(sys.Date())

ggplot() + geom_rect(data = rects, aes(xmin = datemin, xmax = datemax, ymin = start, ymax = end, fill = level), alpha = 0.5) 

This gives the following plot:

enter image description here

So far so good. But what I would like is to give every box a specif colour. And I don't know how to do this.

Moreover, when I combine this with my time-series data it says: Error: Invalid input: time_trans works with objects of class POSIXct only

So my questions are: How to get a specific colour for each box. And how to assure the dates are aacepted?

Lenn
  • 1,283
  • 7
  • 20
  • The second part of your question will need an example of the data that's causing the error e.g. `dput(data)` if it's short, or at least `str(data)`. – Miff Apr 01 '20 at 10:42

2 Answers2

1

Fill colours can be specified manually using scale_fill_manual, with the names attribute of the vector used to assign the correct colour to the correct group. The code would be:

colours <- c("violet","purple","blue","green","yellow")
names(colours) <- rects$level

colours
#                               good                       moderate unhealthy for sensitive groups                       unhealty                  very unhealth 
#                           "violet"                       "purple"                         "blue"                        "green"   

ggplot() + geom_rect(data = rects, aes(xmin = datemin, xmax = datemax, ymin = start, ymax = end, fill = level), alpha = 0.5) +
  scale_fill_manual(values=colours)
Miff
  • 7,486
  • 20
  • 20
  • Thank you very much;)!! what is `names(colours)` = rects$level` doing? Work's perfectly, I just don't know it exactly:/ – Lenn Apr 01 '20 at 19:06
  • @LeKo It matches the colours to the levels, so the first level (good) gets matched to violet. etc. If you don't specify it, you'll get the right colours, but not necessarily in the right order – Miff Apr 02 '20 at 08:30
1

heres my solution

ggplot() +
  geom_rect(data = rects, aes(xmin = datemin, xmax = datemax, ymin = start, ymax = end, fill = level), alpha = 0.5)+
   scale_fill_manual(values = c("red", "blue", "green","orange","grey")

user12256545
  • 2,755
  • 4
  • 14
  • 28