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

求助:ggplot2无法设置longdash线型,始终显示实线

解决ggplot2线型无法正常显示的问题
  • 问题根源:你设置的linewidth数值过大(4和2),当线条宽度超过一定阈值时,虚线/长划线的间隙会被填充,视觉上就显示为实线。
  • 修正方案:
    1. 降低linewidth的取值,比如调整为1~1.5区间;
    2. 推荐将宽格式数据转换为长格式(tidy data),通过aes映射统一控制线型和颜色,代码更简洁易维护。

修正后的示例代码

方案1:直接调整现有代码的线条宽度

ggplot(simu_dat, aes(tset)) +
  geom_line(aes(y = N.simu1), color="plum", linetype = 1, alpha=0.4, linewidth = 1.5) + 
  geom_line(aes(y = S.simu1), color="blue4", linetype = 1, alpha=0.4, linewidth = 1.5) + 
  geom_line(aes(y = I.simu1), color="deeppink", linetype = 1, alpha=0.4, linewidth = 1.5) + 
  geom_line(aes(y = R.simu1), color="springgreen", linetype = 1, alpha=0.4, linewidth = 1.5) +

  geom_line(aes(y = S.simu2), color="blue4", linetype = 6, linewidth = 1) + 
  geom_line(aes(y = I.simu2), color="deeppink", linetype = 6, linewidth = 1) + 
  geom_line(aes(y = R.simu2), color="springgreen", linetype = 6, linewidth = 1)

方案2:转换为长格式数据绘图(更优)

先将宽格式数据整理为长格式:

library(tidyr)
simu_dat_long <- simu_dat %>%
  pivot_longer(cols = -tset, 
               names_to = c("variable", "simu"), 
               names_sep = "\\.",
               values_to = "value")

再统一绘图:

ggplot(simu_dat_long, aes(x = tset, y = value, color = variable, linetype = simu)) +
  geom_line(linewidth = 1.2, alpha = 0.7) +
  scale_color_manual(values = c("N" = "plum", "S" = "blue4", "I" = "deeppink", "R" = "springgreen")) +
  scale_linetype_manual(values = c("simu1" = 1, "simu2" = 6))

这种方式会自动生成对应图例,后续调整样式也更方便。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 16:25:19