0
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-05-10

出力されるHTMLファイル

image.png

コード

import plotly.graph_objs as go
import pandas as pd

# Sample data
df = pd.DataFrame({
    'x': [1, 2, 3, 4, 5],
    'y': [10, 20, 15, 25, 30],
    'details': ['A', 'B', 'C', 'D', 'E'],
    'extra': ['Info1', 'Info2', 'Info3', 'Info4', 'Info5']
})

# Create plot
fig = go.Figure()

fig.add_trace(go.Scatter(
    x=df['x'],
    y=df['y'],
    mode='markers',
    text=df['details'],
    customdata=df['extra'],
    # hoverinfo='x+y',  # Show only X and Y on hover
    name='Data points'
))

fig.update_layout(
    title='Click to Show Details',
    xaxis_title='X-axis',
    yaxis_title='Y-axis'
)

# Export the plot to HTML
html_content = fig.to_html(full_html=False, include_plotlyjs='cdn')

# HTML template
html_template = f"""
<!DOCTYPE html>
<html>
<head>
    <title>Click to Show Details</title>
    <script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
</head>
<body>
    <div id="plotly-div">{html_content}</div>
    <div id="details">
        <h3>Clicked Data Details</h3>
        <table border="1" id="detail-table">
            <tr><th>X</th><th>Y</th><th>Details</th><th>Extra</th></tr>
        </table>
    </div>
    <script>
        // Bind click event
        var plotDiv = document.getElementById('plotly-div').getElementsByClassName('plotly-graph-div')[0];
        plotDiv.on('plotly_click', function(data) {{
            var point = data.points[0];
            var x = point.x;
            var y = point.y;
            var text = point.text;
            var extra = point.customdata;

            // Clear the table and insert new data
            var table = document.getElementById('detail-table');
            while (table.rows.length > 1) {{
                table.deleteRow(1);
            }}

            // Add a new row with the clicked data
            var newRow = table.insertRow(-1);
            newRow.insertCell(0).innerHTML = x;
            newRow.insertCell(1).innerHTML = y;
            newRow.insertCell(2).innerHTML = text;
            newRow.insertCell(3).innerHTML = extra;
        }});
    </script>
</body>
</html>
"""

# Save HTML file
output_dir = "xxx"
file_name = "plotly_click_details.html"
with open("/".join([output_dir,file_name]), "w", encoding="utf-8") as f:
    f.write(html_template)

print(f"HTML file generated: {file_name}")
0
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
0
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?