首页 > 解决方案 > 使用ggplot绘制各种参数值的密度函数

问题描述

我正在尝试为两个参数的各种值绘制密度函数,如下所示:

f_bdsn<-function(x){
  2*(1+delta1*x^2)*dnorm(x)*pnorm(alpha1*x)/(1+delta1)
  }
alpha1<<-0
alpha1<<-0
group1=paste("alpha=",alpha1,", delta=",delta1)
p9 <- ggplot(data.frame(x = c(-4, 4)), aes(x = x)) +
  stat_function(fun = f_bdsn, aes(colour = group1)) 
alpha1<<-0
delta1<<-6
group2=paste("alpha=",alpha1,", delta=",delta1)
p9 <-p9 + stat_function(fun = f_bdsn,
                    aes(colour = group2)) 
p9

我很困惑为什么它不起作用!它只为参数的最后一个值绘制函数。

标签: rggplot2

解决方案


我不得不对您的原始功能进行一些更改。基本上,调用函数时需要参数化并传入 alpha 和 delta 值。然后使用 for 循环,我们可以创建任意数量的组。

# Create Function which takes in an x value, a delta value and an alpha value
f_bdsn<-function(x, delta_input, alpha_input){
  2*(1+delta_input*x^2)*dnorm(x)*pnorm(alpha_input*x)/(1+delta_input)
}

# Define the number of groups, alpha values and delta values
# Note the length of both alpha_values and delta_values are the same
n_groups <- 2
alpha_values <- c(0, 10)
delta_values <- c(6, 16)

# Create inital plot
plot <- ggplot(data.frame(x = c(-4, 4)), aes(x = x))

# Create a for loop to through each group
for (i in seq_len(n_groups)) {
  # Define the group name
  group_name <- paste("alpha=", alpha_values[i],", delta=", delta_values[i])
  
  # Add the values to the main plot variable
  plot <- plot + 
    stat_function(fun = f_bdsn, args = list(delta_input = delta_values[i],
                                            alpha_input = alpha_values[i]),
                  aes(colour = group_name))
}

# Print Plot
plot

推荐阅读