📚 目录

  1. 数据可视化概述
  2. 使用 Matplotlib 进行基础可视化
  3. 使用 Seaborn 进行高级可视化
  4. Pandas 内建的绘图功能
  5. 绘制常见图表
  6. 时间序列数据可视化
  7. 参考资料
  8. 出站链接

1. 数据可视化概述

数据可视化是数据分析的重要步骤,它通过图形展示数据的模式和趋势,帮助分析人员更直观地理解数据。在 Pandas 中,我们可以结合 Matplotlib 和 Seaborn 等库进行丰富的数据可视化。


2. 使用 Matplotlib 进行基础可视化

Matplotlib 是 Python 最常用的绘图库之一,Pandas 数据框架与 Matplotlib 有很好的兼容性。

✅ 创建简单的线图:

1
2
3
4
5
6
7
import matplotlib.pyplot as plt
 
df['Age'].plot(kind='line')
plt.title("Age Over Time")
plt.xlabel("Index")
plt.ylabel("Age")
plt.show()

✅ 创建简单的柱状图:

1
2
3
4
5
df['City'].value_counts().plot(kind='bar')
plt.title("City Frequency")
plt.xlabel("City")
plt.ylabel("Frequency")
plt.show()

3. 使用 Seaborn 进行高级可视化

Seaborn 是一个基于 Matplotlib 的统计数据可视化库,提供了更加美观和丰富的图表类型。

✅ 创建箱线图(Box Plot):

1
2
3
4
5
import seaborn as sns
 
sns.boxplot(x='City', y='Age', data=df)
plt.title("Age Distribution by City")
plt.show()

✅ 创建热力图(Heatmap):

1
2
3
sns.heatmap(df.corr(), annot=True, cmap='coolwarm')
plt.title("Correlation Heatmap")
plt.show()

4. Pandas 内建的绘图功能

Pandas DataFrame 和 Series 提供了内建的 .plot() 方法,支持多种常见的图表类型。

✅ 使用 plot() 绘制线图、柱状图等:

1
2
df['Age'].plot(kind='line', title="Age Over Time")  # 绘制线图
df['City'].value_counts().plot(kind='bar', title="City Frequency")  # 绘制柱状图

✅ 绘制直方图:

1
2
3
4
df['Age'].plot(kind='hist', bins=10, alpha=0.7)
plt.title("Age Distribution")
plt.xlabel("Age")
plt.show()

5. 绘制常见图表

✅ 直方图(Histogram)

1
2
3
4
df['Age'].plot(kind='hist', bins=20, alpha=0.7)
plt.title("Age Distribution")
plt.xlabel("Age")
plt.show()

✅ 散点图(Scatter Plot)

1
2
df.plot(kind='scatter', x='Age', y='Income', title="Age vs Income")
plt.show()

✅ 饼图(Pie Chart)

1
2
3
df['City'].value_counts().plot(kind='pie', autopct='%1.1f%%')
plt.title("City Distribution")
plt.show()

6. 时间序列数据可视化

Pandas 在处理时间序列数据时非常方便,可以轻松地绘制日期与数值的关系图。

✅ 绘制时间序列数据:

1
2
3
4
df['Date'] = pd.to_datetime(df['Date'])
df.set_index('Date', inplace=True)
df['Age'].plot(title="Age Over Time")
plt.show()

📖 参考资料

  • 《Python Data Science Handbook》:Matplotlib 和 Seaborn 可视化
  • Pandas 官方文档:DataFrame.plot() 方法
  • Real Python – A Guide to Data Visualization with Pandas and Matplotlib

🔗 出站链接