【问题标题】:coloring a segments of a curve when using stat_function in ggplot在 ggplot 中使用 stat_function 时为曲线段着色
【发布时间】:2014-11-05 01:28:41
【问题描述】:

我绘制了一条 z 曲线,并使用geom_segment为曲线下方的区域着色。

我已经使用

绘制了 z 分布
p <- ggplot(data.frame(x = c(-3, 3)), aes(x)) + stat_function(fun = dnorm)

我想为曲线段着色,使曲线的颜色与其下方的 x 轴上的颜色相匹配。

由于我使用的是stat_function,我觉得修改它的特性的机会较少。

有没有人尝试过类似的壮举并找到了方法?

【问题讨论】:

    标签: r colors ggplot2


    【解决方案1】:
    dnorm_segment <- function(x, min = 0, max = 1) dnorm(x)*ifelse(x>=min & x<=max, 1, NA)
    zero_segment <- function(x, min = 0, max = 1) ifelse(x>=min & x<=max, 0, NA)
    plot_both <- function(min, max, colour) 
    {
      args <- list(min = min, max = max)
      list(
        stat_function(fun = dnorm_segment, col = colour, size = 3, args = args, n = 1001),
        stat_function(fun = zero_segment, col = colour, size = 3, args = args, n = 1001)
      )
    }
    
    ggplot(data.frame(x = c(-3, 3)), aes(x)) + 
      stat_function(fun = dnorm) + 
      plot_both(-3, -2, "purple") +
      plot_both(-2, -1, "yellow")
    # + etc
    

    【讨论】:

    • 漂亮的答案,我真的很感动。谢谢!
    • 不幸的是,使用 ggplot2 您需要在使用之前对数据进行子集化(手动将其划分为段)。我们希望看到这个选项直接集成在 ggplot2
    猜你喜欢
    • 2017-12-15
    • 1970-01-01
    • 2018-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-04
    • 2022-01-12
    相关资源
    最近更新 更多