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

在Pandas DataFrame内绘制销售数据水平条形图的实现方法

实现类似彭博终端Range列的水平条形图方案(基于Pandas + Matplotlib)

我刚好做过类似的需求,彭博的Range条确实很直观,结合Pandas和Matplotlib完全可以实现,下面是具体的步骤和代码:

1. 示例数据准备

先构造一个模拟的销售DataFrame,方便你快速测试效果:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

# 构造示例销售数据
data = {
    'Company': ['TechCorp', 'RetailInc', 'ManufactureCo', 'ServiceLtd'],
    'Current_Sales': [450, 320, 580, 290],
    'Min_Sales': [300, 200, 400, 180],
    'Max_Sales': [600, 450, 750, 380],
    'Avg_Sales': [420, 280, 550, 250]
}
df = pd.DataFrame(data)

2. 核心绘图实现

核心思路是先绘制最低-最高销售额的区间背景条,再用标记点/短条形突出当前值和平均值,完美匹配彭博Range列的视觉逻辑:

# 设置接近彭博的简洁专业风格
plt.style.use('seaborn-v0_8-whitegrid')
fig, ax = plt.subplots(figsize=(10, len(df)*0.6))  # 根据公司数量动态调整图高

# 为每家公司分配y轴位置,确保条形与标签对齐
y_pos = np.arange(len(df))
bar_height = 0.4  # 区间条的高度

# 1. 绘制最低到最高的灰色区间条形(彭博Range的基础背景)
ax.barh(y_pos, df['Max_Sales'] - df['Min_Sales'], left=df['Min_Sales'], 
        height=bar_height, color='#e0e0e0', label='Sales Range (Min-Max)')

# 2. 用圆点标记当前销售额(蓝色,突出显示)
ax.scatter(df['Current_Sales'], y_pos, color='#1f77b4', s=120, zorder=5, label='Current Sales')

# 3. 用圆点标记平均销售额(橙色,区分当前值)
ax.scatter(df['Avg_Sales'], y_pos, color='#ff7f0e', s=120, zorder=5, label='Average Sales')

# 配置坐标轴与标签
ax.set_yticks(y_pos)
ax.set_yticklabels(df['Company'])
ax.set_xlabel('Sales Amount')
ax.set_title('Sales Metrics by Company (Bloomberg Range Style)')
ax.legend()

# 自动调整布局,避免标签被截断
plt.tight_layout()
plt.show()

3. 细节优化建议

  • 若要更贴近彭博的极简风格,可去掉网格线:ax.grid(False)
  • 给标记点添加数值标签,增强可读性:
    # 给当前销售额加标签
    for x, y in zip(df['Current_Sales'], y_pos):
        ax.text(x + 15, y, f'${x}', va='center', fontweight='bold')
    # 给平均销售额加标签
    for x, y in zip(df['Avg_Sales'], y_pos):
        ax.text(x + 15, y, f'${x}', va='center', color='#ff7f0e')
    
  • 如果公司数量较多,可增大figsize的高度参数,或者将标记点换成更紧凑的短条形(把scatter换成barh即可)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:18:24