Kevin W
Kevin W

Reputation: 33

Adding shaded target region to ggplot2 barchart

I have two data frames: one I am using to create the bars in a barchart and a second that I am using to create a shaded "target region" behind the bars using geom_rect.

Here is example data:

test.data <- data.frame(crop=c("A","B","C"), mean=c(6,4,12))
target.data <-  data.frame(crop=c("ONE","TWO"), mean=c(31,12), min=c(24,9), max=c(36,14))

I start with the means of test.data for the bars and means of target.data for the line in the target region:

library(ggplot2)
a <- ggplot(test.data, aes(y=mean, x=crop)) + geom_hline(aes(yintercept = mean, color = crop), target.data) + geom_bar(stat="identity")
a

enter image description here

So far so good, but then when I try to add a shaded region to display the min-max range of target.data, there is an issue. The shaded region appears just fine, but somehow, the crops from target.data are getting added to the x-axis. I'm not sure why this is happening.

b <- a + geom_rect(aes(xmin=-Inf, xmax=Inf, ymin=min, ymax=max, fill = crop), data = target.data, alpha = 0.5)
b

enter image description here

How can I add the geom_rect shapes without adding those extra names to the x-axis of the bar-chart?

Upvotes: 2

Views: 1929

Answers (1)

Nate
Nate

Reputation: 10671

This is a solution to your question, but I'd like to better understand you problem because we might be able to make a more interpretable plot. All you have to do is add aes(x = NULL) to your geom_rect() call. I took the liberty to change the variable 'crop' in add.data to 'brop' to minimize any confusion.

test.data <- data.frame(crop=c("A","B","C"), mean=c(6,4,12))
add.data <-  data.frame(brop=c("ONE","TWO"), mean=c(31,12), min=c(24,9), max=c(36,14))

ggplot(test.data, aes(y=mean, x=crop)) +
  geom_hline(data = add.data, aes(yintercept = mean, color = brop)) +
  geom_bar(stat="identity") +
  geom_rect(data = add.data, aes(xmin=-Inf, xmax=Inf, x = NULL, ymin=min, ymax=max, fill = brop),
    alpha = 0.5, show.legend = F)

In ggplot calls all of the aesthetics or aes() are inherited from the intial call:

ggplot(data, aes(x=foo, y=bar)).

That means that regardless of what layers I add on geom_rect(), geom_hline(), etc. ggplot is looking for 'foo' to assign to x and 'bar' to assign to y, unless you specifically tell it otherwise. So like aeosmith pointed out you can clear all inherited aethesitcs for a layer with inherit.aes = FALSE, or you can knock out single variables at a time by reassigning them as NULL.

Upvotes: 1

Related Questions