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