数据框子集的交互式绘图

Interactive plotting of a subset of a dataframe

我有一个每个国家和每种疫苗的疫苗接种数量的数据框(这里只是一个摘录,完整数据集中大约有 30 个国家)。

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

我想生成一个条形图,显示给定国家/地区每种疫苗的接种次数。我希望通过使用下拉菜单选择国家/地区来使情节具有交互性。

假设您使用的是 Jupyter notebook

输入数据:

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],
                  })

您可以创建一个函数来仅绘制一个国家并使用 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()))

这是一个替代版本,可以使图表之间的布局保持一致:

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()))

完整代码:

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()));