用ggplot在两行之间的阴影区域

use*_*648 11 r fill ggplot2

我用ggplot生成下面的两行,并且想要遮蔽两行之间的特定区域,即y =x²大于y = 2x,其中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))
Run Code Online (Sandbox Code Playgroud)

结果如下,只是阴影线y = 2x下的区域,这不管x值是什么 - 为什么?

在此输入图像描述

Tob*_*sen 22

如何使用geom_ribbon而不是

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))
Run Code Online (Sandbox Code Playgroud)

情节

  • 如果您的data.frame中没有交点,则会出现问题。示例:x &lt;-seq(0,5,by = 0.2); df &lt;-data.frame(x = x,l1 = 5-x,l2 = x); 库(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)),填充=“ blue”,alpha = 0.5); (2认同)

小智 5

我认为 geom_ribbon 是要走的路。有2个步骤:

  1. 数据操作:您应该操作数据来为 geom_ribbon 中的参数定义 ymin 和 ymax
  2. 用 geom_ribbon 画图。

让我们看看我的例子:

#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()
Run Code Online (Sandbox Code Playgroud)