R语言 在同一ggplot中合并2个正态概率图

6qqygrtg  于 2023-01-03  发布在  其他
关注(0)|答案(1)|浏览(300)

我有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把它们放在同一个图窗口中。
我还想在组合图中添加基于fill颜色的legend,以区分它们。
有什么方法可以用ggplot实现这一点吗?
任何指针都会很有帮助

db2dz4w8

db2dz4w81#

您可以将这两个stat_function组合起来,并为fill创建两个aes,从而使用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

相关问题