John
John

Reputation: 403

Create a ggplot barplot with differently coloured horizontal rectangles as background

I would like to create a bar plot with four bars – where a transparent background of 4 differently colored, horizontal areas represent whether the strength of the bars are considered "low", "medium", "high", or "very high".

# Load ggplot2
library(ggplot2)

# Example data
data <- data.frame(
  name=c("A","B","C", "D") ,  
  value=c(3, 12, 16, 22)
)

# Background data
backgound_area_color <- c(5, 10, 14, 20)
background_area_name <- c("low", "medium", "high", "very high")
background_data <- as.data.frame(backgound_area_color, background_area_name)

# My attempt:
ggplot(data, aes(x=name, y=value)) + 
  geom_bar(stat = "identity") + 
  geom_rect(data = background_data, 
            aes(y = backgound_area_color))

Thanks in advance

Upvotes: 1

Views: 451

Answers (2)

TarJae
TarJae

Reputation: 78927

I like Allan Camerons approach best. Here is what I have tried to provide as an alternative using annotations:

library(ggplot2)

ggplot(data, aes(x=name, y=value))+
  annotate("rect", xmin = 0.5, xmax = 4.5, ymin = 0, ymax = 5, fill = "red", alpha = 0.2)+
  annotate("rect", xmin = 0.5, xmax = 4.5, ymin = 5, ymax = 10, fill = "green", alpha = 0.2)+
  annotate("rect", xmin = 0.5, xmax = 4.5, ymin = 10, ymax = 14, fill = "yellow", alpha = 0.2)+
  annotate("rect", xmin = 0.5, xmax = 4.5, ymin = 14, ymax = 20, fill = "blue", alpha = 0.2) +
  geom_col()+
  scale_x_discrete()+
  geom_text(aes(label=background_area_name), hjust=2.5, vjust=0, angle=90, size=5, color="white") +
  theme_classic()

enter image description here

Upvotes: 2

Allan Cameron
Allan Cameron

Reputation: 173813

You need an xmin, xmax, ymin and ymax aesthetic for geom_rect:

background_data <- data.frame(xmin = -Inf, xmax = Inf,
                              ymin = c(0, 5, 10, 14),
                              ymax = c(5, 10, 14, Inf),
                              fill = factor(background_area_name,
                                            background_area_name))

# My attempt:
ggplot(data, aes(x=name, y=value)) + 
  geom_rect(data = background_data, 
            aes(ymin = ymin, ymax = ymax, xmin = xmin, xmax = xmax, fill = fill),
            inherit.aes = FALSE, alpha = 0.5) +
  geom_bar(stat = "identity")

enter image description here

Upvotes: 3

Related Questions