是否可以按组使用stat_function? [英] Is it possible to use stat_function by group?

查看:97
本文介绍了是否可以按组使用stat_function?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

接着回答我的上一个答案问题,假设我要用ggplot按组绘制密度曲线,并且我想为每组生成相应的正态曲线(及其相应的均值和标准差). 我首先尝试的是

Following with the answer to my previous question, let's say that I am plotting density curves by group with ggplot and I want to produce the corresponding normal curve for each group (with their corresponding means and standard deviations). What I tried first was

library(ggplot2)
mtcars$vs <- as.factor(mtcars$vs)
ggplot(mtcars,aes(x=mpg, fill = vs, colour = vs)) + geom_density(alpha = 0.1) + 
    stat_function(fun = dnorm, args = list(mean = mean(mtcars$mpg), sd = sd(mtcars$mpg)))

但它会产生唯一的法线曲线.然后我在这个问题中找到了(答案我(看不出有什么可以帮助我的)),stat_function理解group美学,所以我尝试了

but it produces a unique normal curve. Then I found in this question (whose answer I don't see how can help me), that stat_function understands group aesthetics, so I tried

ggplot(mtcars,aes(x=mpg, fill = vs, colour = vs)) + geom_density(alpha = 0.1) + 
    stat_function(aes(group = vs), fun = dnorm, args = list(mean = mean(mtcars$mpg), sd = sd(mtcars$mpg)))

但是情节没有改变.那么如何告诉stat_function我希望每个vs组都接受参数?我还希望每条正常曲线的颜色与同一组的mpg曲线颜色相同(或相关).

but plot does not change. So how can I tell to stat_function that I want the arguments should be taken for each vs-group? I also expect the colour of each of these normal curves would be the same that (or related to) the mpg curve colour of the same group.

我也尝试过

library(dplyr)
ggplot(mtcars %>% group_by(vs),...

但没有效果.

谢谢!

推荐答案

使用循环:

示例1:两个变量

mtcars$vs <- as.factor(mtcars$vs)
p <- unique(mtcars$vs)
g <- ggplot(mtcars, aes(x = mpg, fill = vs, colour = vs))
for (i in seq_along(p))  {
  df <- mtcars %>% filter(vs == p[i])
  g <- g + geom_density(alpha = .05) +
    stat_function(data = df,
                  fun = dnorm,
                  args = list(mean = mean(df$mpg), sd = sd(df$mpg)))
}
g

示例2:两个以上的变量

mtcars$cyl <- as.factor(mtcars$cyl)
p <- unique(mtcars$cyl)
g <- ggplot(mtcars, aes(x = mpg, fill = cyl, colour = cyl))
for (i in seq_along(p))  {
  df <- mtcars %>% filter(cyl == p[i])
  g <- g + geom_density(alpha = .05) +
    stat_function(data = df,
                  fun = dnorm,
                  args = list(mean = mean(df$mpg), sd = sd(df$mpg)))
}
g

偷偷摸摸的解决方案:添加两层

library(ggplot2)

mtcars$vs <- as.factor(mtcars$vs)
mt1 <- filter(mtcars, vs == 1)
mt0 <- filter(mtcars, vs == 0)

ggplot(mtcars, aes(x = mpg, fill = vs, colour = vs)) + geom_density(alpha = 0.1) +
  stat_function(data = mt0, fun =  dnorm,
    args = list(mean = mean(mt0$mpg), sd = sd(mt0$mpg))) +
  stat_function(data = mt1, fun = dnorm,
                args = list(mean = mean(mt1$mpg), sd = sd(mt1$mpg)))

输出:

这篇关于是否可以按组使用stat_function?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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