自定义背景以突出显示ggplot中的数据范围

Luc*_*rno 8 r ggplot2

我想在我的ggplot中设置背景颜色以突出显示数据范围.特别是,我想[-0.1,0.1]用绿色[-0.25,-0.1)(0.1,0.25]橙色突出显示.换句话说,我需要的是具有一些alpha透明度的条形图,其y-限制是图形的y范围,x-limits由我设置.

理想情况下,我会想要一些不敏感的东西coord_cartesian(...)(如设置vline(...,size = X)那样).另外,拥有独立于任何数据的东西并且仅基于绘图坐标会很好.我试过geom_segment,但我无法想象我们如何设置一个可行的宽度.

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))
Run Code Online (Sandbox Code Playgroud)

例

Did*_*rts 12

您可以添加"条形图",geom_rect()并将设置yminymax值添加到-InfInf.但根据@sc_evens回答这个问题,你必须移动data,并aes()geom_point()离开ggplot()空确保alpha=geom_rect()作品如预期.

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))
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


Hen*_*rik 11

您可以尝试annotate,它采用向量xminxmax值.

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))
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述