使用ggplot绘制带对数Y轴的柱状图时柱子倒置问题求助
问题修正方案
数据集信息
tibble [56 x 3] (S3: tbl_df/tbl/data.frame) $ Species : Factor w/ 56 levels "OC1","OC2","OC3",..: 1 2 3 4 5 6 7 8 9 10 ... $ Residential: num [1:56] 0 0.077 0.0997 0.1023 0.2268 ... $ FW_AVG : num [1:56] 0.022 0.0944 0.1121 0.0641 0.0659 ...
当前问题与需求
- 需求:绘制以
Species为X轴、FW_AVG为Y轴的柱状图,同时叠加Residential的散点,匹配参考图样式 - 问题:当前绘制的柱子出现错位/倒置,且未添加散点层
当前使用代码
ggplot(data, aes(x = Species, y = FW_AVG)) + geom_bar(stat = "identity", fill = "steelblue", position = position_dodge(width = 0.7)) + scale_y_log10() + labs(x = "Species", y = "FW_AVG (log scale)") + theme_minimal() + theme(axis.text.x = element_text(angle = 45, hjust = 1))
错误点排查
- 多余的
position_dodge参数:单组柱状图不需要位置偏移,该参数会让柱子偏离X轴刻度中心,造成视觉上的"倒置"或错位 - 缺少散点层:未添加
geom_point来展示Residential数据 - log轴0值问题:
Residential包含0值,直接使用scale_y_log10()会丢失该数据点 - 因子顺序不符:默认
Species按OC1-OC56排序,参考图大概率是按FW_AVG值排序,导致视觉差异
修正后的代码
# 按FW_AVG从小到大重新排序Species因子 data$Species <- reorder(data$Species, data$FW_AVG) ggplot(data, aes(x = Species)) + # 绘制FW_AVG柱状图,移除不必要的position_dodge geom_bar(aes(y = FW_AVG), stat = "identity", fill = "steelblue") + # 添加Residential散点,用颜色区分 geom_point(aes(y = Residential), color = "darkred", size = 2) + # 处理log轴0值,设置下限为极小值避免报错 scale_y_log10(limits = c(1e-3, NA), labels = scales::comma) + labs(x = "Species", y = "Value (log scale)") + theme_minimal() + theme(axis.text.x = element_text(angle = 45, hjust = 1))
内容的提问来源于stack exchange,提问作者Jyoti
相关产品推荐
相关产品推荐

