GUEST0 pt
クイズ・バイオインフォの森

【Python】プルダウンによる散布図のカラーリング切替【Plotly】

Text
from matplotlib import pyplot as plt
import seaborn as sns
import plotly.graph_objects as go
Text
data = sns.load_dataset("penguins")


xvar = "bill_length_mm"
yvar = "body_mass_g"
huevar = "species"


fig = plt.figure()
sns.scatterplot(data=data, x=xvar, y=yvar, hue=huevar, alpha=0.75)
st.pyplot(fig)
Text
# グラフの作成
fig = go.Figure()


# 各単位のトレースを作成
cols = ["bill_length_mm", "bill_depth_mm", "flipper_length_mm", "body_mass_g"]
for cn in cols:
    fig.add_trace(
        go.Scatter(
            x=data["bill_length_mm"],
            y=data["bill_depth_mm"],
            mode='markers',
            text=data["species"],
            marker=dict(
                size=16,
                color=data[cn],  # マーカーの色をyにする
                colorscale='Jet',  # カラースケール変更
            ),
            # marker_color= data[cn],
            name=cn
        )
    )


# ドロップダウンメニューを作成
fig.update_layout(
    updatemenus=[
        dict(
            active=0,
            buttons=list([
                dict(
                    label=cn,
                    method="update",
                    args=[
                        {"visible": [True if i == j else False for j in range(len(cols))]},
                        {"title": f"Colored by {cn}"}
                    ])
                for i, cn in enumerate(cols)
            ])
        )
    ]
)


fig.update_layout(font_size=20, hoverlabel_font_size=20)


# 初期表示の設定
fig.update_traces(visible=False)
fig.data[0].visible = True


fig.show()
広告を取得中...
【Python】プルダウンによる散布図のカラーリング切替【Plotly】 | バイオインフォの森