数据帧子集的交互式绘图

2024-05-23 21:10:01 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我想生成一个特定国家每种疫苗接种数量的条形图。我想通过选择一个下拉菜单的国家,情节是互动的


Tags: 数据框架数量国家countrymodernausaindia
1条回答
网友
1楼 · 发布于 2024-05-23 21:10:01

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

相关问题 更多 >