Project

General

Profile

Web tech » History » Version 5

jun chen, 02/12/2025 10:44 AM

1 1 jun chen
# Web tech
2
3 3 jun chen
{{toc}}
4
5 1 jun chen
6 4 jun chen
## How to visualize data:
7
8
D3 ref: https://observablehq.com/@d3/gallery  ,  https://johan.github.io/d3/ex/
9
Plotly ref: https://plotly.com/javascript/
10
11 5 jun chen
### js d3 内嵌数据显示折线
12 4 jun chen
13 1 jun chen
``` 
14
<!DOCTYPE html>
15
<html lang="en">
16
<head>
17
    <meta charset="UTF-8">
18
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
19
    <title>分段填充折线图</title>
20
    <script src="https://d3js.org/d3.v7.min.js"></script>
21
    <style>
22
        .tooltip {
23
            position: absolute;
24
            background-color: rgba(255, 255, 255, 0.9);
25
            border: 1px solid #ccc;
26
            padding: 5px;
27
            font-size: 12px;
28
            pointer-events: none;
29
            opacity: 0;
30
        }
31
        .line {
32
            fill: none;
33
            stroke: black;
34
            stroke-width: 2;
35
        }
36
    </style>
37
</head>
38
<body>
39
    <div id="chart"></div>
40
    <div class="tooltip" id="tooltip"></div>
41
42
    <script>
43
        // 示例数据
44
        const data = [
45
            { time: "2025-01-01", value: 10, description: "说明1" },
46
            { time: "2025-01-02", value: 15, description: "说明2" },
47
            { time: "2025-01-03", value: 20, description: "说明3" },
48
            { time: "2025-01-04", value: 25, description: "说明4" },
49
            { time: "2025-01-05", value: 30, description: "说明5" },
50
            { time: "2025-01-06", value: 35, description: "说明6" },
51
            { time: "2025-01-07", value: 40, description: "说明7" },
52
            { time: "2025-01-08", value: 45, description: "说明8" },
53
            { time: "2025-01-09", value: 50, description: "说明9" },
54
            { time: "2025-01-10", value: 55, description: "说明10" },
55
            { time: "2025-01-11", value: 60, description: "说明11" },
56
            { time: "2025-01-12", value: 65, description: "说明12" },
57
            { time: "2025-01-13", value: 70, description: "说明13" },
58
            { time: "2025-01-14", value: 75, description: "说明14" },
59
            { time: "2025-01-15", value: 80, description: "说明15" },
60
            { time: "2025-01-16", value: 85, description: "说明16" },
61
            { time: "2025-01-17", value: 90, description: "说明17" },
62
            { time: "2025-01-18", value: 95, description: "说明18" },
63
            { time: "2025-01-19", value: 100, description: "说明19" },
64
            { time: "2025-01-20", value: 105, description: "说明20" }
65
        ];
66
67
        // 设置图表尺寸
68
        const margin = { top: 20, right: 30, bottom: 30, left: 40 };
69
        const width = 800 - margin.left - margin.right;
70
        const height = 400 - margin.top - margin.bottom;
71
72
        // 创建 SVG 容器
73
        const svg = d3.select("#chart")
74
            .append("svg")
75
            .attr("width", width + margin.left + margin.right)
76
            .attr("height", height + margin.top + margin.bottom)
77
            .append("g")
78
            .attr("transform", `translate(${margin.left},${margin.top})`);
79
80
        // 解析时间格式
81
        const parseTime = d3.timeParse("%Y-%m-%d");
82
83
        // 格式化数据
84
        data.forEach(d => {
85
            d.time = parseTime(d.time);
86
            d.value = +d.value;
87
        });
88
89
        // 设置比例尺
90
        const x = d3.scaleTime()
91
            .domain(d3.extent(data, d => d.time))
92
            .range([0, width]);
93
94
        const y = d3.scaleLinear()
95
            .domain([0, d3.max(data, d => d.value)])
96
            .range([height, 0]);
97
98
        // 添加 X 轴
99
        svg.append("g")
100
            .attr("transform", `translate(0,${height})`)
101
            .call(d3.axisBottom(x));
102
103
        // 添加 Y 轴
104
        svg.append("g")
105
            .call(d3.axisLeft(y));
106
107
        // 创建折线生成器
108
        const line = d3.line()
109
            .x(d => x(d.time))
110
            .y(d => y(d.value));
111
112
        // 绘制折线
113
        svg.append("path")
114
            .datum(data)
115
            .attr("class", "line")
116
            .attr("d", line);
117
118
        // 分段填充颜色
119
        const first10 = data.slice(0, 10);
120
        const last10 = data.slice(-10);
121
        const middle = data.slice(10, -10);
122
123
        // 填充前十个时间段的绿色区域
124
        svg.append("path")
125
            .datum(first10)
126
            .attr("fill", "green")
127
            .attr("opacity", 0.3)
128
            .attr("d", d3.area()
129
                .x(d => x(d.time))
130
                .y0(height)
131
                .y1(d => y(d.value))
132
            );
133
134
        // 填充中间时间段的蓝色区域
135
        svg.append("path")
136
            .datum(middle)
137
            .attr("fill", "blue")
138
            .attr("opacity", 0.3)
139
            .attr("d", d3.area()
140
                .x(d => x(d.time))
141
                .y0(height)
142
                .y1(d => y(d.value))
143
            );
144
145
        // 填充后十个时间段的红色区域
146
        svg.append("path")
147
            .datum(last10)
148
            .attr("fill", "red")
149
            .attr("opacity", 0.3)
150
            .attr("d", d3.area()
151
                .x(d => x(d.time))
152
                .y0(height)
153
                .y1(d => y(d.value))
154
            );
155
156
        // 添加悬停交互
157
        const tooltip = d3.select("#tooltip");
158
159
        svg.selectAll(".dot")
160
            .data(data)
161
            .enter()
162
            .append("circle")
163
            .attr("class", "dot")
164
            .attr("cx", d => x(d.time))
165
            .attr("cy", d => y(d.value))
166
            .attr("r", 5)
167
            .attr("fill", "steelblue")
168
            .on("mouseover", (event, d) => {
169
                tooltip.style("opacity", 1)
170
                    .html(`时间: ${d3.timeFormat("%Y-%m-%d")(d.time)}<br>数值: ${d.value}<br>说明: ${d.description}`)
171
                    .style("left", `${event.pageX + 5}px`)
172
                    .style("top", `${event.pageY - 20}px`);
173
            })
174
            .on("mouseout", () => {
175
                tooltip.style("opacity", 0);
176
            });
177
    </script>
178
</body>
179
</html>
180
```
181
182 4 jun chen
### 以下是使用 **JavaScript** 和 **Python** 分别实现交互式网页图表的两种方法,包含完整代码和步骤说明:
183 1 jun chen
184
---
185
186
### **方法一:JavaScript + Plotly(纯前端实现)**
187
#### 特点:直接在浏览器中运行,无需后端,适合快速展示。
188 2 jun chen
189 1 jun chen
```html
190
<!DOCTYPE html>
191
<html>
192
<head>
193
    <title>交互式图表</title>
194
    <!-- 引入 Plotly.js -->
195
    <script src="https://cdn.plot.ly/plotly-2.24.1.min.js"></script>
196
</head>
197
<body>
198
    <div id="chart"></div>
199
200
    <script>
201
        // 读取CSV文件(假设文件名为 data.csv)
202
        fetch('data.csv')
203
            .then(response => response.text())
204
            .then(csvText => {
205
                // 解析CSV数据
206
                const rows = csvText.split('\n');
207
                const x = [], y = [];
208
                rows.forEach((row, index) => {
209
                    if (index === 0) return; // 跳过标题行
210
                    const [xVal, yVal] = row.split(',');
211
                    x.push(parseFloat(xVal));
212
                    y.push(parseFloat(yVal));
213
                });
214
215
                // 绘制图表
216
                Plotly.newPlot('chart', [{
217
                    x: x,
218
                    y: y,
219
                    type: 'scatter',
220
                    mode: 'lines+markers',
221
                    marker: { color: 'blue' },
222
                    line: { shape: 'spline' }
223
                }], {
224
                    title: '交互式数据图表',
225
                    xaxis: { title: 'X轴' },
226
                    yaxis: { title: 'Y轴' },
227
                    hovermode: 'closest'
228
                });
229
            });
230
    </script>
231
</body>
232
</html>
233
```
234
235
#### 使用步骤:
236
1. 将CSV文件命名为 `data.csv`,格式如下:
237
   ```csv
238
   x,y
239
   1,5
240
   2,3
241
   3,7
242
   4,2
243
   5,8
244
   ```
