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

如何绘制已预先计算完成的分布数据?支持R、Python、gnuplot实现

R 实现方案

你手里已经预计算好分箱区间和对应取值的话,用ggplot2处理反而比原始数据更简单,直接通过geom_rect指定每个分箱的左右边界和y轴高度即可,不需要做额外的分箱统计:

library(ggplot2)
# 构造分箱数据
df <- data.frame(
  left = c(0, 4, 6),
  right = c(4, 6, 10),
  value = c(1, 2, 1)
)

ggplot(df) +
  geom_rect(
    aes(xmin = left, xmax = right, ymin = 0, ymax = value),
    fill = "steelblue",
    color = "white"
  ) +
  labs(x = "x", y = "y")

如果不需要复杂的可视化效果,用base R的rect函数也可以快速绘制,代码更轻量。

Python 实现方案

用matplotlib的bar函数即可实现,只需要手动指定每个柱子的左边界和宽度(即区间长度):

import matplotlib.pyplot as plt

left = [0, 4, 6]
right = [4, 6, 10]
value = [1, 2, 1]
width = [r - l for l, r in zip(left, right)]

plt.bar(
    x=left,
    height=value,
    width=width,
    align="edge",
    color="steelblue",
    edgecolor="white"
)
plt.xlim(0, 10)
plt.xlabel("x")
plt.ylabel("y")
plt.show()

gnuplot 实现方案

gnuplot非常适合处理这类预计算的区间数据,同时可以直接输出纯文本格式的分布图。
首先把你的原始数据保存为data.txt:

0   1
4   2
6   1
10  0

普通图像输出脚本

set xrange [0:10]
set yrange [0:2.5]
set xlabel "x"
set ylabel "y"
plot 'data.txt' using 1:2 with steps fill solid 0.5 title ''

纯文本格式输出脚本

只需要将终端设置为dumb即可输出文本格式的图表:

# 设置终端为文本模式,指定宽高
set terminal dumb size 80, 20
set output 'histogram.txt'
set xrange [0:10]
set yrange [0:2.5]
set xlabel "x"
set ylabel "y"
plot 'data.txt' using 1:2 with steps fill solid title ''
set output

运行后生成的histogram.txt就是纯文本的分布图,可以直接在终端或文本编辑器中查看。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.12 05:06:04