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

如何在R语言中基于上下限数据绘制范围条形图?

在R语言中绘制范围条形图的方法

你需要的这种展示上下限范围的条形图,其实就是用每个X轴位置对应的上下限差值绘制条形,同时标记出上下限的位置。下面我用你提供的示例数据,分别用Base R和ggplot2两种常用方式实现,都能达到类似示例图的效果~

第一步:整理数据

首先把你给出的示例数据转换成R能处理的数据格式,同时计算每个条形的高度(上下限的差值):

# 定义示例数据
upper <- c(1260, 1284, 1296, 1308, 1320)
lower <- c(1272, 1272, 1284, 1296, 1308)
x <- 1:5

# 合并成数据框
df <- data.frame(x, lower, upper)
# 计算每个条形的高度(上限 - 下限)
df$height <- df$upper - df$lower

方法一:使用Base R绘制

Base R可以通过barplot()绘制基础条形,再用segments()添加上下限的垂直线,points()标记上下限的数值点:

# 绘制基础条形图,设置y轴范围以容纳上下限
bar_plt <- barplot(df$height, 
                   beside = TRUE,
                   ylim = c(min(df$lower)-10, max(df$upper)+10), # 预留上下空间避免截断
                   names.arg = df$x,
                   col = "#87CEEB", # 设置条形颜色
                   ylab = "Y Value",
                   xlab = "X axis")

# 添加连接上下限的垂直线
segments(x0 = bar_plt, y0 = df$lower, y1 = df$upper, lwd = 2)

# 标记下限和上限的点
points(x = bar_plt, y = df$lower, pch = 19, col = "red")
points(x = bar_plt, y = df$upper, pch = 19, col = "blue")

# 添加图例说明
legend("topright", 
       legend = c("Lower Limit", "Upper Limit"),
       pch = 19, 
       col = c("red", "blue"),
       bty = "n") # 去掉图例边框

方法二:使用ggplot2绘制

ggplot2的语法更灵活,视觉效果也更美观,常用geom_col()画条形,搭配geom_errorbar()展示范围:
首先确保你已经安装了ggplot2包(没装过的话先运行install.packages("ggplot2")):

library(ggplot2)

ggplot(df, aes(x = factor(x), y = lower)) +
  # 绘制条形,底部从下限开始,高度为上下限差值
  geom_col(aes(height = height), fill = "#87CEEB", width = 0.7) +
  # 添加上下限范围的误差线
  geom_errorbar(aes(ymin = lower, ymax = upper), 
                width = 0.2, lwd = 1.2) +
  # 标记上下限的点
  geom_point(aes(y = lower), color = "red", size = 3) +
  geom_point(aes(y = upper), color = "blue", size = 3) +
  # 设置坐标轴标签
  labs(x = "X axis", y = "Y Value") +
  # 使用简洁的主题
  theme_minimal() +
  # 调整X轴文字大小
  theme(axis.text.x = element_text(size = 10))

针对100个数据点的小提示

如果你的实际数据有100个点,记得调整条形宽度避免重叠:

  • Base R中可以在barplot()里设置width参数(比如width = 0.5)
  • ggplot2中调整geom_col()的width参数(比如width = 0.4)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:50:06