245
2. 将HTML文件和 `data.csv` 放在同一目录下,用浏览器打开HTML文件。
246
3. 效果:支持**缩放、悬停显示数值、拖拽平移**等交互。
247
248
---
249
250
### **方法二:Python + Plotly(生成独立HTML文件)**
251
#### 特点:适合Python用户,自动化生成图表文件。
252 2 jun chen
253 1 jun chen
```python
254
import pandas as pd
255
import plotly.express as px
256
257
# 1. 读取CSV文件
258
df = pd.read_csv("data.csv")
259
260
# 2. 创建交互式图表
261
fig = px.line(
262
    df, x='x', y='y',
263
    title='Python生成的交互式图表',
264
    markers=True,  # 显示数据点
265
    line_shape='spline'  # 平滑曲线
266
)
267
268
# 3. 自定义悬停效果和样式
269
fig.update_traces(
270
    hoverinfo='x+y',  # 悬停显示x和y值
271
    line=dict(width=2, color='royalblue'),
272
    marker=dict(size=8, color='firebrick')
273
)
274
275
# 4. 保存为HTML文件
276
fig.write_html("interactive_chart.html")
277
```
278
279
#### 使用步骤:
280
1. 安装依赖:
281
   ```bash
282
   pip install pandas plotly
283
   ```
