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

R语言ggplot密度图修改线条类型无效问题求助

ggplot密度曲线设置linetype无效问题排查

问题描述

尝试在ggplot绘图中修改某条密度曲线为虚线以突出显示,使用linetype=2设置后无报错,但目标曲线仍显示为实线。相关代码如下:

Globalpdf<-ggplot() 
+ geom_density(data=GEV[1:5,], mapping = aes(x=GLocation45), 
color="black", size=3) 
+ geom_density(data=GEV[16:20,], mapping = aes(x=GLocation45), 
color="black", size=3, linetype= 2) 
+ geom_density(data=GEV[29:33,], mapping = 
aes(x=GLocation45), color="blue",size=3) 
+ geom_density(data=GEV[1:5,], mapping = 
aes(x=GLocation85), color="black", size=3) 
+ geom_density(data=GEV[16:20,], mapping = 
aes(x=GLocation85), color="black", size=3) 
+ geom_density(data=GEV[29:33,], mapping = 
aes(x=GLocation85), color="red", size=3) 
+ geom_density(data=GEV[1:5,], mapping = 
aes(x=GLocationco), color="green", size=3) 
+ geom_density(data=GEV[16:20,], mapping = 
aes(x=GLocationco), color="green", size=3) 
+ geom_density(data=GEV[29:33,], mapping = 
aes(x=GLocationco), color="green", size=3) 
+ xlab("One-day max (mm/day)") + ggtitle("Global") 
+ xlim(150, 300)+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())

问题原因

核心问题是你设置的线条宽度size=3过大——当线条宽度超过一定阈值时,虚线的短划线会相互重叠,间隙被完全填满,视觉上就和实线没有区别了,即便linetype参数已经生效。

解决方法

两种可行方案:

  • 降低目标曲线的线条宽度:将第二条geom_density的size值调小,比如改为size=2或size=1.5,让虚线的间隙能够显现出来。
  • 更换更稀疏的线型:使用间隙更大的线型,比如linetype="longdash"或linetype="twodash",配合原有的size=3也能看到虚线效果。

修改后的示例代码(以降低线条宽度为例):

Globalpdf<-ggplot() 
+ geom_density(data=GEV[1:5,], mapping = aes(x=GLocation45), 
color="black", size=3) 
+ geom_density(data=GEV[16:20,], mapping = aes(x=GLocation45), 
color="black", size=2, linetype= 2)  # 调整size值让虚线显现
+ geom_density(data=GEV[29:33,], mapping = 
aes(x=GLocation45), color="blue",size=3) 
+ geom_density(data=GEV[1:5,], mapping = 
aes(x=GLocation85), color="black", size=3) 
+ geom_density(data=GEV[16:20,], mapping = 
aes(x=GLocation85), color="black", size=3) 
+ geom_density(data=GEV[29:33,], mapping = 
aes(x=GLocation85), color="red", size=3) 
+ geom_density(data=GEV[1:5,], mapping = 
aes(x=GLocationco), color="green", size=3) 
+ geom_density(data=GEV[16:20,], mapping = 
aes(x=GLocationco), color="green", size=3) 
+ geom_density(data=GEV[29:33,], mapping = 
aes(x=GLocationco), color="green", size=3) 
+ xlab("One-day max (mm/day)") + ggtitle("Global") 
+ xlim(150, 300)+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())

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 08:42:51