1

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?

1
  • I have an interactive pie chart solution it uses from ipywidgets import interact, interactive, fixed, interact_manual imports and uses update_piechart function with the interactive(update_piechart, time=timerange) call. Basically it is a big slider with a timerange and a pie chart showing the values for the selected timerange Commented Jul 3, 2019 at 18:59

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

2 Comments

Great tips! Thanks. I added unstack() also. But how can I use column names as Title?
You can write them as text before the plot for an example. Even better you can use the 'title=' argument for the plot function. See doc reference pandas.pydata.org/pandas-docs/stable/reference/api/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.