[英]How to generate 2-yaxis graphs on a panel data per id?
我有一个数据集df
,它看起来像这样:
日期 | 代码 | 城市 | State | 数量 x | 数量 y | 人口 | 案例 | 死亡人数 |
---|---|---|---|---|---|---|---|---|
2019-01 | 10001 | 洛杉矶 | 加州 | 445 | 0 | 0 | ||
2019-01 | 10002 | 萨克拉门托 | 加州 | 4450 | 556 | 0 | 0 | |
2020-03 | 12223 | 休斯顿 | TX | 440 | 4440 | 3500万 | 23 | 11 |
... | ... | ... | ... | ... | ... | ... | ... | ... |
2021-07 | 10002 | 萨克拉门托 | 加州 | 3220 | 北美 | 5444000 | 211 | 22 |
我的开始和结束日期对所有城市都是一样的。 我有超过 4000 个不同的城市,并且想要 plot 每个城市的 2-yaxis 图,使用类似于以下代码的东西:
import matplotlib.pyplot as plt
fig, ax1 = plt.subplots(figsize=(9,9))
color = 'tab:red'
ax1.set_xlabel('Date')
ax1.set_ylabel('Quantity X', color=color)
ax1.plot(df['Quantity x'], color=color)
ax1.tick_params(axis='y', labelcolor=color)
ax2 = ax1.twinx()
color2 = 'tab:blue'
ax2.set_ylabel('Deaths', color=color2)
ax2.plot(df['Deaths'], color=color2)
ax2.tick_params(axis='y', labelcolor=color2)
plt.show()
我想创建一个循环,以便上面的代码针对与City
相关的每个Code
运行,数量为 x 和死亡,并将每个图表保存到一个文件夹中。 我如何创建一个循环来执行此操作并停止每个不同的Code
?
观察: df['Quantity x]
和df[Population]
上的某些值留空。
如果我理解正确的话,您正在寻找过滤功能:
import matplotlib.pyplot as plt
import pandas as pd
def plot_quantity_and_death(df):
# your code
fig, ax1 = plt.subplots(figsize=(9, 9))
color = 'tab:red'
ax1.set_xlabel('Date')
ax1.set_ylabel('Quantity X', color=color)
ax1.plot(df['Quantity x'], color=color)
ax1.tick_params(axis='y', labelcolor=color)
ax2 = ax1.twinx()
color2 = 'tab:blue'
ax2.set_ylabel('Deaths', color=color2)
ax2.plot(df['Deaths'], color=color2)
ax2.tick_params(axis='y', labelcolor=color2)
# save & close addon
plt.savefig(f"Code_{str(df['Code'].iloc[0])}.png")
plt.close()
df = pd.DataFrame() # this needs to be replaced by your dataset
# get unique city codes, loop over them, filter data and plot it
unique_codes = pd.unique(df['Code'])
for code in unique_codes:
filtered_df = df[df['Code'] == code]
plot_quantity_and_death(filtered_df)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.