2

I am trying to make an interactive plot in Jupyter, and it works somewhat with one problem, which is that every time I hit the button to generate a plot, a new plot is appended instead of the current one being replaced. Any ideas on how to fix this problem?

field_ddl = widgets.Dropdown(
    options=['race', 'gender', 'grade'],
    value='race',
    description='field:',
    disabled=False,
    button_style='info'
)
graph_btn = widgets.Button(
    description='graph',
    disabled=False,
    button_style='success',
    tooltip='distribution plot',
    icon='check'
)

def graph_btn_clicked(e):
    field = field_ddl.value
    df[field].value_counts().plot(kind='bar', title=field)

graph_btn.on_click(graph_btn_clicked)

display(field_ddl)
display(graph_btn)

I've looked up the interact feature, but that doesn't seem to help. Upon initialization, a graph is produced, but when the I select another field and hit the button again, nothing happens.

interact(graph_btn_clicked, x=graph_btn)
Jane Wayne
  • 8,205
  • 17
  • 75
  • 120

1 Answers1

3

You may use the interactive backend

%matplotlib notebook

Then create a figure and an axes to plot to,

fig, ax = plt.subplots()

Then each time the button is clicked, clear the old plot and plot the new to the same axes.

def graph_btn_clicked(e):
    field = field_ddl.value
    ax.clear()
    df[field].value_counts().plot(kind='bar', title=field, ax=ax)
ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712
  • 1
    `%matplotlib notebook` seems to conflict with `%matplotlib inline`. With this approach, would I have to switch between the two as needed? – Jane Wayne Jun 07 '17 at 17:00