两点ggplot2之间的阴影(刻面)密度图

时间:2021-11-15 14:55:35

I am attempting to create a plot that shades the area under the curve of a density plot between two points. Here's what I have so far:

我试图创建一个阴影区域在两点之间的密度曲线下的区域。这是我到目前为止所拥有的:

df.ind <- data.frame(x=rnorm(1000))
df.group <- data.frame(group = factor(1:20))
df.group$gr.mean <- rnorm(20)
df.group$width <- 1 + abs(rnorm(20))
df.group$upper <- df.group$gr.mean + df.group$width
df.group$lower <- df.group$gr.mean - df.group$width

I can then create a ggplot where I use the density of x from df.ind and plot it 20 different times (by each group). I then overlay the vertical lines. What I want to do is shade the area between the lines.

然后我可以创建一个ggplot,其中我使用来自df.ind的x的密度并绘制20个不同的时间(按每组)。然后我覆盖垂直线。我想要做的是遮蔽线条之间的区域。

ggplot(df.group) + 
  stat_density(data=df.ind, mapping=aes(x), 
               geom="line", position="dodge") +
  facet_wrap(~group) + 
  geom_vline(aes(xintercept=lower)) +
  geom_vline(aes(xintercept=upper))

I'm aware of a similar question here: ggplot2 shade area under density curve by group and here: Shading a kernel density plot between two points.

我在这里也知道一个类似的问题:ggplot2密度曲线下面的阴影面积和这里:阴影两点之间的核心密度图。

But my data come from two different data.frame objects. Therefore, I can't use the clever trick they use to aggregate the data...

但我的数据来自两个不同的data.frame对象。因此,我无法使用他们用来聚合数据的聪明技巧......

1 个解决方案

#1


Like I mentioned in the comments, you are going to have to do the work of creating data specifically for each panel yourself. Here's one way

就像我在评论中提到的那样,您将不得不自己专门为每个面板创建数据。这是一种方式

# calculate density
dx<-density(df.ind$x)

#define areas for each group
mm <- do.call(rbind, Map(function(g, l,u) {
    data.frame(group=g, x=dx$x, y=dx$y, below=dx$x<l, above= dx$x > u)
}, df.group$group, df.group$lower, df.group$upper))

#plot data
p2<-ggplot(mm) + 
   geom_area(aes(x, y, fill=interaction(below,above))) + 
   geom_vline(data=df.group, aes(xintercept=lower)) +
   geom_vline(data=df.group, aes(xintercept=upper)) +
   facet_wrap(~group)

两点ggplot2之间的阴影(刻面)密度图

#1


Like I mentioned in the comments, you are going to have to do the work of creating data specifically for each panel yourself. Here's one way

就像我在评论中提到的那样,您将不得不自己专门为每个面板创建数据。这是一种方式

# calculate density
dx<-density(df.ind$x)

#define areas for each group
mm <- do.call(rbind, Map(function(g, l,u) {
    data.frame(group=g, x=dx$x, y=dx$y, below=dx$x<l, above= dx$x > u)
}, df.group$group, df.group$lower, df.group$upper))

#plot data
p2<-ggplot(mm) + 
   geom_area(aes(x, y, fill=interaction(below,above))) + 
   geom_vline(data=df.group, aes(xintercept=lower)) +
   geom_vline(data=df.group, aes(xintercept=upper)) +
   facet_wrap(~group)

两点ggplot2之间的阴影(刻面)密度图