数据框子集的交互式绘图

时间:2021-07-16 07:52:52

标签: python pandas matplotlib drop-down-menu jupyter-notebook

我有一个关于每个国家和每种疫苗的疫苗接种数量的数据框(这里只是摘录,完整数据集中大约有 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

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

1 个答案:

答案 0 :(得分:0)

假设您使用的是 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()))

simple interactive plot

以下是保持图形布局相同的替代版本:

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

standardized interactive plot

完整代码:

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