Giswok
Giswok

Reputation: 579

Controlling rectangular geom_ribbon in R ggplot

I'm using ggplot, and am trying to add a ribbon in the form of a simple rectangle to a barplot I have. The idea is to show a cutoff below a certain value.

The barplot is fine but I can't quite get the ribbon right - I'd like it displayed a little wider but it seems to be limited to the width of the barplot data.

I tried using xmin and xmax but that doesn't increase the width of the shaded area.

Is there a way of explicitly controlling the width of geom_ribbon?

# Where df is a data frame containing the data to plot
library(cowplot)

ggplot(df, aes(x=treatments, y=propNotEliminated)) +
  geom_ribbon(aes(xmin=0, xmax=21, ymin=0, ymax=20)) +  # the xmin and xmax don't do what I'd expect
  geom_bar(stat="identity", fill="white", colour="black", size=1) +
  theme_cowplot()

Resulting plot

Upvotes: 4

Views: 1203

Answers (1)

tonytonov
tonytonov

Reputation: 25638

Why not use geom_rect?

ggplot(mtcars, aes(factor(cyl))) + 
  geom_bar() +
  geom_rect(xmin = 0, xmax = Inf, ymin = 0, ymax = 1, fill = "blue") + 
  geom_rect(xmin = 1, xmax = 3, ymin = 1, ymax = 2, fill = "red") + 
  geom_rect(xmin = 1 - 0.5, xmax = 3 + 0.5, ymin = 2, ymax = 3, fill = "green") 

enter image description here

After you're satisfied with the placement, put geom_bar last.

Upvotes: 6

Related Questions