在Python中按周绘制多个折线图可以使用Matplotlib库进行实现。Matplotlib是一个常用的Python数据可视化库,提供了丰富的绘图功能。
以下是实现该功能的步骤:
import matplotlib.pyplot as plt
import datetime
data = {
'data1': {'2021-01-01': 10, '2021-01-08': 15, '2021-01-15': 12, ...},
'data2': {'2021-01-01': 5, '2021-01-08': 8, '2021-01-15': 6, ...},
...
}
grouped_data = {}
for dataset, values in data.items():
grouped_data[dataset] = {}
for date_str, value in values.items():
date = datetime.datetime.strptime(date_str, '%Y-%m-%d')
week_number = date.strftime('%U') # 获取周数
if week_number in grouped_data[dataset]:
grouped_data[dataset][week_number].append(value)
else:
grouped_data[dataset][week_number] = [value]
for dataset, values in grouped_data.items():
weeks = list(values.keys())
plt.plot(weeks, [sum(v)/len(v) for v in values.values()], label=dataset)
plt.xlabel('Week')
plt.ylabel('Average Value')
plt.title('Multiple Line Plots')
plt.legend()
plt.show()
完整的代码示例:
import matplotlib.pyplot as plt
import datetime
data = {
'data1': {'2021-01-01': 10, '2021-01-08': 15, '2021-01-15': 12},
'data2': {'2021-01-01': 5, '2021-01-08': 8, '2021-01-15': 6},
}
grouped_data = {}
for dataset, values in data.items():
grouped_data[dataset] = {}
for date_str, value in values.items():
date = datetime.datetime.strptime(date_str, '%Y-%m-%d')
week_number = date.strftime('%U')
if week_number in grouped_data[dataset]:
grouped_data[dataset][week_number].append(value)
else:
grouped_data[dataset][week_number] = [value]
for dataset, values in grouped_data.items():
weeks = list(values.keys())
plt.plot(weeks, [sum(v)/len(v) for v in values.values()], label=dataset)
plt.xlabel('Week')
plt.ylabel('Average Value')
plt.title('Multiple Line Plots')
plt.legend()
plt.show()
推荐的腾讯云相关产品:腾讯云服务器(CVM),产品介绍链接地址:https://cloud.tencent.com/product/cvm
领取专属 10元无门槛券
手把手带您无忧上云