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

如何修改ggplot2图表趋势线样式并调整边框、图例背景等外观

ggplot2绘图需求调整实现方案

你需要的三处调整可通过修改原代码的对应部分实现,完整修改后代码如下,关键调整点说明:

  • 新增scale_linetype_manual()手动指定两组的线型:若你的Sex1M因子水平顺序为女孩在前、男孩在后,直接使用下方参数即可,若顺序相反互换values内的参数即可
  • 主题部分删除原有的panel.border设置,新增axis.line = element_line()保留x/y轴轴线,同时设置panel.background = element_blank()清空绘图区背景
  • 主题部分新增legend.key = element_blank()移除图例项的背景阴影,同时给geom_smooth添加show.legend = FALSE避免趋势线图例和点图例重叠
dr <- ggplot(DATASET, 
             aes(x=EC, 
                 y=sqrt_Percent.5, 
                 color=Sex1M, 
                 shape=Sex1M, 
                 linetype=Sex1M)) + 
  geom_point(size= 3, 
             aes(shape=Sex1M, 
                 color=Sex1M)) + 
  scale_shape_manual(values=c(1,16)) +
  # 手动指定两组线型,女孩虚线、男孩实线
  scale_linetype_manual(values = c("dashed", "solid")) +
  geom_smooth(method=lm,
              se=FALSE,
              fullrange=TRUE,
              show.legend = FALSE) + # 隐藏趋势线的图例,避免和点图例重叠
  labs(x="xaxis title", 
       y = "yaxis title", 
       fill= "") + 
  xlim(3,7) + 
  ylim(0,10)  + 
  theme(legend.position = 'right', 
        legend.title = element_blank(),
        panel.background = element_blank(),
        axis.line = element_line(color = "black"), # 保留x/y轴轴线
        legend.key = element_blank(), # 移除图例形状后方的背景阴影
        legend.background = element_rect(fill=NA,
                                         size=0.5,
                                         linetype="solid")) + 
  scale_color_grey(start = 0.0,
                   end = 0.4)

如果你的Sex1M因子水平为男孩在前、女孩在后,将scale_linetype_manual的values改为c("solid", "dashed")即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.18 01:15:01