如何在ggplot2密度曲线下遮蔽特定区域? [英] How to shade specific region under ggplot2 density curve?

查看:62
本文介绍了如何在ggplot2密度曲线下遮蔽特定区域?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(这与 jlhoward 的回答几乎相同,但从 ggplot 中获取计算值).

Related post here

My intention is to shade area an area underneath the density curve that lie between two points. In this example, I would like to shade the areas between the values .25 and .5.

I have been able to plot my density curve with the following:

    setwd("D:/Workspace")

    # -- create dataframe

    coursename <- c('Math','Math','Math','Math','Math')
    value <- c(.12, .4, .5, .8, .9)
    df <- data.frame(coursename, value)

    library(ggplot2)

    density_plot <- ggplot(aes(x=value, colour=coursename, fill=coursename), data=df) +
                      geom_density(alpha=.3) +
                      geom_vline(aes(xintercept=.5), colour="blue", data=df, linetype="dashed", size=1) +
                      scale_x_continuous(breaks=c(0, .25, .5, .75, 1), labels=c("0", ".25", ".5", ".75", "1")) +
                      coord_cartesian(xlim = c(0.01, 1.01)) +
                      theme(axis.title.y=element_blank(), axis.text.y=element_blank()) +
                      ggtitle("sample data")

    density_plot

I've tried using the following code to shade the area between .25 and .5:

    x1 <- min(which(df$value >=.25))
    x2 <- max(which(df$value <=.5))

    with(density_plot, polygon(x=c(x[c(x1,x1:x2,x2)]), y=c(0, y[x1:x2], 0), col="gray"))

But it just generates the following error:

Error in xy.coords(x, y) : object 'y' not found

解决方案

Or use ggplot2 against itself!

coursename <- c('Math','Math','Math','Math','Math')
value <- c(.12, .4, .5, .8, .9)
df <- data.frame(coursename, value)

library(ggplot2)

ggplot() +
  geom_density(data=df, 
               aes(x=value, colour=coursename, fill=coursename),
               alpha=.3) +
  geom_vline(data=df, 
             aes(xintercept=.5), 
             colour="blue", linetype="dashed", size=1) +
  scale_x_continuous(breaks=c(0, .25, .5, .75, 1), 
                     labels=c("0", ".25", ".5", ".75", "1")) +
  coord_cartesian(xlim = c(0.01, 1.01)) +
  theme(axis.title.y=element_blank(), 
        axis.text.y=element_blank()) +
  ggtitle("sample data") -> density_plot

density_plot

dpb <- ggplot_build(density_plot)

x1 <- min(which(dpb$data[[1]]$x >=.25))
x2 <- max(which(dpb$data[[1]]$x <=.5))

density_plot +
  geom_area(data=data.frame(x=dpb$data[[1]]$x[x1:x2],
                       y=dpb$data[[1]]$y[x1:x2]),
            aes(x=x, y=y), fill="grey")

(this pretty much does the same thing as jlhoward's answer but grabs the calculated values from ggplot).

这篇关于如何在ggplot2密度曲线下遮蔽特定区域?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