I have a dataframe of the number of vaccinations per country and per vaccine (here is only an extract, there is about 30 countries in the full dataset).
Country Vaccines Total vaccinations
Austria Pfizer 65000
Austria Moderna 56000
Austria Astrazenca 9000
USA Pfizer 110000
USA Moderna 90000
USA JJ 46000
India Covaxin 312000
India Covishield 256000
Germany Pfizer 36000
Germany Moderna 22000
Germany Covaxin 7000
Germany Astrazenca 14500
I would like to generate a bar plot of the number of vaccinations per vaccine for a given country. I would like the plot to be interactive by selecting the country with a drop down menu.
Assuming you are using a Jupyter notebook .
Input data:
df = pd.DataFrame({'Country': ['Austria', 'Austria', 'Austria', 'USA', 'USA', 'USA', 'India', 'India', 'Germany', 'Germany', 'Germany', 'Germany'],
'Vaccines': ['Pfizer', 'Moderna', 'Astrazenca', 'Pfizer', 'Moderna', 'JJ', 'Covaxin', 'Covishield', 'Pfizer', 'Moderna', 'Covaxin', 'Astrazenca'],
'Total vaccinations': [ 65000, 56000, 9000, 110000, 90000, 46000, 312000, 256000, 36000, 22000, 7000, 14500],
})
You can create a function to plot only one country and call it interactively using ipywidgets :
import ipywidgets as widgets
def plot_bars(country):
df.query('Country == @country').plot.bar(x='Vaccines', y='Total vaccinations')
widgets.interact(plot_bars, country=widgets.Dropdown(value='Austria', options=df.Country.unique()))
Here is an alternative version to keep the layout of the graphs identical among graphs:
import ipywidgets as widgets
df2 = df.pivot(index='Vaccines', columns='Country').fillna(0).astype(int)['Total vaccinations']
def plot_bars(country):
ax = df2[country].plot.bar()
ax.set_ylim(ymax=df2.max().max()*1.1)
widgets.interact(plot_bars, country=widgets.Dropdown(value='Austria', options=df.Country.unique()))
Full code:
import pandas as pd
import ipywidgets as widgets
df = pd.DataFrame({'Country': ['Austria', 'Austria', 'Austria', 'USA', 'USA', 'USA', 'India', 'India', 'Germany', 'Germany', 'Germany', 'Germany'],
'Vaccines': ['Pfizer', 'Moderna', 'Astrazenca', 'Pfizer', 'Moderna', 'JJ', 'Covaxin', 'Covishield', 'Pfizer', 'Moderna', 'Covaxin', 'Astrazenca'],
'Total vaccinations': [ 65000, 56000, 9000, 110000, 90000, 46000, 312000, 256000, 36000, 22000, 7000, 14500],
})
def plot_bars(country):
df.query('Country == @country').plot.bar(x='Vaccines', y='Total vaccinations')
widgets.interact(plot_bars, country=widgets.Dropdown(value='Austria', options=df.Country.unique()));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.