I have a dataset, df
that looks like this:
Date | Code | City | State | Quantity x | Quantity y | Population | Cases | Deaths |
---|---|---|---|---|---|---|---|---|
2019-01 | 10001 | Los Angeles | CA | 445 | 0 | 0 | ||
2019-01 | 10002 | Sacramento | CA | 4450 | 556 | 0 | 0 | |
2020-03 | 12223 | Houston | TX | 440 | 4440 | 35000000 | 23 | 11 |
… | … | … | … | … | … | … | … | … |
2021-07 | 10002 | Sacramento | CA | 3220 | NA | 5444000 | 211 | 22 |
My start and end date are the same for all cities. I have over 4000 different cities, and would like to plot a 2-yaxis graph for each city, using something similar to the following code:
JavaScript
x
17
17
1
import matplotlib.pyplot as plt
2
3
fig, ax1 = plt.subplots(figsize=(9,9))
4
5
color = 'tab:red'
6
ax1.set_xlabel('Date')
7
ax1.set_ylabel('Quantity X', color=color)
8
ax1.plot(df['Quantity x'], color=color)
9
ax1.tick_params(axis='y', labelcolor=color)
10
11
ax2 = ax1.twinx()
12
color2 = 'tab:blue'
13
ax2.set_ylabel('Deaths', color=color2)
14
ax2.plot(df['Deaths'], color=color2)
15
ax2.tick_params(axis='y', labelcolor=color2)
16
plt.show()
17
I would like to create a loop so that the code above runs for every Code
that is related to a City
, with quantity x and deaths, and it saves each graph made into a folder. How can I create a loop that does that, and stops every different Code
?
Observations: Some values on df['Quantity x]
and df[Population]
are left blank.
Advertisement
Answer
If I understood you correctly, you are looking for a filtering functionality:
JavaScript
1
33
33
1
import matplotlib.pyplot as plt
2
import pandas as pd
3
4
5
def plot_quantity_and_death(df):
6
# your code
7
fig, ax1 = plt.subplots(figsize=(9, 9))
8
9
color = 'tab:red'
10
ax1.set_xlabel('Date')
11
ax1.set_ylabel('Quantity X', color=color)
12
ax1.plot(df['Quantity x'], color=color)
13
ax1.tick_params(axis='y', labelcolor=color)
14
15
ax2 = ax1.twinx()
16
color2 = 'tab:blue'
17
ax2.set_ylabel('Deaths', color=color2)
18
ax2.plot(df['Deaths'], color=color2)
19
ax2.tick_params(axis='y', labelcolor=color2)
20
21
# save & close addon
22
plt.savefig(f"Code_{str(df['Code'].iloc[0])}.png")
23
plt.close()
24
25
26
df = pd.DataFrame() # this needs to be replaced by your dataset
27
28
# get unique city codes, loop over them, filter data and plot it
29
unique_codes = pd.unique(df['Code'])
30
for code in unique_codes:
31
filtered_df = df[df['Code'] == code]
32
plot_quantity_and_death(filtered_df)
33