You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用ggplot绘制GEV分布时出现dgev参数未使用错误的求助

解决ggplot绘制GEV分布报错问题

问题说明

使用base R的plot+lines可以成功绘制GEV分布曲线,但改用ggplot2尝试时触发报错:

Error in dgev(seq(1, 500), mu = 170.19, sigma = 53.59, xi = 0.09) : 
unused arguments (mu = 170.19, sigma = 53.59, xi = 0.09)

原base plot代码:

library(evir)

Gpdf <- plot(dgev(seq(1,500),mu=170.19, sigma=53.59, xi=0.09),type = 'l',col='black', lty = 1, ylim = c(0,0.010), lwd = 5, ylab = "Density",xlab = "mm/day", cex.lab = 2, cex.axis = 2, main = "Global", cex.main = 4) + lines(dgev(seq(1,500),mu = 195.38, sigma = 63.13, xi = -0.05),type='l', col = 'blue', lty = 1, lwd = 5) 

原ggplot尝试代码:

library(ggplot2)
library(evir)

Gpdf <- ggplot(geom_density(dgev(seq(1,500),mu = 170.19, sigma = 53.59, xi = 0.09), color = "black", size = 3, linetype = "solid", ylim = c(0,0.010), ylab = "Density", xlab= "mm/day", main = "Global", cex.main=4) + geom_density(dgev(seq(1,500),mu = 195.38, sigma = 63.13, xi = -0.05), col="blue", linetype = "solid") + theme(plot.title = element_text(size = 54))+ theme(axis.title = element_text(size = 54)) + theme(axis.text = element_text(size = 54))+theme(panel.background = element_blank()) + theme(plot.title = element_text(size = 54, face = "bold")))

报错原因

  • 参数名不匹配:evir包的dgev函数参数名是loc(位置参数,对应你用的mu)、scale(尺度参数,对应sigma)、shape(形状参数,对应xi),而非你使用的mu/sigma/xi。
  • 包函数覆盖:之前base plot能运行,是因为当时环境中加载了其他支持mu/sigma/xi参数的包(比如fExtremes),该包的dgev函数覆盖了evir::dgev。

修正后的ggplot代码

ggplot2是基于数据框的绘图框架,不能直接将密度值传给geom_density(该函数用于对原始数据计算密度),需先构造包含x值和对应密度值的数据框,再用geom_line绘制:

library(ggplot2)
library(evir)

# 生成x轴序列
x_seq <- seq(1, 500)

# 计算两组GEV分布的密度值,构造数据框
df_gev <- data.frame(
  x = rep(x_seq, 2),
  density = c(
    dgev(x_seq, loc = 170.19, scale = 53.59, shape = 0.09),
    dgev(x_seq, loc = 195.38, scale = 63.13, shape = -0.05)
  ),
  group = rep(c("Group1", "Group2"), each = length(x_seq))
)

# 绘制ggplot图
Gpdf <- ggplot(df_gev, aes(x = x, y = density, color = group)) +
  geom_line(size = 3, linetype = "solid") +
  scale_color_manual(values = c("Group1" = "black", "Group2" = "blue")) +
  labs(title = "Global", x = "mm/day", y = "Density") +
  ylim(0, 0.010) +
  theme(
    plot.title = element_text(size = 54, face = "bold"),
    axis.title = element_text(size = 54),
    axis.text = element_text(size = 54),
    panel.background = element_blank(),
    legend.position = "none" # 不需要图例可删除此行
  )

# 显示图形
print(Gpdf)

额外说明

  • 若坚持使用mu/sigma/xi参数,可加载fExtremes包调用fExtremes::dgev,但需注意包之间的函数冲突问题。
  • ggplot2的参数设置逻辑与base plot不同,标签、范围等设置需通过labs()、ylim()等函数实现,不能直接在geom中传递ylab/xlab这类参数。

内容的提问来源于stack exchange,提问作者Android17

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 16:40:31