Python數(shù)據(jù)可視化之Pandas、Matplotlib與Seaborn的高效實戰(zhàn)指南
使用Pandas內(nèi)置的繪圖功能
Pandas基于Matplotlib封裝了便捷的繪圖接口,使數(shù)據(jù)可視化變得異常簡單。.plot()方法能夠智能識別DataFrame結(jié)構(gòu)并生成合適的圖表。
基礎(chǔ)繪圖功能
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# 創(chuàng)建示例數(shù)據(jù)
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年月度業(yè)績趨勢',
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年月度業(yè)績對比',
figsize=(10, 6),
color=['#3498db', '#2ecc71'], # 自定義顏色
alpha=0.8,
rot=45) # x軸標(biāo)簽旋轉(zhuǎn)角度
plt.ylabel('金額(萬元)')
plt.grid(axis='y', alpha=0.3)
plt.show()
# 面積圖
df.plot.area(title='2023年月度業(yè)績構(gòu)成',
figsize=(10, 6),
alpha=0.4,
stacked=False) # 非堆疊模式
plt.ylabel('金額(萬元)')
plt.grid(True, alpha=0.3)
plt.show()
專業(yè)技巧
# 多子圖繪制
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='業(yè)績分布分析',
figsize=(8, 6),
vert=False, # 水平箱線圖
patch_artist=True) # 填充顏色
plt.xlabel('金額(萬元)')
plt.show()
與Matplotlib結(jié)合進行高級繪圖
雖然Pandas繪圖便捷,但結(jié)合Matplotlib可以實現(xiàn)更精細(xì)的控制和更專業(yè)的可視化效果。
雙坐標(biāo)軸圖表
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()
專業(yè)金融圖表
from mplfinance.original_flavor import candlestick_ohlc
import matplotlib.dates as mdates
# 準(zhǔn)備股票數(shù)據(jù)
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)
# 轉(zhuǎn)換為OHLC格式
data = pd.DataFrame({
'Open': open_prices,
'High': high_prices,
'Low': low_prices,
'Close': close_prices
}, index=dates)
# 創(chuàng)建專業(yè)K線圖
fig, ax = plt.subplots(figsize=(12, 6))
# 轉(zhuǎn)換日期格式
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軸轉(zhuǎn)換為日期格式
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結(jié)合進行統(tǒng)計圖形繪制
Seaborn是基于Matplotlib的高級統(tǒng)計可視化庫,特別適合數(shù)據(jù)分布和關(guān)系分析。
分布可視化
import seaborn as sns
# 設(shè)置Seaborn風(fēng)格
sns.set_style("whitegrid")
sns.set_palette("husl")
# 創(chuàng)建示例數(shù)據(jù)
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()
關(guān)系分析
# 散點圖矩陣
sns.pairplot(tips, hue="time",
palette="Set2",
height=2.5,
corner=True) # 只顯示下三角
plt.suptitle('消費數(shù)據(jù)關(guān)系矩陣', y=1.02)
plt.show()
# 熱力圖(相關(guān)性分析)
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': '相關(guān)系數(shù)'})
plt.title('消費數(shù)據(jù)相關(guān)性分析', fontsize=14)
plt.xticks(rotation=45)
plt.yticks(rotation=0)
plt.show()
高級統(tǒng)計圖表
# 回歸分析圖
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('消費金額與小費金額關(guān)系', fontsize=14)
plt.xlabel('消費金額(美元)')
plt.ylabel('小費金額(美元)')
plt.grid(True, alpha=0.3)
plt.show()
# 分面網(wǎng)格(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('不同場景下消費金額與小費關(guān)系', y=1.03)
plt.tight_layout()
plt.show()
三庫結(jié)合的綜合案例
# 創(chuàng)建綜合可視化面板
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雙坐標(biāo)軸圖')
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關(guān)系圖
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()
專業(yè)建議與最佳實踐
工具選擇原則
快速探索:優(yōu)先使用Pandas內(nèi)置繪圖
統(tǒng)計可視化:首選Seaborn
高度定制化:使用Matplotlib底層API
性能優(yōu)化
# 大數(shù)據(jù)集優(yōu)化 plt.plot(large_data.index, large_data.values, '-', rasterized=True)
樣式統(tǒng)一
# 全局樣式設(shè)置
plt.style.use('seaborn')
plt.rcParams.update({
'font.size': 12,
'axes.titlesize': 14,
'axes.labelsize': 12
})
交互式可視化
# 啟用交互模式 plt.ion() # 繪制圖表后保持交互 plt.show(block=True)
輸出專業(yè)報告
# 保存高質(zhì)量圖片
plt.savefig('professional_plot.png',
dpi=300,
bbox_inches='tight',
transparent=True)
通過掌握Pandas、Matplotlib和Seaborn這三大可視化工具的組合使用,我們就能夠高效地從數(shù)據(jù)探索過渡到專業(yè)報告制作,滿足不同場景下的數(shù)據(jù)可視化需求。
到此這篇關(guān)于Python數(shù)據(jù)可視化之Pandas、Matplotlib與Seaborn的高效實戰(zhàn)指南的文章就介紹到這了,更多相關(guān)Python數(shù)據(jù)可視化內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- Python數(shù)據(jù)可視化完全指南之Matplotlib+Seaborn+Plotly用法詳解
- Python數(shù)據(jù)可視化庫:Matplotlib、Seaborn、Plotly、Bokeh等對比與選擇
- python安裝?Matplotlib?庫和Seaborn?庫的示例詳解
- Python繪圖工具使用Matplotlib、Seaborn和Pyecharts繪制散點圖詳解
- Python使用Matplotlib和Seaborn繪制常用圖表的技巧
- Python數(shù)據(jù)可視化之Matplotlib和Seaborn的使用教程詳解
- Python實現(xiàn)Matplotlib,Seaborn動態(tài)數(shù)據(jù)圖的示例代碼
- Python?matplotlib?seaborn繪圖教程詳解
- python可視化分析的實現(xiàn)(matplotlib、seaborn、ggplot2)
- Python AI基礎(chǔ):Matplotlib和Seaborn兩大可視化庫的原理和使用(實踐代碼)
相關(guān)文章
matplotlib如何設(shè)置坐標(biāo)軸刻度的個數(shù)及標(biāo)簽的方法總結(jié)
這里介紹兩種設(shè)置坐標(biāo)軸刻度的方法,一種是利用pyplot提交的api去進行設(shè)置,另一種是通過調(diào)用面向?qū)ο蟮腶pi, 即通過matplotlib.axes.Axes去設(shè)置,需要的朋友可以參考下2021-06-06
pytorch 實現(xiàn)多個Dataloader同時訓(xùn)練
這篇文章主要介紹了pytorch 實現(xiàn)多個Dataloader同時訓(xùn)練的操作,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-05-05
python實現(xiàn)Zabbix-API監(jiān)控
這篇文章主要為大家詳細(xì)介紹了python實現(xiàn)Zabbix-API監(jiān)控,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-09-09

