2017-09-15 106 views
1

enter image description here在ggplot2中,如何避免geom_rect擴展劇情的界限?

隨着附代碼段,geom_rect延伸的情節,即,對於2016年的垂直帶,即使沒有數據被包含在該間隔繪製的極限。

我想矩形只有在它們包含數據點時纔會繪製。

我讀了幫助annotate,它明確地說,annotate正好有我geom_rect和我想避免看到的行爲。

詳細

注意,所有的位置美學縮放(即,它們將擴大情節 限度,因此它們是可見的),但所有其他美學 設置。這意味着使用此功能創建的圖層永遠不會影響圖例 。

library(ggplot2) 
days<-rep(Sys.Date(),100)+seq(1,100) 
v<-sin(as.numeric(days)) 
df<-data.frame(days=c(days,days),v=c(v,cos(v)+.1),n=c(rep('a',100),rep('b',100))) 

shade <- data.frame(x1=c(as.Date('2016-10-15'),as.Date('2017-11-11')), 
        x2=c(as.Date('2016-10-20'),as.Date('2017-11-13')), 
        y1=c(-Inf,-Inf), y2=c(Inf,Inf)) 

plot(ggplot(df, aes(x=days, y=v, colour=n)) + 
    geom_line() + 
    geom_rect(data=shade, inherit.aes = F, 
      aes(xmin=x1, xmax=x2, ymin=y1, ymax=y2), 
      color = 'grey', alpha=0.2) + 
    geom_point()) 

回答

2

將根據您的具體情況range(df$days)工作設置限制?

my_limits <- range(df$days) 

ggplot(df, aes(x=days, y=v, colour=n)) + 
    geom_line() + 
    geom_rect(data=shade, inherit.aes = F, 
      aes(xmin=x1, xmax=x2, ymin=y1, ymax=y2), 
      color = 'grey', alpha=0.2) + 
    geom_point() + 
    scale_x_date(limits = my_limits) # See scale_x_datetime in case the data has time too. 

enter image description here

+0

是的,它適合我的情況。 –

1

我的解決辦法創建矩形情節,並將其添加至主情節如果daysshade間隔內。日期操作使用lubridate包執行。

# Main plot that doesn't change depending on time interval 
pMain <- ggplot(df, aes(days, v, colour = n)) + 
    geom_line() + 
    geom_point() 

# Time manipulation part 
library(lubridate) 
# Turn character string to dates 
df$days <- ymd(df$days) 
shade$x1 <- ymd(shade$x1) 
shade$x2 <- ymd(shade$x2) 

# Check which shade entries contain days 
foo <- c() 
for(i in nrow(shade)) { 
    bar <- any(df$days %within% interval(shade[i, ]$x1, shade[i, ]$x2)) 
    if (bar) { 
     foo <- c(foo, i) 
    } 
} 

# If any interval contained days 
# Create rectangle plot and add it to the main plot 
CONTAINS <- length(foo) > 0 
if (CONTAINS) { 
    pRect <- geom_rect(data=shade[foo, ], inherit.aes = F, 
       aes(xmin=x1, xmax=x2, ymin=y1, ymax=y2), 
       color = 'grey', alpha=0.2) 
    pMain <- pMain + pRect 
} 
plot(pMain) 

enter image description here

1

賦予其ggplot之前就過濾shade

library(dplyr) 
library(ggplot2) 
days<-rep(Sys.Date(),100)+seq(1,100) 
v<-sin(as.numeric(days)) 
df<-data.frame(days=c(days,days),v=c(v,cos(v)+.1),n=c(rep('a',100),rep('b',100))) 

shade <- data.frame(x1=c(as.Date('2016-10-15'),as.Date('2017-11-11')), 
        x2=c(as.Date('2016-10-20'),as.Date('2017-11-13')), 
        y1=c(-Inf,-Inf), y2=c(Inf,Inf)) %>% 
    filter(between(x1, min(df$days), max(df$days)), between(x2, min(df$days), max(df$days))) 

plot(ggplot(df, aes(x=days, y=v, colour=n)) + 
     geom_line() + 
     geom_rect(data=shade, inherit.aes = F, 
       aes(xmin=x1, xmax=x2, ymin=y1, ymax=y2), 
       color = 'grey', alpha=0.2) + 
     geom_point()) 
+0

「shade2」在哪裏定義? –

+0

Woops;它應該是'陰影'。我已經編輯了答案。 – MrGumble

相關問題