如何修改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
相关产品推荐
相关产品推荐

