如何在ggplot中将X轴设为log10刻度?负值报错的解决方法
问题:ggplot设置log10刻度X轴因置信区间下限为负报错的解决办法
问题背景
想把ggplot绘制的剂量反应曲线X轴设为log10刻度,解决图表开头的大幅拉伸问题,但因置信区间下限小于0,出现如下报错:
Error in if (zero_range(range)) zero_width else diff(range) :
missing value where TRUE/FALSE needed
In addition: Warning message:
In trans$transform(limits) : NaNs produced
当前使用连续X轴,绘图代码如下:
ggplot(drc_2, aes(x= Treatment.concentration.0, y = Total.dead), breaks = drc_2$Treatment.concentration) + geom_point(position = position_jitter(width = 0, height = 0.15)) + geom_ribbon(data=datanew, aes(x=Treatment.concentration, y = p, ymin=pmin, ymax=pmax), alpha=0.2) + geom_line(data=datanew, aes(x=Treatment.concentration, y = p)) + coord_trans(x="log") + scale_x_continuous(breaks = drc_2$Treatment.concentration) + scale_y_continuous(breaks = 0:5)+ theme_grey() + theme(axis.title = element_text(face = "bold"), plot.title = element_text(face = "bold", hjust = 0.5)) +labs(title = "Dose-Response Curve", x = "Treatment Concentration (mg/kg)", y = "Total Dead")
可行解决办法
修正置信区间下限的负值:log变换仅对正数有效,直接把
datanew中pmin列的负值替换为极小正数(比如0.001,需小于你数据中最小的非零处理浓度):datanew$pmin <- pmax(datanew$pmin, 0.001)这种方法不会破坏置信区间的整体趋势,同时能绕过log变换的NaN报错。
改用
scale_x_log10()替代coord_trans(x="log"):scale_x_log10()是专门针对X轴的log10变换工具,支持手动设置轴范围避开非正数区域,同时保留刻度的可读性。修改代码中的X轴设置部分:# 替换原有的coord_trans和scale_x_continuous scale_x_log10(breaks = drc_2$Treatment.concentration, limits = c(你的最小非零浓度值, NA))把
你的最小非零浓度值替换成你数据里实际的最小正处理浓度,确保X轴范围全为正数。处理含0浓度的情况:如果你的数据里有0浓度(比如对照组),log变换无法直接处理0,可以给所有X轴数据加一个极小偏移量,同时在刻度标签显示原数值:
# 给X数据加偏移量 drc_2$x_log <- drc_2$Treatment.concentration.0 + 0.001 datanew$x_log <- datanew$Treatment.concentration + 0.001 # 绘图时使用处理后的x_log,刻度标签保留原数值 ggplot(drc_2, aes(x= x_log, y = Total.dead)) + geom_point(position = position_jitter(width = 0, height = 0.15)) + geom_ribbon(data=datanew, aes(x=x_log, y = p, ymin=pmin, ymax=pmax), alpha=0.2) + geom_line(data=datanew, aes(x=x_log, y = p)) + scale_x_log10(breaks = drc_2$x_log, labels = drc_2$Treatment.concentration.0) + scale_y_continuous(breaks = 0:5)+ theme_grey() + theme(axis.title = element_text(face = "bold"), plot.title = element_text(face = "bold",hjust = 0.5)) + labs(title = "Dose-Response Curve", x = "Treatment Concentration (mg/kg)", y = "Total Dead")这种方法适合必须保留0浓度数据的场景,视觉上不会影响曲线趋势。
内容的提问来源于stack exchange,提问作者Georble02
相关产品推荐
相关产品推荐

