Skip to content

高级绘图

除了基础绘图,Pandas 还支持更多高级可视化功能。

多子图

python
import pandas as pd
import matplotlib.pyplot as plt

plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False

df = pd.DataFrame({
    '月份': ['1月', '2月', '3月', '4月', '5月'],
    '销售额': [100, 120, 110, 130, 140],
    '利润': [20, 25, 22, 28, 30],
    '客户数': [500, 550, 530, 600, 620]
})

# 创建多子图
fig, axes = plt.subplots(2, 2, figsize=(12, 10))

df.plot(x='月份', y='销售额', kind='bar', ax=axes[0, 0], title='销售额')
df.plot(x='月份', y='利润', kind='line', ax=axes[0, 1], title='利润', marker='o')
df.plot(x='月份', y='客户数', kind='area', ax=axes[1, 0], title='客户数', alpha=0.5)
df.plot(x='月份', y=['销售额', '利润'], kind='bar', ax=axes[1, 1], title='对比')

plt.tight_layout()
plt.show()

双Y轴

python
# 双Y轴图
ax1 = df.plot(x='月份', y='销售额', kind='bar', color='blue', figsize=(10, 6))
ax2 = ax1.twinx()
df.plot(x='月份', y='利润', kind='line', color='red', marker='o', ax=ax2)

ax1.set_ylabel('销售额', color='blue')
ax2.set_ylabel('利润', color='red')
plt.title('销售额与利润对比')
plt.show()

时间序列绘图

python
import numpy as np

# 创建时间序列数据
dates = pd.date_range('2024-01-01', periods=30, freq='D')
ts_data = pd.DataFrame({
    '价格': np.cumsum(np.random.randn(30)) + 100
}, index=dates)

# 时间序列图
ts_data.plot(figsize=(12, 6))
plt.title('价格走势')
plt.show()

# 添加移动平均线
ts_data['MA7'] = ts_data['价格'].rolling(window=7).mean()
ts_data.plot(figsize=(12, 6))
plt.title('价格走势与移动平均')
plt.legend(['价格', '7日均线'])
plt.show()

分组绘图

python
df_group = pd.DataFrame({
    '类别': ['A', 'A', 'B', 'B', 'C', 'C'],
    '月份': ['1月', '2月', '1月', '2月', '1月', '2月'],
    '销售额': [100, 120, 80, 90, 110, 130]
})

# 透视后绘图
pivot_df = df_group.pivot(index='月份', columns='类别', values='销售额')
pivot_df.plot(kind='bar', figsize=(10, 6))
plt.title('各类别销售额对比')
plt.legend(title='类别')
plt.show()

热力图

python
import seaborn as sns

# 创建相关性矩阵
df_corr = pd.DataFrame({
    'A': np.random.randn(100),
    'B': np.random.randn(100),
    'C': np.random.randn(100),
    'D': np.random.randn(100)
})
corr_matrix = df_corr.corr()

# 绘制热力图
plt.figure(figsize=(8, 6))
sns.heatmap(corr_matrix, annot=True, cmap='coolwarm', center=0)
plt.title('相关性热力图')
plt.show()

保存图表

python
# 保存为图片
df.plot(x='月份', y='销售额', kind='bar', figsize=(10, 6))
plt.title('月度销售额')
plt.savefig('sales.png', dpi=300, bbox_inches='tight')
plt.savefig('sales.pdf', bbox_inches='tight')
plt.savefig('sales.svg', bbox_inches='tight')

交互式绘图

python
# 使用plotly创建交互式图表
try:
    import plotly.express as px
    
    fig = px.line(df, x='月份', y='销售额', title='月度销售额')
    fig.show()
    
    fig = px.bar(df, x='月份', y='销售额', color='利润', title='销售额与利润')
    fig.show()
except ImportError:
    print("请安装plotly: pip install plotly")

高级绘图功能可以创建更专业的数据可视化,满足不同的展示需求。