ggplot2 - 带ggplot的两条直线之间的阴影区域

  显示原文与译文双语对照的内容
0 0

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

那么使用 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

原作者:
...