如何利用python绘制不同年份每月产品平均需求量变化曲线代码
时间: 2024-03-21 14:17:03 浏览: 19
以下是利用Python绘制不同年份每月产品平均需求量变化曲线的代码示例:
```
import pandas as pd
import matplotlib.pyplot as plt
# 读取数据
data = pd.read_csv('product_demand.csv')
# 将时间列转换为日期格式
data['date'] = pd.to_datetime(data['date'], format='%Y-%m-%d')
# 计算每月产品需求量均值
monthly_avg = data.groupby([pd.Grouper(key='date', freq='M'), 'product'])['demand'].mean().reset_index()
# 按年份分组
groups = monthly_avg.groupby(pd.Grouper(key='date', freq='Y'))
# 绘图
fig, axes = plt.subplots(nrows=len(groups), figsize=(6, 10))
for i, (year, group) in enumerate(groups):
ax = axes[i]
ax.set_title(year.year)
for product in group['product'].unique():
ax.plot(group[group['product'] == product]['date'], group[group['product'] == product]['demand'], label=product)
ax.legend()
plt.tight_layout()
plt.show()
```
说明:
1. 假设数据文件product_demand.csv中包含三列:日期(date)、产品(product)、需求量(demand);
2. 使用pandas库进行数据读取和处理,其中将日期列转化为日期格式,并按年份和产品分组计算出每月的需求量均值;
3. 将分组后的数据按年份分组,然后使用matplotlib库进行绘图,每个子图绘制一个年份,子图中每个产品对应一条曲线;
4. 可以根据实际情况调整图像大小和字体大小等参数。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)