Python数据可视化之Pandas、Matplotlib与Seaborn的高效实战指南
作者:豆本-豆豆奶
本文介绍了Python数据可视化的综合解决方案,涵盖Pandas、Matplotlib和Seaborn三大工具的使用技巧,文中的示例代码讲解详细,感兴趣的小伙伴可以了解下
使用Pandas内置的绘图功能
Pandas基于Matplotlib封装了便捷的绘图接口,使数据可视化变得异常简单。.plot()方法能够智能识别DataFrame结构并生成合适的图表。
基础绘图功能
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# 创建示例数据
np.random.seed(42)
df = pd.DataFrame({
'销售额': np.random.randint(100, 500, 12).cumsum(),
'利润': np.random.randint(20, 80, 12).cumsum()
}, index=pd.date_range('2023-01-01', periods=12, freq='M'))
# 基本折线图
df.plot(title='2023年月度业绩趋势',
figsize=(10, 6),
style=['-o', '--s'], # 线条样式
linewidth=2,
markersize=8)
plt.ylabel('金额(万元)')
plt.grid(True, alpha=0.3)
plt.show()
多种图表类型
# 柱状图
df.plot.bar(title='2023年月度业绩对比',
figsize=(10, 6),
color=['#3498db', '#2ecc71'], # 自定义颜色
alpha=0.8,
rot=45) # x轴标签旋转角度
plt.ylabel('金额(万元)')
plt.grid(axis='y', alpha=0.3)
plt.show()
# 面积图
df.plot.area(title='2023年月度业绩构成',
figsize=(10, 6),
alpha=0.4,
stacked=False) # 非堆叠模式
plt.ylabel('金额(万元)')
plt.grid(True, alpha=0.3)
plt.show()
专业技巧
# 多子图绘制
axes = df.plot(subplots=True,
figsize=(10, 8),
layout=(2, 1),
sharex=True,
title=['销售额趋势', '利润趋势'],
style=['-o', '--s'])
plt.tight_layout()
plt.show()
# 箱线图(自动按列绘制)
df.plot.box(title='业绩分布分析',
figsize=(8, 6),
vert=False, # 水平箱线图
patch_artist=True) # 填充颜色
plt.xlabel('金额(万元)')
plt.show()
与Matplotlib结合进行高级绘图
虽然Pandas绘图便捷,但结合Matplotlib可以实现更精细的控制和更专业的可视化效果。
双坐标轴图表
fig, ax1 = plt.subplots(figsize=(10, 6))
# 第一个y轴(销售额)
color = '#3498db'
ax1.set_xlabel('月份')
ax1.set_ylabel('销售额(万元)', color=color)
ax1.plot(df.index, df['销售额'], color=color, marker='o')
ax1.tick_params(axis='y', labelcolor=color)
ax1.grid(True, alpha=0.3)
# 第二个y轴(利润率)
ax2 = ax1.twinx()
color = '#e74c3c'
ax2.set_ylabel('利润率(%)', color=color)
# 计算利润率(示例)
profit_rate = (df['利润']/df['销售额']*100).values
ax2.plot(df.index, profit_rate, color=color, marker='s', linestyle='--')
ax2.tick_params(axis='y', labelcolor=color)
plt.title('2023年销售额与利润率趋势', pad=20)
fig.tight_layout()
plt.show()
专业金融图表
from mplfinance.original_flavor import candlestick_ohlc
import matplotlib.dates as mdates
# 准备股票数据
np.random.seed(42)
dates = pd.date_range('2023-01-01', periods=20)
open_prices = np.random.normal(100, 5, 20).cumsum()
high_prices = open_prices + np.random.uniform(1, 3, 20)
low_prices = open_prices - np.random.uniform(1, 3, 20)
close_prices = open_prices + np.random.normal(0, 1, 20)
# 转换为OHLC格式
data = pd.DataFrame({
'Open': open_prices,
'High': high_prices,
'Low': low_prices,
'Close': close_prices
}, index=dates)
# 创建专业K线图
fig, ax = plt.subplots(figsize=(12, 6))
# 转换日期格式
data['Date'] = mdates.date2num(data.index.to_pydatetime())
ohlc = data[['Date', 'Open', 'High', 'Low', 'Close']].values
# 绘制K线
candlestick_ohlc(ax, ohlc, width=0.6,
colorup='r', colordown='g', alpha=0.8)
# 添加移动平均线
data['MA5'] = data['Close'].rolling(5).mean()
ax.plot(data['Date'], data['MA5'], 'b-', label='5日均线')
# 图表装饰
ax.xaxis_date() # 将x轴转换为日期格式
ax.xaxis.set_major_formatter(mdates.DateFormatter('%m-%d'))
plt.xticks(rotation=45)
plt.title('股票K线图示例', fontsize=14)
plt.ylabel('价格(元)')
plt.legend()
plt.grid(True, alpha=0.3)
plt.tight_layout()
plt.show()
与Seaborn结合进行统计图形绘制
Seaborn是基于Matplotlib的高级统计可视化库,特别适合数据分布和关系分析。
分布可视化
import seaborn as sns
# 设置Seaborn风格
sns.set_style("whitegrid")
sns.set_palette("husl")
# 创建示例数据
tips = sns.load_dataset("tips")
# 分布图(直方图+KDE)
plt.figure(figsize=(10, 6))
sns.histplot(data=tips, x="total_bill", kde=True,
bins=20, alpha=0.6)
plt.title('消费金额分布', fontsize=14)
plt.xlabel('消费金额(美元)')
plt.ylabel('频次')
plt.show()
# 小提琴图(展示分布密度)
plt.figure(figsize=(10, 6))
sns.violinplot(data=tips, x="day", y="total_bill",
hue="sex", split=True,
inner="quartile")
plt.title('不同性别每日消费分布', fontsize=14)
plt.xlabel('星期')
plt.ylabel('消费金额(美元)')
plt.legend(title='性别')
plt.show()
关系分析
# 散点图矩阵
sns.pairplot(tips, hue="time",
palette="Set2",
height=2.5,
corner=True) # 只显示下三角
plt.suptitle('消费数据关系矩阵', y=1.02)
plt.show()
# 热力图(相关性分析)
plt.figure(figsize=(8, 6))
corr = tips.corr(numeric_only=True)
sns.heatmap(corr, annot=True, fmt=".2f",
cmap="coolwarm",
linewidths=.5,
cbar_kws={'label': '相关系数'})
plt.title('消费数据相关性分析', fontsize=14)
plt.xticks(rotation=45)
plt.yticks(rotation=0)
plt.show()
高级统计图表
# 回归分析图
plt.figure(figsize=(10, 6))
sns.regplot(data=tips, x="total_bill", y="tip",
scatter_kws={'alpha':0.5},
line_kws={'color':'red'})
plt.title('消费金额与小费金额关系', fontsize=14)
plt.xlabel('消费金额(美元)')
plt.ylabel('小费金额(美元)')
plt.grid(True, alpha=0.3)
plt.show()
# 分面网格(FacetGrid)
g = sns.FacetGrid(tips, col="time", row="smoker",
margin_titles=True,
height=4)
g.map(sns.scatterplot, "total_bill", "tip", alpha=0.7)
g.fig.suptitle('不同场景下消费金额与小费关系', y=1.03)
plt.tight_layout()
plt.show()
三库结合的综合案例
# 创建综合可视化面板
plt.figure(figsize=(16, 12))
# 子图1:Pandas折线图
plt.subplot(2, 2, 1)
df.plot(ax=plt.gca(), style=['-o', '--s'], linewidth=2)
plt.title('Pandas折线图')
plt.grid(True, alpha=0.3)
# 子图2:Matplotlib高级图表
plt.subplot(2, 2, 2)
ax1 = plt.gca()
ax1.plot(df.index, df['销售额'], 'b-o', label='销售额')
ax1.set_ylabel('销售额(万元)', color='b')
ax1.tick_params(axis='y', labelcolor='b')
ax1.grid(True, alpha=0.3)
ax2 = ax1.twinx()
ax2.plot(df.index, profit_rate, 'r--s', label='利润率')
ax2.set_ylabel('利润率(%)', color='r')
ax2.tick_params(axis='y', labelcolor='r')
plt.title('Matplotlib双坐标轴图')
lines1, labels1 = ax1.get_legend_handles_labels()
lines2, labels2 = ax2.get_legend_handles_labels()
ax1.legend(lines1 + lines2, labels1 + labels2, loc='upper left')
# 子图3:Seaborn分布图
plt.subplot(2, 2, 3)
sns.violinplot(data=tips, x="day", y="total_bill", hue="sex", split=True)
plt.title('Seaborn小提琴图')
plt.legend(title='性别')
# 子图4:Seaborn关系图
plt.subplot(2, 2, 4)
sns.scatterplot(data=tips, x="total_bill", y="tip",
hue="time", style="sex", size="size",
sizes=(20, 200), alpha=0.7)
plt.title('Seaborn多维度散点图')
plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left')
plt.tight_layout()
plt.show()
专业建议与最佳实践
工具选择原则
快速探索:优先使用Pandas内置绘图
统计可视化:首选Seaborn
高度定制化:使用Matplotlib底层API
性能优化
# 大数据集优化 plt.plot(large_data.index, large_data.values, '-', rasterized=True)
样式统一
# 全局样式设置
plt.style.use('seaborn')
plt.rcParams.update({
'font.size': 12,
'axes.titlesize': 14,
'axes.labelsize': 12
})
交互式可视化
# 启用交互模式 plt.ion() # 绘制图表后保持交互 plt.show(block=True)
输出专业报告
# 保存高质量图片
plt.savefig('professional_plot.png',
dpi=300,
bbox_inches='tight',
transparent=True)
通过掌握Pandas、Matplotlib和Seaborn这三大可视化工具的组合使用,我们就能够高效地从数据探索过渡到专业报告制作,满足不同场景下的数据可视化需求。
到此这篇关于Python数据可视化之Pandas、Matplotlib与Seaborn的高效实战指南的文章就介绍到这了,更多相关Python数据可视化内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
