1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

HTMLに埋め込んだplotlyグラフを凡例クリック時にグレーアウトさせる

Last updated at Posted at 2025-07-29

テスト中

code

import plotly.express as px

# サンプルデータでPlotly Express図を作成
df = px.data.iris()
fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species", title="Iris Plot")

# HTMLとしてエクスポート(スクリプト埋め込み形式、div単独取得)
html_div = fig.to_html(full_html=False, include_plotlyjs=False)

# 完全なHTMLページとして構成(JSライブラリとカスタムJSを追加)
custom_html = f"""
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Plotly Express Legend Gray Out</title>
    <script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
</head>
<body>

{html_div}

<script>
    // 凡例クリックでopacityを変更する処理
    var gd = document.querySelectorAll(".js-plotly-plot")[0];

    var activeStates = Array(gd.data.length).fill(true);

    gd.on('plotly_legendclick', function(eventData) {{
        const traceIndex = eventData.curveNumber;
        activeStates[traceIndex] = !activeStates[traceIndex];
        const newOpacity = activeStates.map(active => active ? 1.0 : 0.2);
        Plotly.restyle(gd, {{opacity: newOpacity}});
        return false;  // デフォルトの非表示動作を防ぐ
    }});
</script>

</body>
</html>
"""

# ファイルに保存
output_path = Path("/mnt/data/plotly_express_legend_grayout.html")
output_path.write_text(custom_html, encoding="utf-8")

output_path.name
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?