r - 使用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
我很困惑为什么它不起作用!它只为参数的最后一个值绘制函数。
解决方案
我不得不对您的原始功能进行一些更改。基本上,调用函数时需要参数化并传入 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
推荐阅读
- nginx - Nginx server_name 正则表达式与地址根不匹配
- acumatica - 如何过滤生成经常性分录 (GL504000) 屏幕的记录
- android - Jenkins Android 构建未创建获取操作不允许错误
- python - 如何找到包含两个部分的 geojson 多边形的区域,例如一个离海岸有一个岛屿的县?
- python - 使用 django 框架从 sqlitedb 切换到 PostgreSQL 后创建了模式但没有数据存在
- reactjs - 如何在 Next.js 中使用组件作为路由?
- flutter - 我如何使用 logging 包来收集 Flutter 错误?
- typescript - 使用 TypeScript 设置 HTMLElement
- flutter - 致命错误:找不到在 MabookBook M1 上运行的“Flutter/Flutter.h”文件
- ms-access - 将组合框中的值记录到特定表字段