您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
# 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进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。