如何用Python模块或Bash+Gnuplot绘制体积-概率密度图?
绘制体积vs概率图的实现方案
问题描述
我有如下格式的数据文件:
1 volume 318.31 2 volume 317.59 3 volume 316.71 4 volume 315.78 5 volume 315.07 6 volume 314.55 7 volume 314.38 8 volume 314.40 9 volume 314.86 10 volume 315.74 11 volume 316.83 12 volume 318.08 13 volume 319.44 14 volume 320.70 15 volume 322.04 16 volume 323.17 17 volume 323.77 18 volume 324.16 19 volume 324.02 20 volume 323.59 ... 10000 volume 322.72 10001 volume 321.69 10002 volume 320.34 10003 volume 318.87
希望绘制体积vs概率图,以下是两种可行的实现方案:
一、Python方案(使用NumPy + Matplotlib)
适合需要灵活数据处理或自定义绘图样式的场景,代码可复用性强。
步骤与代码示例
- 读取数据文件,提取体积列;
- 对体积数据排序,计算每个值对应的累积概率;
- 绘制体积-概率曲线。
import numpy as np import matplotlib.pyplot as plt # 读取数据:提取第三列的体积值 volumes = np.loadtxt('data.txt', usecols=2) # 排序体积数据 sorted_volumes = np.sort(volumes) # 计算累积概率:每个数据点对应的概率为 (索引+1)/总样本数 n = len(sorted_volumes) probabilities = (np.arange(n) + 1) / n # 绘制体积vs累积概率图 plt.figure(figsize=(8, 6)) plt.plot(sorted_volumes, probabilities, linewidth=1.5, label='累积概率') plt.xlabel('体积') plt.ylabel('概率') plt.title('体积vs概率分布图') plt.grid(alpha=0.3) plt.legend() plt.show() # 若需绘制概率密度分布(PDF),可使用直方图+核密度估计 plt.figure(figsize=(8, 6)) counts, bins, _ = plt.hist(volumes, bins=30, density=True, alpha=0.5, label='直方图') # 核密度估计 from scipy.stats import gaussian_kde kde = gaussian_kde(volumes) xvals = np.linspace(min(volumes), max(volumes), 1000) plt.plot(xvals, kde(xvals), linewidth=1.5, label='核密度估计') plt.xlabel('体积') plt.ylabel('概率密度') plt.title('体积概率密度分布图') plt.grid(alpha=0.3) plt.legend() plt.show()
二、Bash Shell + Gnuplot方案
适合纯命令行环境下快速生成图表,无需编写Python代码。
步骤与命令示例
- 用
awk提取体积数据,排序后计算对应概率; - 用Gnuplot绘制图表。
1. 预处理数据(生成体积-概率临时文件)
# 统计总样本数 total=$(wc -l < data.txt) # 提取体积列、排序、计算概率,保存到temp_data.txt awk '{print $3}' data.txt | sort -n | awk -v total="$total" '{print $1, (NR)/total}' > temp_data.txt
2. 绘制累积概率图
创建Gnuplot脚本plot_cdf.gp:
set terminal pngcairo enhanced font 'Arial,10' size 800,600 set output 'volume_vs_prob.png' set title '体积vs概率分布图' set xlabel '体积' set ylabel '概率' set grid plot 'temp_data.txt' using 1:2 with lines lw 1.5 title '累积概率'
执行脚本:
gnuplot plot_cdf.gp
3. 绘制概率密度图
创建Gnuplot脚本plot_pdf.gp:
set terminal pngcairo enhanced font 'Arial,10' size 800,600 set output 'volume_pdf.png' set title '体积概率密度分布图' set xlabel '体积' set ylabel '概率密度' set grid binwidth=0.5 set boxwidth binwidth plot 'data.txt' using 3:(1.0/(total*binwidth)) smooth freq with boxes lw 1.5 title '概率密度'
执行脚本(传递总样本数参数):
total=$(wc -l < data.txt) gnuplot -e "total=$total" plot_pdf.gp
内容的提问来源于stack exchange,提问作者Binh Thien
相关产品推荐
相关产品推荐