284
2. 运行代码后,生成 `interactive_chart.html`,用浏览器打开即可看到图表。
285
286
---
287
288
### **交互功能对比**
289
| **功能**               | **JavaScript/Plotly** | **Python/Plotly** |
290
|------------------------|-----------------------|-------------------|
291
| 缩放/平移              | ✔️                    | ✔️                |
292
| 悬停显示数值           | ✔️                    | ✔️                |
293
| 数据点高亮             | ✔️                    | ✔️                |
294
| 导出为图片(PNG/JPEG) | ✔️                    | ✔️                |
295
| 动态更新数据           | ✔️(需额外代码)      | ❌                |
296
297
---
298
299
### **进阶方案(可选)**
300
1. **动态数据加载**(JavaScript):
301
   ```html
302
   <input type="file" id="csvFile" accept=".csv">
303
   <div id="chart"></div>
304
   <script>
305
     document.getElementById('csvFile').addEventListener('change', function(e) {
306
       const file = e.target.files[0];
307
       const reader = new FileReader();
308
       reader.onload = function(e) {
309
         // 解析并绘制图表(代码同方法一)
310
       };
311
       reader.readAsText(file);
312
     });
313
   </script>
314
   ```
315
   - 用户可上传任意CSV文件,实时生成图表。
316
317
2. **添加控件**(Python + Dash):
318
   ```python
319
   from dash import Dash, dcc, html
320
   import pandas as pd
321
   import plotly.express as px
322
323
   app = Dash(__name__)
324
   df = pd.read_csv("data.csv")
325
326
   app.layout = html.Div([
327
       dcc.Graph(
328
           id='live-chart',
329
           figure=px.scatter(df, x='x', y='y', title='Dash动态图表')
330
       ),
331
       html.Button('更新数据', id='update-button')
332
   ])
333
334
   if __name__ == '__main__':
335
       app.run_server(debug=True)
336
   ```
337
   - 运行后访问 `http://localhost:8050`,支持动态交互和按钮触发操作。
338
339
---
340
341
### **最终效果示例**
342
![交互式图表示例](https://plotly.com/javascript/static/images/line-chart.png)
343
344
选择适合你的场景快速实现吧!