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