简体   繁体   中英

How to create interactive plot in Jupyter Notebook and Python

I have a following dataframe.

CustID| Age |Gender|Smoking_history |Alcohol_history

1 |18-24| M | Non-smoker | <21 units per week

2 |43-48| F | Non-smoker | <21 units per week

3 |37-42| M | Unknown | <21 units per week

4 |18-24| F | Unknown | Unknown

5 |43-48| M | Previous smoker | <21 units per week

I created bar plot and used the following code:

df.groupby(['Smoking history','Age']).size().unstack().plot(kind='bar',stacked=True) plt.show()

It is noted that Age is a numeric range value, and "Smoking history" is string value.

It creates stacked bar plot in Jupyter Notebook and shows number of persons in different age groups based on smoking history.

I want to make it interactive, so that I can select columns from drop down list.

How can I do it by using ipywidgets in Jupyter Notebook?

** Is there any way to use non-numeric columns in plot?

Actually it is not that difficult to create it. First you have to import all the required widget library. Library widgets holds the definition of the ui elements. The interactive library will call you custom function every time you triggered an event on the element -- in our case selecting a different column. Each time the function get called you we just return a new plot. Please note that you should only read data from your dataset inside the function. Changing it could introduce side effects in later cells.

import ipywidgets as widgets
from ipywidgets import interact, interactive, fixed, interact_manual
drop_down=widgets.Dropdown(
    options=data2.columns.values,
    value='Age',
    description='Column:',
    disabled=False,
)

def update_barchart(columns):
    return data2.groupby(columns).size().plot(kind='bar',stacked=True)

interactive(update_barchart, columns=drop_down)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM