Plotting with multiple y values with subplot and groupby

扶醉桌前 提交于 2021-01-29 17:28:44

问题


I have a df. See below for the head:

Country         Date     suspected case    confirmed cases   suspected deaths   confirmed deaths   

0   Guinea   2014-08-29       25.0            141.0              482.0              648.0
1   Nigeria  2014-08-29       3.0             1.0                15.0               19.0
2   Liberia  2014-08-29       382.0           674.0              322.0              1378.0

By using df.groupby('Country') I want to plot the suspected case against the confirmed case using the Date column for the xaxis. Plotting these as (5, 2) subplots

What I've done so far hasn't quite got it yet:

fig, ax = plt.subplots(2, 5, sharey=True)
df.groupby('Country').plot(x='Date', y=['suspected cases', 'confirmed cases'], title=f'Suspected vs. Confirmed cases {country}')
plt.show()

What's happened so far is that there is an empty 5x2 subplot and below displays each graph individually. Why is this?

Also just a minor issue but would like some clarification. Within my .plot() function, why is the last grouped country only being shown in the title? For instance I have 10 countries grouped together for this plot but the title Suspected vs. Confirmed cases USA is showing fr each graph.

Looked at a few SO posts and combined a few answers to try to solve my problem but I seem to be going in circles.


回答1:


You could do:

fig, ax = plt.subplots(2, 5, sharey=True)
for (c,d), a in zip(df.groupby('Country'), ax.ravel()):
    d.plot(x='Date', 
           y=['suspected cases', 'confirmed cases'], 
           title=f'Suspected vs. Confirmed cases {c}', 
           ax=a, subplots=False)

Output:



来源:https://stackoverflow.com/questions/60815052/plotting-with-multiple-y-values-with-subplot-and-groupby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!