github star gitee star atomgit star PyPI Downloads AI 编程 AI 交流群

大家好,我是正在实战各种AI项目的程序员晚枫。

今天介绍Pandas内置的plot方法,这是最快的数据可视化方式。

不需要导入Matplotlib或Seaborn,直接对DataFrame调用.plot(),一秒出图!


为什么用Pandas内置绘图?

优势

极简:一行代码出图
集成:和数据分析流程无缝衔接
快速:探索性分析首选
灵活:底层仍是Matplotlib,可深度定制

适用场景

  • 快速查看数据趋势
  • 探索性数据分析(EDA)
  • 临时图表需求

基础用法

1
2
3
4
5
6
7
8
9
10
11
12
import pandas as pd
import numpy as np

# 创建时间序列数据
dates = pd.date_range('2024-01-01', periods=30)
df = pd.DataFrame({
'销售额': np.random.randint(100, 200, 30).cumsum(),
'利润': np.random.randint(20, 50, 30).cumsum()
}, index=dates)

# 最简单的折线图
df.plot()

常用图表类型

折线图(Line)

1
2
3
4
5
6
7
8
# 默认就是折线图
df['销售额'].plot()

# 多列同时绘制
df.plot(figsize=(12, 6), title='月度业绩趋势')

# 子图形式
df.plot(subplots=True, figsize=(10, 8))

柱状图(Bar)

1
2
3
4
5
6
7
8
9
10
11
# 准备分类数据
monthly = df.resample('M').last()

# 垂直柱状图
monthly.plot(kind='bar')

# 水平柱状图
monthly.plot(kind='barh')

# 堆叠柱状图
monthly.plot(kind='bar', stacked=True)

面积图(Area)

1
2
3
4
5
# 填充面积的折线
df.plot(kind='area', alpha=0.5)

# 堆叠面积图
df.plot(kind='area', stacked=True)

直方图(Hist)

1
2
3
4
5
# 单列直方图
df['销售额'].plot(kind='hist', bins=20)

# 多列直方图
df.plot(kind='hist', alpha=0.5, bins=20)

箱线图(Box)

1
df.plot(kind='box')

散点图(Scatter)

1
df.plot(kind='scatter', x='销售额', y='利润')

饼图(Pie)

1
2
# 饼图需要指定一列
monthly['销售额'].plot(kind='pie', autopct='%1.1f%%')

样式参数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
df.plot(
kind='line', # 图表类型
figsize=(12, 6), # 图形大小
title='销售趋势', # 标题
xlabel='日期', # X轴标签
ylabel='金额(万元)', # Y轴标签
grid=True, # 显示网格
legend=True, # 显示图例
style=['-', '--'], # 线型
color=['red', 'blue'], # 颜色
linewidth=2, # 线宽
marker='o', # 标记
markersize=6 # 标记大小
)

Series专用绘图

1
2
3
4
5
6
7
s = pd.Series(np.random.randn(100).cumsum())

# 密度图
s.plot(kind='kde')

# 累积分布
s.plot(kind='hist', cumulative=True, density=True)

高级技巧

双Y轴

1
2
ax = df['销售额'].plot(legend=True)
df['利润率'].plot(secondary_y=True, ax=ax, color='red', legend=True)

自定义颜色映射

1
df.plot(colormap='viridis')

按条件着色

1
2
3
4
# 正负值不同颜色
returns = df['销售额'].pct_change()
colors = ['green' if x > 0 else 'red' for x in returns]
returns.plot(kind='bar', color=colors)

与Matplotlib结合

1
2
3
4
5
6
7
8
9
10
11
12
13
import matplotlib.pyplot as plt

# Pandas绘图返回Axes对象
ax = df.plot(figsize=(12, 6))

# 用Matplotlib进一步美化
ax.set_title('销售分析', fontsize=16, fontweight='bold')
ax.grid(True, alpha=0.3)
ax.axhline(y=df['销售额'].mean(), color='r', linestyle='--', label='平均值')
ax.legend()

