用ggplot中的函数定义的两行之间的阴影区域 [英] Shade area between two lines defined with function in ggplot
问题描述
我试图找到在函数定义的ggplot中的两条线之间加阴影的可能性.我找到了一些使用geom_area或geom_ribbon的解决方案,但是在这两种情况下,都需要一个用于定义ymin和ymax的数据库.还有其他可能性吗?以这样的方式定义ymin和ymax的功能也与线条相同?
I tried to find the possibilities how to shade the area between two lines in ggplot that are defined by function. I found some solutions using geom_area or geom_ribbon but in both cases you need a database in which you define ymin and ymax. Is there any other possibility? In the way that the ymin and ymax are defined also with same functions as the lines?
这是我的样品:
myplot <- ggplot(data.frame(x=c(0, 100)), aes(x=x)) +
stat_function(fun= function(x)20*sqrt(x), geom="line", colour= "black", size= 1) +
stat_function(fun= function(x)50*sqrt(x), geom="line", colour= "black", size= 1)
myplot
谢谢您的帮助.
推荐答案
尝试将函数放入提供图形的数据框中.然后,您可以使用 geom_ribbon
填充两个函数之间的区域.
Try putting the functions into the data frame that feeds the figure. Then you can use geom_ribbon
to fill in the area between the two functions.
mydata = data.frame(x=c(0:100),
func1 = sapply(mydata$x, FUN = function(x){20*sqrt(x)}),
func2 = sapply(mydata$x, FUN = function(x){50*sqrt(x)}))
ggplot(mydata, aes(x=x, y = func2)) +
geom_line(aes(y = func1)) +
geom_line(aes(y = func2)) +
geom_ribbon(aes(ymin = func2, ymax = func1), fill = "blue", alpha = .5)
这篇关于用ggplot中的函数定义的两行之间的阴影区域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!