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

ggplot2设置虚线及图例显示异常、scale_linetype_manual不生效求助

问题根因

你的scale_linetype_manual未生效的核心原因是没有将linetype美学映射到region变量,ggplot2的scale系列函数只会作用于已经在aes()中声明过的映射属性,你只声明了color=region,所以线型的设置不会被关联到region分组,也不会同步到图例。

修正后的代码

把geom_line的美学映射补充linetype=region即可,修改后的完整代码如下:

ggplot(data = Differences_TODO, aes(x = Years,y= MeanDifference))+
  geom_line(aes(color=region, linetype=region)) +
  labs(x = "Figure 2 (Modified) - Extra hours to get to work in Israel by region of residence" , y = "Extra Hours")+
  theme_bw() + 
  theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),legend.position = c(0.2,0.8))+
  scale_x_continuous(n.breaks = 10) + 
  scale_linetype_manual(values=c("solid","dotted")) +
  theme(legend.title=element_blank()) +
  scale_color_manual(values = c("black", "black"))

补充说明

因为color和linetype都映射到了同一个变量region,ggplot2会自动合并两个维度的图例,最终图例里会同步显示每个分组对应的线型样式,你要的WBank对应虚线的效果就能正常呈现了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.12 18:33:02