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

如何为多个geom_function()添加可正确显示线型的自定义图例

问题解决方法

你当前代码的问题是仅为每个geom_function直接指定了linetype固定值,没有将线型映射到ggplot的美学维度中,因此scale_linetype_manual的规则无法匹配到对应图层,导致图例显示异常。

修改后的可正常运行代码如下:

library(tidyverse)
ggplot(data = data.frame(x = c(0, 1)), aes(x)) +
  geom_function(fun = dnorm, n = 10001,
                args = list(mean = .5, sd = .125),
                aes(linetype = "a"), 
                show.legend = T) +
  geom_function(fun = dbeta, n = 10001,
                args = list(shape1 = 10, shape2 = 8),
                aes(linetype = "b"), 
                show.legend = T) +
  geom_function(fun = dbeta, n = 10001,
                args = list(shape1 = 15, shape2 = 8),
                aes(linetype = "c"), 
                show.legend = T) +
  geom_function(fun = dbeta, n = 10001,
                args = list(shape1 = 20, shape2 = 8),
                aes(linetype = "d"), 
                show.legend = T) +
  ylab("f(θ)") +
  xlab("θ") +
  scale_linetype_manual(
    name = "分布类型", # 可自定义图例标题
    values = c("a" = 1,
               "b" = 5,
               "c" = 2,
               "d" = 3)
  )+
  theme_test(base_size = 20)

修改说明:

  • 核心改动是把每个图层的线型设置从直接写linetype = 数值,改为在aes()中为linetype映射赋值你预设的标签(a/b/c/d),这样ggplot会自动将图层和scale_linetype_manual中定义的规则关联
  • 标签可以根据你的需求替换为实际分布名称,只要和scale_linetype_manual的values键名对应即可,替换后图例就会显示你自定义的分布名称,而非a/b/c/d。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 15:54:03