Shadow area between two lines with ggplot

I am creating two lines with ggplot and want to shade a specific area between the two lines, i.e. where y = x² is greater than y = 2x, where 2 <= x <= 3.

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

The result is the following, which simply shades the area under the line y = 2x, and this is independent of the value of x - why?

enter image description here

+6
source share
2 answers

How to use geom_ribbon instead

 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

+10
source

I think geom_ribbon is the way to go. There are 2 steps:

  • Data manipulation: you must manipulate data to determine ymin and ymax for arguments in geom_ribbon
  • Draw a graph using geom_ribbon.

Let's look at my example:

 #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() 
+2
source

Source: https://habr.com/ru/post/982686/


All Articles