使用D3.js加载用于可视化的本地数据

Loading local data for visualization using D3.js

本文关键字:数据 可视化 用于 D3 js 加载 使用      更新时间:2023-09-26

我正在进行一个项目,该项目要求我可视化一种相当复杂的数据类型(请参阅这个老问题)。简言之,我有一大块数据,可以导出为JSON、CSV或其他任意的平面格式,尽管如果可能的话,我更喜欢避免使用XML(有关底层数据的详细解释,请参阅上面的链接问题)。

我已经开始使用D3进行可视化,到目前为止,当我用一些非常简单的数据进行测试时,我写的布局似乎还可以,这些数据是我在Javascript中硬编码为数组的。我在D3中读到的关于数据绑定的教程有点令人困惑,因为有些使用JSON,有些使用TXT/CSV格式,而另一些则使用硬编码数组/矩阵。

在JSON的情况下,我看了一个教程,其中叙述者坚定地建议在Web服务器上托管JSON文件,并使用HTTP请求而不是本地文件读取来获取它。我意识到这是由于跨域请求的限制,我相信我必须设法解决这个问题。在这一点上,我不确定如何进行,因为:

  1. D3支持的可视化将基于一系列HTML报告,这些报告是作为我编写的分析工具的结果创建的。分析在用户计算机上完成,HTML报告也在客户端本地创建。

  2. 目标用户肯定不懂技术,因此不能指示他们在计算机上运行Web服务器,以便能够通过localhost 提供JSON或任何其他类型或资源

为了记录在案,我已经尝试运行python SimpleHTTPServer模块来尝试它,而且一切都很好。然后,我尝试对生成的HTML报告中的数据进行硬编码,然后从使用D3、的脚本中调用JSON对象

//d3.json("mydata.json", function(json){
d3.json(myjson, function(json){
    nodeData = json.elements;
....
}

这失败了,因为在这种情况下,当D3.js期望URL时,我最终发送了一个JSON对象。

我能做些什么来避免/解决这个问题?

要在不使用服务器的情况下加载数据本地文件,请在正文中附加一个脚本标记,并将源数据分配给所需的变量或对象元素。在下面的示例中,我从[country_ISO3CODE].js文件加载某个国家的数据。具体来说,阿富汗数据文件的内容可能采用以下格式:

data[AFG] = {"name": "Afghanistan", "estimate": 9.003, ... }

调用文件将具有以下内容:

if (!data[iso3]) { //only load the needed data-script as needed
    // if using jQuery
    $('body').append("<script type='text/javascript' src='jdb/"+ iso3 +".js'></script>")
    //If not using jQuery
    /*var script   = document.createElement("script");
    script.type  = "text/javascript";
    script.src   = "jdb/"+iso3+".js"; //?_="+ (new Date()); URL might have to be randomized to avoid cached data
    document.body.appendChild(script);
    */
    // call the data-handling function only after 
    // the desired data has fully loaded
    // in this case, I check every 100 milliseconds
    var intervalId = setInterval( function () {
        if (data[iso3]) {    //once data is detected, process data
            clearInterval(intervalId); //stop checking for data
            prepData(mainWrapper, iso3)
            drawCharts(mainWrapper, iso3)
        }
    }, 100)
}
else drawCharts(mainWrapper, iso3)

对于JSON:

var data = JSON.parse(JavascriptStringVariableThatContainsJSON);

对于CSV:

 var data = d3.csv.parseRows(JavascriptStringVariableThatContainsMyCSVdata);

//然后将数据添加到图形中并调用enter,类似于:

 var dataEnter = svg.selectAll("rect").data(data).enter();

如果您想通过FileReader调用加载本地数据,下面的内容取自JavaScript中的Reading本地文件。然而,在上面的例子的基础上,这段代码将图像文件加载到svg中,而不链接文件,而是实际将光栅数据插入svg中。您可以随意将光栅数据替换为任何其他数据,只需添加正确的处理即可…

首先是<body>部分中支持的html元素:

<input type="file" id="files" name="files[]" multiple />

然后,您想将<input ... />元素链接到<script>部分中的一些代码:

document.getElementById('files').addEventListener('change', handleFileSelect, false);

现在,文件后面的代码读取事件处理代码(在这种情况下,我想将本地映像加载到D3JS svg中):

function handleFileSelect(evt) {
    reader = new FileReader();
    reader.onabort = function(e) {alert('File read cancelled');};
    var imageObj = new Image();  //image object to hold the local file contents.
    //and given the asynchronous nature, set up the event so that when the image is loaded, do something with it:
    imageObj.onload = function() {image.datum(imageObj.src).attr("xlink:href", function(d) {return d})};
    //similarly for the file reading:
    reader.onload = function(e) {imageObj.src = reader.result};
    //With all the events set up, lets start reading the file in.
    //the secret sauce is the DataURL
    reader.readAsDataURL(evt.target.files[0]);
}

为了完整起见,图片背后的D3JS酱汁:

var svg = d3.select("body").append("svg");
var image = svg.append("defs")
    .append("pattern")
    .attr("id", "venus")
    .attr('patternUnits', 'userSpaceOnUse')
    .attr("width", 200)
    .attr("height", 200)
    .append("image")
    .attr("width", 200)
    .attr("height", 200);
var image2 = svg.append("rect")
    .attr("x", "0")
    .attr("y", "0")
    .attr("width", 200)
    .attr("height", 200)
    .attr("fill", "url(#venus)");

如果您每次都在生成HTML,您可以将数据作为JSON放在HTML的右侧,也可以放在可以从HTML引用的.js文件中,可能是通过生成的唯一URL。

D3有一些很棒的工具可以导入数据并对其进行操作。由于过去一直提供json服务(有时创建起来很麻烦),我更倾向于提供csv并在javascript/D3中进行操作,但我很想看看其他人如何回答你的问题。

这是一个简单的示例,在这里显示csv到嵌套json:https://gist.github.com/3053667

还有许多用于操作数据的工具:https://github.com/mbostock/d3/wiki/Arrays

如果你想切片和骰子,还有Crossfilter。看起来很值得一试,但我正在等待假人指南的发布!http://square.github.com/crossfilter/

d3.json通过ajax调用加载外部json文件-示例中的myjson变量已经是一个javascript对象,因此不需要加载它,只需在nodeData赋值中直接使用它即可。

nodeData = myjson.elements;