Plot a line chart with checkboxes from indexed data frame


#1

I am working on an indexed data frame (immigration) that looks like this:

I would like to plot a line chart for each state with the years in the x axis, and add checkboxes so the user can choose which state to display in the plot.

I got stuck in the very first step trying to create the line chart. It looks like I am not slicing my data frame correctly…?

    data = [
    go.Scatter(
        x=immigration.iloc[1], 
        y=immigration.loc["State"]
    )
]

layout = go.Layout(
    title='Immigration',
    yaxis=dict(title='Immigration %'),
    xaxis=dict(title='Years')
)

fig = go.Figure(data=data, layout=layout)

#2

Hi @suttersg,

To get the values in the second row in your dataframe, you can use immigration.iloc[1]. Or, to get the row corresponding to a particular state, say “Maryland”, you can use immigration.loc["Maryland"].

Based on your description, you would want to use one of these as the y property of your scatter trace.

To get the corresponding years for your x coordinate you can use immigration.columns

Here’s a full example

import pandas as pd
import plotly.graph_objs as go
from plotly.offline import plot

immigration = pd.DataFrame({
    'State': ['California', 'New York', 'New Jersey'],
    1850: [23, 21, 12],
    1851: [28, 21, 13],
    1852: [31, 22, 13]}).set_index('State')

data = [go.Scatter(x=immigration.columns,
                   y=immigration.loc[state],
                   name=state) for state in immigration.index]

layout = go.Layout(
    title='Immigration',
    yaxis=dict(title='Immigration %'),
    xaxis=dict(title='Years')
)

fig = go.Figure(data=data, layout=layout)
plot(fig)

And, if all you want to do is show and hide traces, you can actually do this by clicking on traces in the legend. Single click to toggle the individual trace. Double click to toggle all of the other traces.

Hope that helps!
-Jon