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

如何使用Pandas结合matplotlib.pyplot按指定列绘制符合要求的图表

基于Pandas+Matplotlib实现分组NPS图表方案

以下为可直接运行的完整实现代码,适配你提供的数据结构和常规商务分组图表样式:

import pandas as pd
import matplotlib.pyplot as plt

# 1. 构造DataFrame(如果你已有对应df可直接跳过该步骤)
data = [
    ["Transportation", 50.84, 2020],
    ["Professional Services", 52.59, 2020],
    ["Life Sciences", 43.15, 2020],
    ["Transportation", 39.28, 2019],
    ["Professional Services", 43.52, 2019],
    ["Life Sciences", 40.19, 2019],
    ["Transportation", 37.66, 2018],
    ["Professional Services", 27.61, 2018],
    ["Life Sciences", 34.11, 2018],
    ["Transportation", 17.60, 2017],
    ["Professional Services", 17.33, 2017],
    ["Life Sciences", -3.33, 2017]
]
df = pd.DataFrame(data, columns=["industry", "nps", "year"])

# 2. 数据转宽格式适配分组绘图
df_pivot = df.pivot(index='year', columns='industry', values='nps').reset_index()
industries = df['industry'].unique()
year_count = len(df_pivot['year'])
bar_width = 0.25 # 单根柱子宽度,可按需调整
x = range(year_count) # x轴基础位置

# 3. 全局样式配置
plt.rcParams['font.sans-serif'] = ['Arial']
plt.rcParams['axes.unicode_minus'] = False # 解决负NPS的负号显示异常问题
fig, ax = plt.subplots(figsize=(10, 6), dpi=100)

# 4. 绘制分组柱状图+数据标签
colors = ['#1f77b4', '#ff7f0e', '#2ca02c'] # 三个行业对应配色,可按需替换
for idx, industry in enumerate(industries):
    bar_pos = [i + idx*bar_width for i in x]
    bars = ax.bar(bar_pos, df_pivot[industry], width=bar_width, label=industry, color=colors[idx])
    # 给每个柱子添加顶部数值标签
    for bar in bars:
        height = bar.get_height()
        ax.text(bar.get_x() + bar.get_width()/2., height,
                f'{height:.1f}',
                ha='center', va='bottom', fontsize=9)

# 5. 坐标轴、图例配置
ax.set_xlabel('Year', fontsize=12)
ax.set_ylabel('NPS Score', fontsize=12)
ax.set_title('NPS by Industry Over Years', fontsize=14, pad=20)
ax.set_xticks([i + bar_width for i in x])
ax.set_xticklabels(df_pivot['year'])
ax.legend(title='Industry', bbox_to_anchor=(1.01, 1), loc='upper left')
# 可选样式优化:隐藏多余边框、添加y轴网格
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.grid(axis='y', linestyle='--', alpha=0.7)

plt.tight_layout()
plt.show()

核心可调整配置说明

  • 调整bar_width参数可以修改柱子粗细和同组柱子的间隙大小
  • 替换colors数组可以自定义不同行业的对应配色
  • 修改figsize参数可以调整整体画布尺寸,修改各类fontsize参数可以适配不同场景的字体大小需求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 17:24:02