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

时间:2015-02-18 14:57:57

标签: r ggplot2 fill

我用ggplot产生下面的两行并且想要遮蔽两行之间的特定区域,即y = x 2大于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))

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

enter image description here

2 个答案:

答案 0 :(得分:17)

如何使用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))

plot

答案 1 :(得分:3)

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

  1. 数据处理:您应该操纵数据来定义ymin&amp; geom_ribbon
  2. 中参数的ymax
  3. 使用geom_ribbon绘制绘图。
  4. 让我们看看我的例子:

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