如何用geom_bar绘制y值为负的直立柱状图?
解决方案
核心原因是ggplot的柱状图默认从y=0开始绘制,你的数据全为负数,所以柱子会向下延伸。要实现目标效果,有两种简单方案:
方案1:用geom_segment直接绘制柱子(最直观)
这种方法直接指定柱子的起始和结束位置,完全符合需求:
library(ggplot2) # 加载数据 df <- structure(list(Target_depth_mean1 = c(3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22), TS_mean1 = c(-47, -45, -40, -43, -40, -39, -42, -42, -37, -41, -41, -38, -40, -41, -41, -40, -42, -42, -41, -38)), row.names = c(NA, -20L), class = c("tbl_df", "tbl", "data.frame")) ggplot(df, aes(x = Target_depth_mean1)) + # 从y轴底部(-48)画到对应TS_mean1的值,size控制柱子宽度 geom_segment( aes(xend = Target_depth_mean1, y = -48, yend = TS_mean1), color = "steelblue", size = 3 ) + # 设置y轴范围和刻度 scale_y_continuous( limits = c(-48, -36), breaks = seq(-48, -36, 4) ) + xlab("Target_depth_mean1") + ylab("TS_mean1") + theme_minimal()
方案2:调整geom_col的绘制基准
通过转换y值,让柱子从y轴最小值开始向上绘制,再映射回原刻度:
ggplot(df, aes(x = Target_depth_mean1)) + # 将TS_mean1转换为相对于-48的差值,作为柱子高度 geom_col(aes(y = TS_mean1 - (-48)), fill = "steelblue") + # 将转换后的刻度映射回原数值 scale_y_continuous( breaks = c(0, 4, 8, 12), labels = c("-48", "-44", "-40", "-36"), limits = c(0, 12) ) + ylab("TS_mean1") + xlab("Target_depth_mean1") + theme_minimal()
两种方案都能得到你想要的效果,方案1更直观易懂,推荐使用。
内容的提问来源于stack exchange,提问作者FishyFishies
相关产品推荐
相关产品推荐

