change graph dataframe by selecting button in plotly

Question:

import pandas as pd
import plotly.graph_objs as go
import plotly.express as px

tmp_df = {
"col_a" : [1,2,3,4,5,6], "col_b":[0,1,0,1,0,1], 
"col_c":[2,4,6,8,10,12], "col_d":[9,8,7,6,5,4]}
tmp_df = pd.DataFrame(tmp_df)

fig = px.scatter_3d(data_frame = tmp_df, x="col_a",  y='col_c', z='col_d', color="col_b")
data_type = tmp_df.col_b.unique()
buttons = []
for counter, i in enumerate(data_type):
    buttons.append(dict(method='update',
                        label = '{}'.format(i),
                        args = [    {"data_frame" : tmp_df[tmp_df.col_b == i].to_json() # TypeError: Object of type DataFrame is not JSON serializable
                                }  ]
                        )
                   )
fig.update_layout(updatemenus=[dict(buttons=buttons, direction='down', x=0.1, y=1.15)])
fig.show()

hi. I’m pretty noob in plotly.

above code is 3d scatter graph about two types data with selecting buttons. (above code is simple example code. it runs without bug. )

I want to make it possible to select the data I want to see by pressing a button, but the button appears but does not work.

What am I missing?

Asked By: vitamin Cho

||

Answers:

Instead of using .to_json() which is invalid for the data_frame parameter of the scatter_3d() function, you can pass the dataframe directly.

Replace your for loop with the following.

for counter, i in enumerate(data_type):
    buttons.append(dict(method='update',
                        label='{}'.format(i),
                        args=[{"x": [tmp_df[tmp_df.col_b == i].col_a],
                               "y": [tmp_df[tmp_df.col_b == i].col_c],
                               "z": [tmp_df[tmp_df.col_b == i].col_d],
                               "type": "scatter3d",
                               "mode": "markers",
                               "marker": {"color": tmp_df[tmp_df.col_b == i].col_b.map({0: "red", 1: "blue"})}
                              }]
                       )
                  )
Answered By: tmc
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.