如何用Pandas和Matplotlib复刻HdrHistogram的HistogramPlotter输出
解决HdrHistogram复刻图表尾部压缩问题的调整方案
核心问题根源
HdrHistogram的HistogramPlotter默认用对数坐标轴展示尾部数据,你的脚本大概率用了线性坐标轴,导致大数值的尾部直接被压缩到图表边缘,完全看不到细节。
具体调整步骤
1. 切换为对数坐标轴
直接给Matplotlib的X轴设置对数刻度,这是解决尾部压缩的关键:
plt.xscale('log')
还可以优化刻度显示,避免科学计数法,让关键数值更清晰:
from matplotlib.ticker import LogLocator, FormatStrFormatter # 控制对数刻度的显示密度 ax.xaxis.set_major_locator(LogLocator(base=10, numticks=10)) ax.xaxis.set_minor_locator(LogLocator(base=10, subs='auto')) # 把刻度标签格式化成普通数字 ax.xaxis.set_major_formatter(FormatStrFormatter('%.0f'))
2. 匹配HdrHistogram的分位数聚焦逻辑
HdrHistogram的图表会重点展示99%、99.9%这类高百分位区间,你可以针对性放大这些区域:
# 假设你的数据框df包含percentile和value列 # 筛选99%到100%的分位数,单独放大展示 tail_data = df[df['percentile'] >= 99] plt.xlim(tail_data['value'].min() * 0.9, tail_data['value'].max() * 1.1)
3. 调整图表布局给尾部留空间
- 加宽图表宽度,避免尾部挤在一起:
plt.figure(figsize=(12, 6))
- 开启网格线,对齐对数刻度,提升可读性:
plt.grid(True, which='both', axis='x', linestyle='--', alpha=0.7)
4. 正确解析.hgrm数据格式
确保你读对了consumer.hgrm的结构,HdrHistogram的hgrm文件前两行是注释,后面是分位数、数值、累计计数,示例解析代码:
import pandas as pd # 跳过前两行注释,按空格分割列 df = pd.read_csv('consumer.hgrm', skiprows=2, sep='\s+', names=['percentile', 'value', 'cumulative_count']) # 把百分数字符串转成数值(去掉%符号) df['percentile'] = df['percentile'].str.rstrip('%').astype(float)
完整可运行示例代码
import pandas as pd import matplotlib.pyplot as plt from matplotlib.ticker import LogLocator, FormatStrFormatter # 读取hgrm测试数据 df = pd.read_csv('consumer.hgrm', skiprows=2, sep='\s+', names=['percentile', 'value', 'cumulative_count']) df['percentile'] = df['percentile'].str.rstrip('%').astype(float) # 创建图表并设置尺寸 plt.figure(figsize=(12, 6)) ax = plt.gca() # 绘制分位数-数值折线图 plt.plot(df['value'], df['percentile'], marker='.', linestyle='-', alpha=0.8) # 配置对数X轴 plt.xscale('log') ax.xaxis.set_major_locator(LogLocator(base=10, numticks=10)) ax.xaxis.set_minor_locator(LogLocator(base=10, subs='auto')) ax.xaxis.set_major_formatter(FormatStrFormatter('%.0f')) # 设置标签和标题 plt.xlabel('Latency') plt.ylabel('Percentile') plt.title('HdrHistogram Style Latency Distribution') # 添加网格线 plt.grid(True, which='both', axis='x', linestyle='--', alpha=0.7) # 自动调整布局 plt.tight_layout() plt.show()
内容的提问来源于stack exchange,提问作者Hofbr
相关产品推荐
相关产品推荐

