代码之家  ›  专栏  ›  技术社区  ›  Bogaso

在同一ggplot中组合2个正态概率图

  •  0
  • Bogaso  · 技术社区  · 3 年前

    我有2个 normal probability plots 如下所示

    library(ggplot2)
    
    # Plot 1
    ggplot(data.frame(x = c(-4, 4)), aes(x)) + 
      stat_function(fun = dnorm, args = list(mean = 0, sd = 1), col='red') + 
      stat_function(fill='red', fun = dnorm, xlim = c(-4, -1), geom = "area") + 
      stat_function(fill='red', fun = dnorm, xlim = c(-1, 4), geom = "area", alpha = 0.3) 
    
    # Plot 2
    ggplot(data.frame(x = c(-4, 4)), aes(x)) + 
      stat_function(fun = dnorm, args = list(mean = 0, sd = 2), col='blue') + 
      stat_function(fill='blue', fun = dnorm, args = list(mean = 0, sd = 2), xlim = c(-4, -1), geom = "area") + 
      stat_function(fill='blue', fun = dnorm, args = list(mean = 0, sd = 2), xlim = c(-1, 4), geom = "area", alpha = 0.3) 
    

    就个人而言,他们还不错。然而,我想将这两个绘图组合起来,并将它们放在相同的绘图窗口中 x-axis .

    我还想添加一个 legend 基于 fill 颜色在组合图中进行区分。

    有什么方法可以实现这一点吗 ggplot ?

    任何指针都会非常有用

    1 回复  |  直到 3 年前
        1
  •  0
  •   Quinten    3 年前

    你可以将两者结合起来 stat_function s,并用创建两个 aes 为您 fill 使用创建图例 scale_fill_manual 这样地:

    library(ggplot2)
    ggplot(data.frame(x = c(-4, 4)), aes(x)) + 
      stat_function(fun = dnorm, args = list(mean = 0, sd = 1), col='red') + 
      stat_function(fun = dnorm, xlim = c(-4, -1), geom = "area", aes(fill = "plot 1")) + 
      stat_function(fill='red', fun = dnorm, xlim = c(-1, 4), geom = "area", alpha = 0.3) +
      stat_function(fun = dnorm, args = list(mean = 0, sd = 2), col='blue') + 
      stat_function(fun = dnorm, args = list(mean = 0, sd = 2), xlim = c(-4, -1), geom = "area", aes(fill = "plot 2")) + 
      stat_function(fill='blue', fun = dnorm, args = list(mean = 0, sd = 2), xlim = c(-1, 4), geom = "area", alpha = 0.3) +
      scale_fill_manual(name = "Legend", values = c("red", "blue"))
    

    创建于2022-12-31 reprex v2.0.2

    推荐文章