ggplot

2015-02-18 13 views
6

के साथ दो लाइनों के बीच छाया क्षेत्र मैं ggplot के साथ दो पंक्तियों को फोल्डिंग करता हूं और दो पंक्तियों के बीच एक विशिष्ट क्षेत्र को छाया करना चाहता हूं, जहां y = x² y = 2x से बड़ा है, जहां 2 < = x < = 3 ।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)) 

परिणाम जिसके बाद सिर्फ रेखा y के तहत क्षेत्र रंगों = 2x इस कोई बात नहीं क्या एक्स-मूल्य है, और - क्यों?

enter image description here

+1

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

+0

संभावित शिकार: http://stackoverflow.com/q/20260749/903061 – Gregor

उत्तर

10

कैसे बजाय

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 हमेशा इस तरह के कार्य के लिए काम करता है? http://www.r-bloggers.com/shading-between-two-lines-ggplot/ बताता है कि यह नहीं है। – CMichael

+1

यदि आपके डेटा में अंतरंग बिंदु नहीं है तो एक समस्या है। फ्रेम। उदाहरण: x <- seq (0,5, द्वारा = 0.2); डीएफ <- data.frame (x = x, l1 = 5-x, l2 = x); पुस्तकालय (ggplot2); ggplot (डीएफ, एईएस (x = x)) + geom_line (aes (y = l1)) + geom_line (aes (y = l2)) + geom_ribbon (aes (ymin = pmin (l1, l2), ymax = pmax (l1 , एल 2)), भरें = "नीला", अल्फा = 0.5); –

+0

उस चित्रण के लिए धन्यवाद! – CMichael

2

geom_ribbon उपयोग के बारे में मुझे लगता है कि geom_ribbon जाने का रास्ता है।

  1. डेटा हेरफेर:: वहाँ जाने के लिए 2 कदम हैं आप geom_ribbon साथ
  2. ड्रा साजिश geom_ribbon में तर्क के लिए ymin & ymax परिभाषित करने के लिए डेटा में हेरफेर करना चाहिए।

चलो मेरे उदाहरण देखें:

#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()