Project

General

Profile

Actions

Web tech » History » Revision 6

« Previous | Revision 6/29 (diff) | Next »
jun chen, 02/12/2025 10:45 AM


Web tech

How to visualize data:

D3 ref: https://observablehq.com/@d3/gallery , https://johan.github.io/d3/ex/
Plotly ref: https://plotly.com/javascript/

js d3 内嵌数据显示折线

show code...

以下是使用 JavaScriptPython 分别实现交互式网页图表的两种方法,包含完整代码和步骤说明:


方法一:JavaScript + Plotly(纯前端实现)

特点:直接在浏览器中运行,无需后端,适合快速展示。

<!DOCTYPE html>
<html>
<head>
    <title>交互式图表</title>
    <!-- 引入 Plotly.js -->
    <script src="https://cdn.plot.ly/plotly-2.24.1.min.js"></script>
</head>
<body>
    <div id="chart"></div>

    <script>
        // 读取CSV文件(假设文件名为 data.csv)
        fetch('data.csv')
            .then(response => response.text())
            .then(csvText => {
                // 解析CSV数据
                const rows = csvText.split('\n');
                const x = [], y = [];
                rows.forEach((row, index) => {
                    if (index === 0) return; // 跳过标题行
                    const [xVal, yVal] = row.split(',');
                    x.push(parseFloat(xVal));
                    y.push(parseFloat(yVal));
                });

                // 绘制图表
                Plotly.newPlot('chart', [{
                    x: x,
                    y: y,
                    type: 'scatter',
                    mode: 'lines+markers',
                    marker: { color: 'blue' },
                    line: { shape: 'spline' }
                }], {
                    title: '交互式数据图表',
                    xaxis: { title: 'X轴' },
                    yaxis: { title: 'Y轴' },
                    hovermode: 'closest'
                });
            });
    </script>
</body>
</html>

使用步骤:

  1. 将CSV文件命名为 data.csv,格式如下:
    x,y
    1,5
    2,3
    3,7
    4,2
    5,8
    
  2. 将HTML文件和 data.csv 放在同一目录下,用浏览器打开HTML文件。
  3. 效果:支持缩放、悬停显示数值、拖拽平移等交互。

方法二:Python + Plotly(生成独立HTML文件)

特点:适合Python用户,自动化生成图表文件。

import pandas as pd
import plotly.express as px

# 1. 读取CSV文件
df = pd.read_csv("data.csv")

# 2. 创建交互式图表
fig = px.line(
    df, x='x', y='y',
    title='Python生成的交互式图表',
    markers=True,  # 显示数据点
    line_shape='spline'  # 平滑曲线
)

# 3. 自定义悬停效果和样式
fig.update_traces(
    hoverinfo='x+y',  # 悬停显示x和y值
    line=dict(width=2, color='royalblue'),
    marker=dict(size=8, color='firebrick')
)

# 4. 保存为HTML文件
fig.write_html("interactive_chart.html")

使用步骤:

  1. 安装依赖:
    pip install pandas plotly
    
  2. 运行代码后,生成 interactive_chart.html,用浏览器打开即可看到图表。

交互功能对比

功能 JavaScript/Plotly Python/Plotly
缩放/平移 ✔️ ✔️
悬停显示数值 ✔️ ✔️
数据点高亮 ✔️ ✔️
导出为图片(PNG/JPEG) ✔️ ✔️
动态更新数据 ✔️(需额外代码)

进阶方案(可选)

  1. 动态数据加载(JavaScript):

    <input type="file" id="csvFile" accept=".csv">
    <div id="chart"></div>
    <script>
      document.getElementById('csvFile').addEventListener('change', function(e) {
        const file = e.target.files[0];
        const reader = new FileReader();
        reader.onload = function(e) {
          // 解析并绘制图表(代码同方法一)
        };
        reader.readAsText(file);
      });
    </script>
    
    • 用户可上传任意CSV文件,实时生成图表。
  2. 添加控件(Python + Dash):

    from dash import Dash, dcc, html
    import pandas as pd
    import plotly.express as px
    
    app = Dash(__name__)
    df = pd.read_csv("data.csv")
    
    app.layout = html.Div([
        dcc.Graph(
            id='live-chart',
            figure=px.scatter(df, x='x', y='y', title='Dash动态图表')
        ),
        html.Button('更新数据', id='update-button')
    ])
    
    if __name__ == '__main__':
        app.run_server(debug=True)
    
    • 运行后访问 http://localhost:8050,支持动态交互和按钮触发操作。

最终效果示例

交互式图表示例

选择适合你的场景快速实现吧!

Updated by jun chen 4 months ago · 29 revisions