plt.tight_layout()
plt.show()

实战:完整的数据探索

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import pandas as pd
import numpy as np

# 生成模拟数据
np.random.seed(42)
df = pd.DataFrame({
'产品A': np.random.randint(100, 200, 12),
'产品B': np.random.randint(80, 150, 12),
'产品C': np.random.randint(60, 120, 12)
}, index=pd.date_range('2024-01', periods=12, freq='M'))

print("=== 快速可视化探索 ===\n")

# 1. 整体趋势
print("1. 产品销售趋势")
df.plot(figsize=(12, 6), title='月度产品销售对比', marker='o')
plt.ylabel('销量')
plt.show()

# 2. 占比分析
print("\n2. 产品占比(年末)")
df.iloc[-1].plot(kind='pie', autopct='%1.1f%%', title='12月产品销售占比')
plt.ylabel('')
plt.show()

# 3. 分布情况
print("\n3. 销量分布")
df.plot(kind='box', title='各产品销量分布')
plt.ylabel('销量')
plt.show()

# 4. 累计趋势
print("\n4. 累计销量")
df.cumsum().plot(kind='area', alpha=0.5, title='累计销量趋势')
plt.ylabel('累计销量')
plt.show()

# 5. 增长率
print("\n5. 环比增长率")
growth = df.pct_change() * 100
growth.plot(kind='bar', title='月度环比增长率(%)')
plt.axhline(y=0, color='black', linestyle='-', linewidth=0.5)
plt.ylabel('增长率(%)')
plt.show()

性能对比:Pandas内置绘图 vs 其他方式

1
2
3
4
5
6
7
8
9
10
import pandas as pd
import numpy as np

df = pd.DataFrame(np.random.randn(100, 4), columns=['A', 'B', 'C', 'D'])

# Pandas内置:1行代码
%timeit df.plot()

# Matplotlib:需要5-10行代码
# Seaborn:需要3-5行代码
方式代码量美观度灵活性
Pandas内置1行
Matplotlib5-10行低(需美化)
Seaborn2-3行

进阶用法

快速探索性分析

1
2
3
4
5
6
7
8
9
10
11
# 一行代码看所有数值列的分布
df.hist(figsize=(12, 8), bins=30)

# 一行代码看所有列的相关性
pd.plotting.scatter_matrix(df, figsize=(12, 12), alpha=0.5)

# 一行代码看自相关
pd.plotting.autocorrelation_plot(df['sales'])

# 一行代码看安德鲁斯曲线(分类可视化)
pd.plotting.andrews_curves(df, 'category')

subplots参数

1
2
3
4
5
# 每列一个子图
df.plot(subplots=True, figsize=(12, 8), layout=(2, 2))

# 共享X轴
df.plot(subplots=True, sharex=True)

避坑指南

❌ 坑1:plot不显示

1
2
3
4
5
6
7
8
# 需要导入matplotlib并调用show
import matplotlib.pyplot as plt
df.plot()
plt.show() # 在脚本中必须调用

# 在Jupyter中
%matplotlib inline
df.plot() # 自动显示

实战案例:快速分析销售数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

plt.rcParams['font.sans-serif'] = ['Arial Unicode MS']
plt.rcParams['axes.unicode_minus'] = False

np.random.seed(42)
dates = pd.date_range('2025-01-01', periods=365)
df = pd.DataFrame({
'线上': np.cumsum(np.random.randn(365)) + 100,
'线下': np.cumsum(np.random.randn(365) * 0.5) + 80,
}, index=dates)

# 1行代码画趋势图
df.plot(figsize=(14, 6), title='2025年销售趋势')
plt.savefig('trend.png', dpi=150)

# 1行代码画面积图
df.plot.area(figsize=(14, 6), alpha=0.5, title='销售面积图')

