Home > Blockchain >  ggplot: shaded area above a curve and between specific lines w.r.t. x
ggplot: shaded area above a curve and between specific lines w.r.t. x

Time:09-29

I want to produce the following plot

x   = seq(-3,3,0.005)
y   = x**3
df  = data.frame('x' = x, 'y' = y)

library(ggplot2)
ggplot(df, aes(x, y))   
  geom_line()   
  geom_hline(yintercept = 0)   geom_vline(xintercept = 0)  
  geom_vline(xintercept = c(-2,-1,0,2), lty = 'dashed', color = 'red')  
  ylab(expression('f(x) = '~X^3))   
  theme_classic()  
  geom_ribbon(aes(ymin = y, ymax = max(y)), alpha = 0.2, fill = 'blue')  
  geom_ribbon(aes(xmin = -2, xmax = -1), alpha = 0.2, fill = 'red')   
  geom_ribbon(aes(xmin = 0, xmax = 2), alpha = 0.2, fill = 'red')

I want only the shaded area where the blue and red intersect. enter image description here

Is there a way to obtain such plot using ggplot or even base r?

CodePudding user response:

ggplot(df, aes(x, y))   
  geom_line()   
  geom_hline(yintercept = 0)   geom_vline(xintercept = 0)  
  geom_vline(xintercept = c(-2,-1,0,2), lty = 'dashed', color = 'red')  
  ylab(expression('f(x) = '~X^3))   
  theme_classic()  
  geom_ribbon(data=subset(df, -2 <= x & x <= -1),
              aes(ymin = y, ymax = max(df$y)), alpha = 0.2, fill = 'blue')  
  geom_ribbon(data=subset(df, 0 <= x & x <= 2),
              aes(ymin = y, ymax = max(df$y)), alpha = 0.2, fill = 'blue') 
  • Related