在 HTML 中嵌入 csv 以与 D3.js 一起使用 [英] Embedding csv in HTML for use with D3.js
问题描述
在 D3.js 中,通常从外部 csv 文件加载数据.这对于大数据非常有效,并且避免了数据变化时更改代码.
但是,有两种情况(仅使用小型 csv 数据)我想将 csv 直接嵌入 HTML 页面:
- 无需运行本地 HTTP 服务器即可在本地(即从 file:///)加载的页面.
- 一个小 jsfiddle 示例,解释了用于 stackoverflow 的 D3.js 问题.
这是我想出的解决方案,使用来自 D3.js API.
嵌入 csv 数据:
年份、品牌、型号、长度1997,福特,E350,2.342000,水星,美洲狮,2.38
在页面上隐藏原始数据:
#csvdata {显示:无;}
解析:
var raw = d3.select("#csvdata").text();var parsed = d3.csv.parse(raw);
可选地,显示结果:
d3.select("#parsed").text(JSON.stringify(parsed));//假设 <div id="parsed"></div>页面上的某处
如果觉得这有缺陷,或者你有更优雅的解决方案,我很乐意接受你的回答!
中查看它的实际效果In D3.js, one usually loads data from an external csv file. This is very efficient for large data, and avoids changing the code when the data changes.
However, there are two situations (only using small csv data) where I want to embed csv directly in an HTML page:
- A page that can be loaded locally (i.e. from file:///), without requiring to run a local HTTP server.
- A small jsfiddle example explaining a D3.js question for use on stackoverflow.
This is the solution I have come up with, using the example from the D3.js API.
Embedding the csv data:
<pre id="csvdata">
Year,Make,Model,Length
1997,Ford,E350,2.34
2000,Mercury,Cougar,2.38
</pre>
Hidding the raw data on the page:
#csvdata {
display: none;
}
Parsing it:
var raw = d3.select("#csvdata").text();
var parsed = d3.csv.parse(raw);
Optionally, show the result:
d3.select("#parsed").text(JSON.stringify(parsed));
// Assuming <div id="parsed"></div> somewhere on the page
If think this is flawed, or if you have a more elegant solution, I will gladly accept your answer!
EDIT: see it in action in this fiddle
这篇关于在 HTML 中嵌入 csv 以与 D3.js 一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!