# 月度汇总1行代码
df.resample('M').mean().plot.bar(figsize=(14, 6), title='月度平均销售')

Pandas绘图参数详解

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# 通用参数
df.plot(
kind='line', # 图表类型
x='date', # X轴列
y='value', # Y轴列
figsize=(12, 6), # 图片大小
title='标题', # 标题
xlabel='X轴', # X轴标签
ylabel='Y轴', # Y轴标签
color='blue', # 颜色
alpha=0.7, # 透明度
grid=True, # 显示网格
legend=True, # 显示图例
subplots=False, # 分列显示
sharex=True, # 共享X轴
rot=45, # X轴标签旋转角度
fontsize=12, # 字体大小
style='o-', # 线型和标记
)

# kind参数可选值:
# 'line' 折线图
# 'bar' 柱状图
# 'barh' 横向柱状图
# 'hist' 直方图
# 'box' 箱线图
# 'kde' 核密度图
# 'area' 面积图
# 'pie' 饼图
# 'scatter' 散点图
# 'hexbin' 六边形图

Pandas绘图常用模板

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import matplotlib.pyplot as plt

plt.rcParams['font.sans-serif'] = ['Arial Unicode MS']
plt.rcParams['axes.unicode_minus'] = False

# 模板1:销售趋势
df.set_index('date')['sales'].plot(figsize=(12, 5), title='销售趋势', grid=True)

# 模板2:品类对比
df.groupby('category')['sales'].sum().plot.bar(figsize=(10, 5), rot=0, title='品类销售对比')

# 模板3:占比分析
df['category'].value_counts().plot.pie(figsize=(8, 8), autopct='%1.1f%%', title='品类占比')

# 模板4:分布分析
df['price'].plot.hist(bins=30, figsize=(10, 5), title='价格分布')

# 模板5:多列趋势对比
df[['online', 'offline']].plot(figsize=(12, 5), subplots=True, sharex=True)

# 模板6:箱线图
df.boxplot(column='salary', by='city', figsize=(12, 6))

快速出图工作流

1
2
3
4
5
6
7
8
9
10
11
12
13
# 实际工作中的快速出图流程
def quick_plot(df, x, y=None, kind='bar', title=''):
'''一键出图,适合快速探索'''
if y:
ax = df.plot(x=x, y=y, kind=kind, figsize=(12, 5), title=title, grid=True)
else:
ax = df[x].plot(kind=kind, figsize=(12, 5), title=title, grid=True)
plt.tight_layout()
return ax

# 使用
quick_plot(df, 'category', 'sales', 'bar', '品类销售对比')
quick_plot(df, 'price', kind='hist', title='价格分布')

下节预告

下一课我们将学习交互式可视化-pyecharts,制作动态图表。

👉 继续阅读:交互式可视化-pyecharts制作动态图表


💬 加入学习交流群

扫码加入Python学习交流群,和数千名同学一起进步:

👉 点击加入交流群

群里不定期分享:

  • 数据分析实战案例
  • Python学习资料
  • 求职面试经验
  • 行业最新动态

推荐:AI Python数据分析实战营

🎁 限时福利:送《利用Python进行数据分析》实体书

👉 点击了解详情


课程导航

上一篇: Seaborn统计可视化-让图表更优雅

下一篇: 交互式可视化-pyecharts制作动态图表


PS:Pandas内置绘图是效率神器。日常分析先用它快速出图,需要精细调整时再换Matplotlib。



📚 推荐教材

主教材《Excel+Python 飞速搞定数据分析与处理(图灵出品)》

💬 联系我

平台账号/链接
微信扫码加好友
微博@程序员晚枫
知乎@程序员晚枫
抖音@程序员晚枫
小红书@程序员晚枫
B 站Python 自动化办公社区

主营业务:AI 编程培训、企业内训、技术咨询

🎓 AI 编程实战课程

想系统学习 AI 编程?程序员晚枫的 AI 编程实战课 帮你从零上手!