# Python Pandas工具繪制數據圖怎么實現
## 一、前言
在數據分析和可視化領域,Python的Pandas庫與Matplotlib/Seaborn的結合已成為行業標準。本文將詳細介紹如何利用Pandas內置的繪圖功能快速實現數據可視化,涵蓋從基礎圖表到高級定制的完整流程。
## 二、環境準備與數據加載
### 1. 安裝必要庫
```python
pip install pandas matplotlib seaborn
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline # Jupyter Notebook魔法命令
# 生成時間序列數據
date_rng = pd.date_range(start='2023-01-01', end='2023-12-31', freq='D')
df = pd.DataFrame({
'date': date_rng,
'value': np.random.randn(len(date_rng)).cumsum(),
'category': np.random.choice(['A','B','C'], len(date_rng))
})
df.set_index('date')['value'].plot(
figsize=(12, 6),
title='時間序列趨勢圖',
xlabel='日期',
ylabel='數值',
grid=True,
color='royalblue'
)
plt.show()
df.groupby('category').size().plot.bar(
rot=0,
color=['#1f77b4', '#ff7f0e', '#2ca02c'],
edgecolor='black',
title='類別分布'
)
df['value'].plot.hist(
bins=30,
alpha=0.7,
density=True,
figsize=(10,6)
)
df.plot.box(
column='value',
by='category',
vert=False,
patch_artist=True
)
fig, axes = plt.subplots(2, 2, figsize=(14,10))
df['value'].plot.hist(ax=axes[0,0], title='分布直方圖')
df['value'].plot.kde(ax=axes[0,1], title='密度估計')
df.groupby('category')['value'].mean().plot.bar(ax=axes[1,0], title='均值比較')
df['value'].rolling(30).mean().plot(ax=axes[1,1], title='30日移動平均')
plt.tight_layout()
ax = df['value'].plot(color='blue', label='原始值')
ax2 = ax.twinx()
df['value'].rolling(7).mean().plot(
color='red',
ax=ax2,
label='7日均線'
)
ax.legend(loc='upper left')
ax2.legend(loc='upper right')
df_sample = pd.DataFrame({
'A': np.random.rand(50).cumsum(),
'B': np.random.rand(50).cumsum(),
'C': np.random.rand(50).cumsum()
})
df_sample.plot.area(
alpha=0.4,
stacked=False,
figsize=(12,6)
)
plt.style.use('seaborn-darkgrid')
df['value'].plot(figsize=(12,6))
colors = {'A':'#1f77b4', 'B':'#ff7f0e', 'C':'#2ca02c'}
df.groupby('category')['value'].plot(
legend=True,
color=[colors[x] for x in df['category'].unique()]
)
ax = df['value'].plot()
ax.annotate('峰值點',
xy=(df['value'].idxmax(), df['value'].max()),
xytext=(10,10),
textcoords='offset points',
arrowprops=dict(arrowstyle='->'))
sales_data = pd.DataFrame({
'Month': pd.date_range('2023-01', periods=12, freq='M'),
'Product_A': np.random.randint(50,200,12),
'Product_B': np.random.randint(30,150,12),
'Product_C': np.random.randint(80,250,12)
})
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(16,6))
# 月度趨勢圖
sales_data.set_index('Month').plot(
ax=ax1,
marker='o',
title='月度銷售趨勢'
)
# 年度占比餅圖
sales_data.sum()[1:].plot.pie(
ax=ax2,
autopct='%.1f%%',
explode=(0,0.1,0),
shadow=True,
startangle=90
)
plt.suptitle('2023年度銷售分析', y=1.05, fontsize=16)
plotting.backend
切換為Plotlypd.options.plotting.backend = 'plotly'
df.plot().get_figure().savefig('output.svg', format='svg')
import plotly.express as px
px.line(df, x='date', y='value', color='category')
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
from matplotlib.dates import DateFormatter
ax = df.plot()
ax.xaxis.set_major_formatter(DateFormatter('%Y-%m'))
df.plot().legend(
loc='upper center',
bbox_to_anchor=(0.5, -0.1),
ncol=3
)
Pandas的繪圖API提供了數據可視化的快速入口,關鍵優勢包括: - 與DataFrame無縫集成 - 語法簡潔直觀 - 支持大多數常見圖表類型 - 可輕松與Matplotlib生態系統結合
通過本文介紹的方法,您可以高效完成80%的常規數據可視化需求。對于更復雜的場景,建議結合Seaborn或Plotly等專業可視化庫。
最佳實踐建議:將常用的繪圖配置封裝為函數,建立自己的可視化工具庫,可顯著提升分析效率。 “`
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。