在Python中为每个类别创建多个按月分组的图表可以通过以下步骤实现:
import pandas as pd
import matplotlib.pyplot as plt
data = {'Category': ['A', 'A', 'B', 'B', 'C', 'C'],
'Date': ['2022-01-01', '2022-02-01', '2022-01-01', '2022-02-01', '2022-01-01', '2022-02-01'],
'Value': [10, 15, 8, 12, 5, 9]}
df = pd.DataFrame(data)
df['Date'] = pd.to_datetime(df['Date']) # 将日期列转换为日期类型
df_grouped = df.groupby(['Category', pd.Grouper(key='Date', freq='M')]).sum().reset_index()
categories = df_grouped['Category'].unique() # 获取所有类别
for category in categories:
category_data = df_grouped[df_grouped['Category'] == category]
plt.plot(category_data['Date'], category_data['Value'], label=category)
plt.xlabel('Date')
plt.ylabel('Value')
plt.legend()
plt.show()
这样就可以在Python中为每个类别创建多个按月分组的图表。根据具体需求,可以进一步调整图表的样式、添加标题等。
没有搜到相关的结果
领取专属 10元无门槛券
手把手带您无忧上云