

大家好,我是正在实战各种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)
散点图(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='日期', ylabel='金额(万元)', 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
ax = df.plot(figsize=(12, 6))
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")
print("1. 产品销售趋势") df.plot(figsize=(12, 6), title='月度产品销售对比', marker='o') plt.ylabel('销量') plt.show()
print("\n2. 产品占比(年末)") df.iloc[-1].plot(kind='pie', autopct='%1.1f%%', title='12月产品销售占比') plt.ylabel('') plt.show()
print("\n3. 销量分布") df.plot(kind='box', title='各产品销量分布') plt.ylabel('销量') plt.show()
print("\n4. 累计销量") df.cumsum().plot(kind='area', alpha=0.5, title='累计销量趋势') plt.ylabel('累计销量') plt.show()
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'])
%timeit df.plot()
|
| 方式 | 代码量 | 美观度 | 灵活性 |
|---|
| Pandas内置 | 1行 | 中 | 低 |
| Matplotlib | 5-10行 | 低(需美化) | 高 |
| Seaborn | 2-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))
df.plot(subplots=True, sharex=True)
|
避坑指南
❌ 坑1:plot不显示
1 2 3 4 5 6 7 8
| import matplotlib.pyplot as plt df.plot() plt.show()
%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)
df.plot(figsize=(14, 6), title='2025年销售趋势') plt.savefig('trend.png', dpi=150)
df.plot.area(figsize=(14, 6), alpha=0.5, title='销售面积图')
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', y='value', figsize=(12, 6), title='标题', xlabel='X轴', ylabel='Y轴', color='blue', alpha=0.7, grid=True, legend=True, subplots=False, sharex=True, rot=45, fontsize=12, style='o-', )
|
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
df.set_index('date')['sales'].plot(figsize=(12, 5), title='销售趋势', grid=True)
df.groupby('category')['sales'].sum().plot.bar(figsize=(10, 5), rot=0, title='品类销售对比')
df['category'].value_counts().plot.pie(figsize=(8, 8), autopct='%1.1f%%', title='品类占比')
df['price'].plot.hist(bins=30, figsize=(10, 5), title='价格分布')
df[['online', 'offline']].plot(figsize=(12, 5), subplots=True, sharex=True)
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 飞速搞定数据分析与处理(图灵出品)》
💬 联系我
主营业务:AI 编程培训、企业内训、技术咨询
🎓 AI 编程实战课程
想系统学习 AI 编程?程序员晚枫的 AI 编程实战课 帮你从零上手!