Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Customize background to highlight ranges of data in ggplot [duplicate]

Tags:

r

ggplot2

I want to set background colors in my ggplot to highlight ranges of data. Particularly, I want to highlight [-0.1,0.1] with, say, green,[-0.25,-0.1) and (0.1,0.25] with orange. In other words, what I need are bars with some alpha-transparency whose y-limits are the plot's y range, and x-limits are set by me.

Ideally, I would want something that would not be sensitive to coord_cartesian(...) (as setting vline(...,size = X) would). Additionally, it would be nice to have something independent from any data, and based solely on plot coordinates. I tried geom_segment, but I could not figure it our how to set a width that would work.

library(ggplot2)
x <- c(seq(-1, 1, by = .001))
y <- rnorm(length(x))
df <- as.data.frame(x=x,y=y)

ggplot(df,aes(x,y)) +
  geom_point(aes(y*abs(x)),alpha=.2,size=5) +
  theme_bw() +
  coord_cartesian(xlim = c(-.5,.5),ylim=c(-1,1))

example

like image 380
Lucarno Avatar asked Nov 25 '13 13:11

Lucarno


2 Answers

You can add the "bars" with geom_rect() and setting ymin and ymax values to -Inf and Inf. But according to @sc_evens answer to this question you have to move data and aes() to geom_point() and leave ggplot() empty to ensure that alpha= of geom_rect() works as expected.

ggplot()+
  geom_point(data=df,aes(x=y*abs(x),y=y),alpha=.2,size=5) +
  geom_rect(aes(xmin=-0.1,xmax=0.1,ymin=-Inf,ymax=Inf),alpha=0.1,fill="green")+
  geom_rect(aes(xmin=-0.25,xmax=-0.1,ymin=-Inf,ymax=Inf),alpha=0.1,fill="orange")+
  geom_rect(aes(xmin=0.1,xmax=0.25,ymin=-Inf,ymax=Inf),alpha=0.2,fill="orange")+
  theme_bw() +
  coord_cartesian(xlim = c(-.5,.5),ylim=c(-1,1))

enter image description here

like image 61
Didzis Elferts Avatar answered Oct 05 '22 09:10

Didzis Elferts


You may try annotate, which takes vectors of xmin and xmax values.

ggplot(df,aes(x,y)) +
  geom_point(aes(y*abs(x)), alpha =.2, size = 5) +
  annotate("rect", xmin = c(-0.1, -0.25, 0.1), xmax = c(0.1, -0.1, 0.25),
           ymin = -1, ymax = 1,
           alpha = 0.2, fill = c("green", "orange", "orange")) +
  theme_bw() +
  coord_cartesian(xlim = c(-.5,.5),ylim=c(-1,1))

enter image description here

like image 29
Henrik Avatar answered Oct 05 '22 08:10

Henrik