2015-02-18 15 views
6

Tôi tạo ra hai dòng folg với ggplot và muốn che khu vực cụ thể giữa hai dòng tức là nơi y = x² lớn hơn y = 2x, trong đó 2 < = x < = 3 .Vùng tô bóng giữa hai hàng với ggplot

# create data # 

x<-as.data.frame(c(1,2,3,4)) 
colnames(x)<-"x" 
x$twox<-2*x$x 
x$x2<-x$x^2 

# Set colours # 

blue<-rgb(0.8, 0.8, 1, alpha=0.25) 
clear<-rgb(1, 0, 0, alpha=0.0001) 

# Define region to fill # 

x$fill <- "no fill" 
x$fill[(x$x2 > x$twox) & (x$x <= 3 & x$x >= 2)] <- "fill" 

# Plot # 

ggplot(x, aes(x=x, y=twox)) + 
    geom_line(aes(y = twox)) + 
    geom_line(aes(y = x2)) + 
    geom_area(aes(fill=fill)) + 
    scale_y_continuous(expand = c(0, 0), limits=c(0,20)) + 
    scale_x_continuous(expand = c(0, 0), limits=c(0,5)) + 
    scale_fill_manual(values=c(clear,blue)) 

Kết quả là sau đây chỉ che khu vực dưới dòng y = 2x và điều này không quan trọng giá trị x là gì - tại sao?

enter image description here

+1

http://www.r-bloggers.com/shading-between-two-lines-ggplot/ – CMichael

+0

thể dupe: http://stackoverflow.com/q/20260749/903061 – Gregor

Trả lời

10

Làm thế nào về việc sử dụng geom_ribbon thay

ggplot(x, aes(x=x, y=twox)) + 
    geom_line(aes(y = twox)) + 
    geom_line(aes(y = x2)) + 
    geom_ribbon(data=subset(x, 2 <= x & x <= 3), 
      aes(ymin=twox,ymax=x2), fill="blue", alpha="0.5") + 
    scale_y_continuous(expand = c(0, 0), limits=c(0,20)) + 
    scale_x_continuous(expand = c(0, 0), limits=c(0,5)) + 
    scale_fill_manual(values=c(clear,blue)) 

plot

+0

Geom_ribbon có luôn hoạt động cho loại nhiệm vụ này không? http://www.r-bloggers.com/shading-between-two-lines-ggplot/ nói rằng nó không. – CMichael

+1

Có vấn đề nếu bạn không có điểm giao nhau trong data.frame của mình. Ví dụ: x <- seq (0,5, by = 0,2); df <- data.frame (x = x, l1 = 5-x, l2 = x); thư viện (ggplot2); ggplot (df, aes (x = x)) + geom_line (aes (y = l1)) + geom_line (aes (y = l2)) + geom_ribbon (aes (ymin = pmin (l1, l2), ymax = pmax (l1 , l2)), fill = "blue", alpha = 0,5); –

+0

Cảm ơn bạn đã minh họa! – CMichael

2

Tôi nghĩ geom_ribbon đó là con đường để đi. Có 2 bước để đi:

  1. Data Manipulation: Bạn nên thao tác dữ liệu để xác định ymin ymax & cho các đối số trong geom_ribbon
  2. cốt truyện Draw với geom_ribbon.

Hãy xem ví dụ của tôi:

#Data 
library(gcookbook) 
# Data Manipulation 
cb <-subset(climate,Source=="Berkeley") 
cb$valence[cb$Anomaly10y >= 0.3] <- "pos" 
cb$valence[cb$Anomaly10y < 0.3] <- "neg" 
cb$min <- ifelse(cb$Anomaly10y >= 0.3, 0.3, cb$Anomaly10y) 
cb$max <- ifelse(cb$Anomaly10y >= 0.3, cb$Anomaly10y, 0.3) 

#Drawing plot 
ggplot(cb,aes(x=Year,y=Anomaly10y)) + 
geom_ribbon(aes(ymin = min, ymax = max, fill = valence), alpha = 0.75) + 
scale_fill_manual(values = c("blue", "orange")) + 
geom_line(aes(col = valence), size = 1) + 
scale_color_manual(values = c("blue", "orange")) + 
geom_hline(yintercept=0.3, col = "blue") + 
theme_bw() 
Các vấn đề liên quan