2013-11-25 30 views
5

我想在我的ggplot中設置背景顏色以突出顯示數據範圍。特別是,我想用橙色突出顯示[-0.1,0.1],例如綠色,[-0.25,-0.1)(0.1,0.25]。換句話說,我需要的是帶有一些透明度的酒吧,其中y-限制是圖的y範圍,x-限制是由我設定的。自定義背景以突出顯示ggplot中的數據範圍

理想情況下,我想要一些不會對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)) 

example

+0

使用'geom_rect'。 – Roland

回答

9

您可以geom_rect()添加 「酒吧」,並設置yminymax-InfInf。但根據@sc_evens回答this question您必須將dataaes()改爲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)) 

enter image description here

+1

我只想和你覈對一下:如果你將「orange」的其中一個「alpha」設置爲「 0.1,另一個爲0.9,它是否會改變矩形的外觀?即'alpha'是否至少可以在'geom_rect'中預期?對不起,如果我在這裏做錯了事。 – Henrik

+0

@Henrik謝謝你指出alpha的問題 - 更新我的答案。 –

+0

我有一種模糊的感覺,我以前一直在用'geom_rect'和'alpha'掙扎。就在我瘋了之前,我放棄了,而是去'註解'。非常感謝@Didzis Elferts澄清這個問題! – Henrik

8

您可以嘗試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)) 

enter image description here