简体   繁体   English

当源保存在文件中时,不会出现D3.js图

[英]D3.js graph does not appear when source is saved in file

HTML newbie question HTML新手问题

I'm trying to draw a graph using D3.js 我正在尝试使用D3.js绘制图形

The example I'm trying to learn from can be found here 我想要学习的例子可以在这里找到

I tried saving the source code to a file and opening the file in chrome and IE, however the chart was not displayed. 我尝试将源代码保存到文件并在chrome和IE中打开文件,但是没有显示图表。 In fact the entire page is blank. 实际上整个页面都是空白的。

The source code is here 源代码在这里

<!DOCTYPE html>
<meta charset="utf-8">
<style>

.chart rect {
  fill: steelblue;
}

.chart text {
  fill: white;
  font: 10px sans-serif;
  text-anchor: middle;
}

</style>
<svg class="chart"></svg>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>

var width = 960,
    height = 500;

var y = d3.scale.linear()
    .range([height, 0]);

var chart = d3.select(".chart")
    .attr("width", width)
    .attr("height", height);

d3.tsv("data.tsv", type, function(error, data) {
  y.domain([0, d3.max(data, function(d) { return d.value; })]);

  var barWidth = width / data.length;

  var bar = chart.selectAll("g")
      .data(data)
    .enter().append("g")
      .attr("transform", function(d, i) { return "translate(" + i * barWidth + ",0)"; });

  bar.append("rect")
      .attr("y", function(d) { return y(d.value); })
      .attr("height", function(d) { return height - y(d.value); })
      .attr("width", barWidth - 1);

  bar.append("text")
      .attr("x", barWidth / 2)
      .attr("y", function(d) { return y(d.value) + 3; })
      .attr("dy", ".75em")
      .text(function(d) { return d.value; });
});

function type(d) {
  d.value = +d.value; // coerce to number
  return d;
}

</script>

It looks like the only included script is <script src="http://d3js.org/d3.v3.min.js"></script> so I don't think I am missing any scripts. 看起来唯一包含的脚本是<script src="http://d3js.org/d3.v3.min.js"></script>所以我不认为我错过了任何脚本。

You won't be able to just open the .html file in your browser and have the script work, you need to serve it through an HTTP server. 您将无法在浏览器中打开.html文件并使脚本正常工作,您需要通过HTTP服务器提供它。 Python's built-in SimpleHTTPServer is a good choice. Python的内置SimpleHTTPServer是一个不错的选择。 Just cd to the directory with your HTML file in the terminal and type python -m SimpleHTTPServer . 只需在终端中使用HTML文件cd到目录,然后键入python -m SimpleHTTPServer You should now be able to view it by opening your browser to the IP address and port listed in the terminal. 您现在应该可以通过打开浏览器查看终端中列出的IP地址和端口来查看它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM