使用绝对路径将文件加载到d3.js中的csv文件

时间:2020-07-14 08:46:40

标签: javascript d3.js

例如,如果它位于同一工作目录中,则可以加载一个csv文件:

.defer(d3.csv,"data.csv", function(d) { .. })

但是,如果文件位于另一个目录中,并且我通过了绝对路径,则不会加载该文件:

.defer(d3.csv,"/home/path/data.csv", function(d) {..})

我收到代码404,未找到消息文件

我已经在运行本地Web服务器

编辑

我正在关注本教程:

https://www.d3-graph-gallery.com/graph/choropleth_basic.html 这是index.html

<script>

    // The svg
    var svg = d3.select("svg"),
      width = +svg.attr("width"),
      height = +svg.attr("height");
    
    // Map and projection
    var path = d3.geoPath();
    var projection = d3.geoMercator()
      .scale(70)
      .center([0,20])
      .translate([width / 2, height / 2]);
    
    // Data and color scale
    var data = d3.map();
    var colorScale = d3.scaleThreshold()
      .domain([10, 30, 40, 50, 70, 100])
      .range(d3.schemeBlues[7]);
    
    // Load external data and boot
    d3.queue()
      .defer(d3.json, "https://raw.githubusercontent.com/holtzy/D3-graph-gallery/master/DATA/world.geojson")
      .defer(d3.csv, "data.csv", function(d) { data.set(d.codice, d.rtt); })
      .await(ready);
    
    function ready(error, topo) {
    
      // Draw the map
      svg.append("g")
        .selectAll("path")
        .data(topo.features)
        .enter()
        .append("path")
          // draw each country
          .attr("d", d3.geoPath()
            .projection(projection)
          )
          // set the color of each country
          .attr("fill", function (d) {
            d.total = data.get(d.id) || 0;
            return colorScale(d.total);
          });
        }
    
    </script>

如果文件data.csv与index.html处于同一目录,那么哪个可以工作,但是如果文件位于另一个目录中,并且我得到:

code 404, message File not found

Uncaught TypeError: topo is undefined
    ready http://localhost:8000/:43
    _call https://d3js.org/d3.v4.js:11174
    maybeNotify https://d3js.org/d3.v4.js:11251
    abort https://d3js.org/d3.v4.js:11244
    end https://d3js.org/d3.v4.js:11218
    call https://d3js.org/d3.v4.js:792
    respond https://d3js.org/d3.v4.js:11397

编辑2

尝试以这种方式直接加载csv文件而不先下载它,但是不起作用:

if (rows.length == 5) {
   createmap(createcsv(rows))
}
function createcsv(rows) {

    let csvContent = "data:text/csv;charset=utf-8,";

    csvContent ="codice,rtt"+"\r\n";

    rows.forEach(function(rowArray) {

        let row = rowArray.join(",");

        csvContent +=row+"\r\n";

    });

    return csvContent;

}


function createmap(map) {
d3.queue()
          .defer(d3.json, "https://raw.githubusercontent.com/holtzy/D3-graph-gallery/master/DATA/world.geojson")
          .defer(d3.csv, mappa, function(d) { data.set(d.codice, d.rtt); })
          .await(ready)
}

1 个答案:

答案 0 :(得分:0)

这里没有几件事:

  1. 确保您的data.csv和dat.csv命名法不是问题。

  2. 您是否要尝试访问权限不属于以下内容的目录? 本地主机?您需要允许www-data才能访问 路径。看来您正在尝试访问/ home / path /,这很可能不在www-data的访问范围内。或者只是尝试将data.csv放在/var/www/yourapplication/path/内的某个位置。可能会有帮助。

相关问题