Pandas 数据可视化基础绘图教程
Pandas 提供了便捷的内置绘图功能,底层基于 Matplotlib,使得数据探索变得简单高效。 Pandas 数据可视化的基础操作,包括环境配置、Series 与 DataFrame 的绘制、常用图表类型(折线、柱状、直方、散点、饼图)的选择以及自定义样式和保存图片的方法。内容涵盖从基础代码示例到进阶的子图布局与性能优化建议,帮助读者快速上手数据可视化流程。

Pandas 提供了便捷的内置绘图功能,底层基于 Matplotlib,使得数据探索变得简单高效。 Pandas 数据可视化的基础操作,包括环境配置、Series 与 DataFrame 的绘制、常用图表类型(折线、柱状、直方、散点、饼图)的选择以及自定义样式和保存图片的方法。内容涵盖从基础代码示例到进阶的子图布局与性能优化建议,帮助读者快速上手数据可视化流程。

众所周知,Pandas 是基于 Python 平台的大数据分析与处理的利器。在数据为王的时代,想要掌握数据分析能力,学会 Pandas 数据可视化工具是十分重要的。Pandas 内置了强大的绘图功能,底层基于 Matplotlib,使得数据探索变得简单高效。
本文将带领大家学习 Pandas 数据可视化的基础绘图,涵盖环境配置、Series 与 DataFrame 的绘制、图表类型选择以及自定义样式等内容。
IDE : Jupyter Notebook
Anaconda 3.X
首先确保已安装必要的库:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
注:导入 matplotlib.pyplot 作为绘图接口。
设置绘图样式并启用内联显示:
import matplotlib
matplotlib.style.use('ggplot')
%matplotlib inline
注:使用 ggplot 样式美化图表,并将图画在 Jupyter Notebook 中直接显示。
使用 Pandas 创建一个 Series(序列),序列值是随机生成的 1000 个标准正态分布值,索引是从 2000-1-1 开始的 1000 个时间序列值。
ts = pd.Series(np.random.randn(1000), index=pd.date_range('1/1/2000', periods=1000))
ts.plot()
plt.show()
注:使用 plot 默认画图。可以看出,下图非常不规则,因为相邻的两个值也是随机大小。
在时间序列分析中,经常观察累积值曲线来观察走势。
ts = pd.Series(np.random.randn(1000), index=pd.date_range('1/1/2000', periods=1000))
ts = ts.cumsum()
ts.plot()
plt.show()
注:这里加上了 ts = ts.cumsum(),意思是返回累积值。这个累积值看起来规则多了,适合分析趋势。
DataFrame 可以创建多组数据,类似于 Excel 表格。
df = pd.DataFrame(np.random.randn(1000, 4), index=ts.index, columns=list('ABCD'))
df = df.cumsum()
plt.figure(figsize=(10, 6))
df.plot()
plt.title('DataFrame Cumulative Plot')
plt.legend(loc='best')
plt.show()
注:这里使用 Pandas 创建了一个 DataFrame,包含 4 组数据(A、B、C、D 列)。每列都是随机生成的 1000 个标准正态分布值,索引是时间序列,并且求各自的累积值后画图。
可以使用 x 和 y 参数指定绘图的数据列。
df3 = pd.DataFrame(np.random.randn(1000, 2), columns=['B', 'C']).cumsum()
df3['A'] = pd.Series(list(range(len(df3))))
df3.plot(x='A', y='B')
plt.title('Plot with Custom X and Y')
plt.show()
注:使用 DataFrame 创建了 2 组数据 B、C,并加上了一列名为 A,A 的值是 0-999。X 轴是 A 列数据,Y 轴是 B 列数据(累积值)。
Pandas 支持多种图表类型,通过 kind 参数切换。
data = pd.Series(np.random.randn(10), index=list('ABCDEFGHIJ'))
data.plot(kind='bar')
plt.title('Bar Chart')
plt.show()
用于展示数据的分布情况。
data = pd.Series(np.random.randn(1000) * 10 + 50)
data.plot(kind='hist', bins=30, density=True, alpha=0.6)
plt.title('Histogram Distribution')
plt.show()
data = pd.DataFrame({'x': np.random.randn(100), 'y': np.random.randn(100)})
data.plot(kind='scatter', x='x', y='y')
plt.title('Scatter Plot')
plt.show()
data = pd.Series([10, 20, 30, 40], index=['A', 'B', 'C', 'D'])
data.plot(kind='pie', autopct='%1.1f%%')
plt.title('Pie Chart')
plt.axis('equal')
plt.show()
可以修改颜色、线型、标记等属性。
ts.plot(color='red', linestyle='--', marker='o', label='Random Walk')
plt.xlabel('Date')
plt.ylabel('Value')
plt.legend()
plt.grid(True)
plt.show()
在同一画布上绘制多个图表。
df = pd.DataFrame(np.random.randn(1000, 4), columns=list('ABCD')).cumsum()
df.plot(subplots=True, layout=(2, 2), figsize=(10, 8))
plt.tight_layout()
plt.show()
将绘制的图表保存到本地文件。
fig = plt.figure()
df.plot()
plt.savefig('pandas_plot.png', dpi=300, bbox_inches='tight')
print('Figure saved successfully.')
本文介绍了 Pandas 库在数据可视化方面的基础应用。通过内置的 plot 方法,可以快速生成折线图、柱状图、散点图等多种图表。结合 Matplotlib 的定制能力,可以满足大多数数据分析场景下的可视化需求。掌握这些基础技能,将大大提升数据分析的效率和质量。

微信公众号「极客日志」,在微信中扫描左侧二维码关注。展示文案:极客日志 zeeklog
使用加密算法(如AES、TripleDES、Rabbit或RC4)加密和解密文本明文。 在线工具,加密/解密文本在线工具,online
生成新的随机RSA私钥和公钥pem证书。 在线工具,RSA密钥对生成器在线工具,online
基于 Mermaid.js 实时预览流程图、时序图等图表,支持源码编辑与即时渲染。 在线工具,Mermaid 预览与可视化编辑在线工具,online
解析常见 curl 参数并生成 fetch、axios、PHP curl 或 Python requests 示例代码。 在线工具,curl 转代码在线工具,online
将字符串编码和解码为其 Base64 格式表示形式即可。 在线工具,Base64 字符串编码/解码在线工具,online
将字符串、文件或图像转换为其 Base64 表示形式。 在线工具,Base64 文件转换器在线工具,online