本文介绍了在ggplot2对象的多行周围添加单独的阴影区域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我使用ggplot创建了一个简单的图:

Let's say I create a simple plot using ggplot:

data(mtcars)
var1 <- mtcars$mpg
var2 <- mtcars$mpg + 5
df <- melt(cbind(var1,var2))
ggplot(df,aes(x=X1, y=value,color=X2))+geom_line()

我想在每条绘制的线上画一个阴影区域.

I would like to draw a shaded region over each plotted line.

问题是我想为每行使用不同的值.

The problem is that I would like to use different values for each line.

我尝试使用 geom_ribbon(),但是我只能为其中一行提供阴影区域值,而不能为多行提供阴影区域.

I tried using geom_ribbon() but I could only supply the shaded region values for one of the lines, but not for multiple lines.

是否可以分别为每行绘制一个 geom_ribbon()?

Is there a way to plot a geom_ribbon() for each line separately?

推荐答案

这就是您想要的吗?

data(mtcars)
var1 <- mtcars$mpg
var2 <- mtcars$mpg + 15
df <- melt(cbind(var1,var2))
df$shadv <- rep(c(2,6),each=length(var1))
df1 <- df[df$X2=="var1",]   
df2 <- df[df$X2=="var2",] 
ggplot(df,aes(x=X1, y=value,color=X2))+
  geom_ribbon(data=df1,aes(x = X1,ymin = value - shadv, ymax = value + shadv), inherit.aes = FALSE,fill = "lightblue")+
  geom_ribbon(data=df2,aes(x = X1,ymin = value - shadv, ymax = value + shadv), inherit.aes = FALSE,fill = "lightgreen")+
  geom_point()+geom_line()

这篇关于在ggplot2对象的多行周围添加单独的阴影区域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 04:15