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

如何为自定义坐标轴的R密度图添加指定轴标签?

问题描述

希望为以下R代码生成的密度图添加轴标签:x轴为原纤维直径(nm),y轴为密度,请问如何实现?

现有代码:

den1 = density(CDE1$V1)
den2 = density(CDE1$V2)

col1 = hsv(h = 0.65, s = 0.6, v = 0.8, alpha = 0.5)
col2 = hsv(h = 0.85, s = 0.6, v = 0.8, alpha = 0.5)

op = par(mar = c(3, 3, 2, 2))
plot.new( )
plot.window(xlim = c(25,65), ylim = c(0, 0.14))
axis(side = 1, pos = 0, at = seq(from = 25, to = 65, by = 5), col = "gray20", 
     lwd.ticks = 0.25, cex.axis = 1, col.axis = "gray20", lwd = 1.5)
axis(side = 2, pos = 25, at = seq(from = 0, to = 0.14, by = 0.02), col = "gray20", 
     las = 2, lwd.ticks = 0.5, cex.axis = 1, col.axis = "gray20", lwd = 1.5)
polygon(den1$x, den1$y, col = col1, border ="black",lwd = 2)
polygon(den2$x, den2$y, col = col2, border ="black",lwd = 2)
text(52, 0.10, labels ="CDET", col =col1, cex = 1.25,font=2)
text(35, 0.03, labels ="SDFT", col =col2, cex = 1.25,font=2)
par(op)
title(main="Gestational Day 100/283")

当前绘图效果:展示了CDET和SDFT两个密度多边形,x轴范围25-65,y轴范围0-0.14,但缺少指定的轴标签。

解决方法

由于你使用R基础绘图的手动构建模式(plot.new() + plot.window()),可以通过以下两种方式添加轴标签:

方法1:扩展title()函数参数

直接在现有title()调用中添加x轴和y轴标签参数,适配当前边距设置:

title(main="妊娠第100/283天", xlab="原纤维直径(nm)", ylab="密度", line=1)
  • line参数控制标签与轴的距离,设为1可匹配你当前mar = c(3, 3, 2, 2)的边距配置。

方法2:使用mtext()灵活控制

如果需要更精细的位置调整,可在绘制轴之后添加:

# 添加x轴标签
mtext("原纤维直径(nm)", side=1, line=1.5, cex=1, col="gray20")
# 添加y轴标签
mtext("密度", side=2, line=1.5, cex=1, col="gray20", las=0)
  • side=1对应x轴,side=2对应y轴;line控制标签与轴的间距;las=0让y轴标签保持垂直,与你设置的axis(side=2, las=2)风格匹配。

修改后的完整代码

den1 = density(CDE1$V1)
den2 = density(CDE1$V2)

col1 = hsv(h = 0.65, s = 0.6, v = 0.8, alpha = 0.5)
col2 = hsv(h = 0.85, s = 0.6, v = 0.8, alpha = 0.5)

op = par(mar = c(3, 3, 2, 2))
plot.new( )
plot.window(xlim = c(25,65), ylim = c(0, 0.14))
axis(side = 1, pos = 0, at = seq(from = 25, to = 65, by = 5), col = "gray20", 
     lwd.ticks = 0.25, cex.axis = 1, col.axis = "gray20", lwd = 1.5)
axis(side = 2, pos = 25, at = seq(from = 0, to = 0.14, by = 0.02), col = "gray20", 
     las = 2, lwd.ticks = 0.5, cex.axis = 1, col.axis = "gray20", lwd = 1.5)
# 添加轴标签(方法2示例)
mtext("原纤维直径(nm)", side=1, line=1.5, cex=1, col="gray20")
mtext("密度", side=2, line=1.5, cex=1, col="gray20", las=0)
polygon(den1$x, den1$y, col = col1, border ="black",lwd = 2)
polygon(den2$x, den2$y, col = col2, border ="black",lwd = 2)
text(52, 0.10, labels ="CDET", col =col1, cex = 1.25,font=2)
text(35, 0.03, labels ="SDFT", col =col2, cex = 1.25,font=2)
par(op)
title(main="妊娠第100/283天")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 18:54:38