为什么此D3代码在Jupyter Notebook中不产生任何输出? [英] Why does this D3 code not produce any output in Jupyter Notebook?

查看:41
本文介绍了为什么此D3代码在Jupyter Notebook中不产生任何输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我关注了此博客此处,这里是代码我正在尝试在Jupyter Notebook上运行-本质上是来自虹膜数据集的简单散点图.

I followed this blog here and here's the code that I'm trying to run on my Jupyter Notebook - essentially a simple scatter plot from the iris dataset.

from IPython.core.display import display, HTML
from string import Template
import pandas as pd
import json, random

HTML('<script src="./d3.min.js"></script>')

filename = 'https://gist.githubusercontent.com/mbostock/3887118/raw/2e68ffbeb23fe4dadd9b0f6bca62e9def6ee9e17/data.tsv'
iris = pd.read_csv(filename,sep="\t")

iris_array_of_dicts = iris.to_dict(orient='records')

css_text = '''
.axis path,
.axis line {
  fill: none;
  stroke: #000;
  shape-rendering: crispEdges;
}

.dot {
  stroke: #000;
}
'''

js_text_template = Template('''
var margin = {top: 20, right: 20, bottom: 30, left: 40},
// ****    width = 960 - margin.left - margin.right, ****
// ****    height = 500 - margin.top - margin.bottom; ****
    width = 720 - margin.left - margin.right,
    height = 375 - margin.top - margin.bottom;

var x = d3.scale.linear()
    .range([0, width]);

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

var color = d3.scale.category10();

var xAxis = d3.svg.axis()
    .scale(x)
    .orient("bottom");

var yAxis = d3.svg.axis()
    .scale(y)
    .orient("left");

// **** var svg = d3.select("body").append("svg") ****
var svg = d3.select("#$graphdiv").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
  .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

// **** d3.tsv("data.tsv", function(error, data) { ****
// ****  if (error) throw error; ****

var data = $python_data ;

  data.forEach(function(d) {
    d.sepalLength = +d.sepalLength;
    d.sepalWidth = +d.sepalWidth;
  });

  x.domain(d3.extent(data, function(d) { return d.sepalWidth; })).nice();
  y.domain(d3.extent(data, function(d) { return d.sepalLength; })).nice();

  svg.append("g")
      .attr("class", "x axis")
      .attr("transform", "translate(0," + height + ")")
      .call(xAxis)
    .append("text")
      .attr("class", "label")
      .attr("x", width)
      .attr("y", -6)
      .style("text-anchor", "end")
      .text("Sepal Width (cm)");

  svg.append("g")
      .attr("class", "y axis")
      .call(yAxis)
    .append("text")
      .attr("class", "label")
      .attr("transform", "rotate(-90)")
      .attr("y", 6)
      .attr("dy", ".71em")
      .style("text-anchor", "end")
      .text("Sepal Length (cm)")

  svg.selectAll(".dot")
      .data(data)
    .enter().append("circle")
      .attr("class", "dot")
      .attr("r", 3.5)
      .attr("cx", function(d) { return x(d.sepalWidth); })
      .attr("cy", function(d) { return y(d.sepalLength); })
      .style("fill", function(d) { return color(d.species); });

  var legend = svg.selectAll(".legend")
      .data(color.domain())
    .enter().append("g")
      .attr("class", "legend")
      .attr("transform", function(d, i) { return "translate(0," + i * 20 + ")"; });

  legend.append("rect")
      .attr("x", width - 18)
      .attr("width", 18)
      .attr("height", 18)
      .style("fill", color);

  legend.append("text")
      .attr("x", width - 24)
      .attr("y", 9)
      .attr("dy", ".35em")
      .style("text-anchor", "end")
      .text(function(d) { return d; });

// **** }); ****

''')

html_template = Template('''
<style> $css_text </style>
<div id="graph-div"></div>
<script> $js_text </script>
''')

js_text = js_text_template.substitute({'python_data': json.dumps(iris_array_of_dicts),
                                       'graphdiv': 'graph-div'})
HTML(html_template.substitute({'css_text': css_text, 'js_text': js_text}))

代码运行无误,但不显示任何输出. 我也尝试过使用显示功能,但仍然无法产生任何结果.

The code runs without errors but doesn't display any output. I've also tried to use the display functionality but that still produces no results.

我做错了什么?我的假设是,由于这是一篇老博客文章,Jupyter已经不再支持这种方式支持Javascript,现在我必须使用单元格和换行符,但是我不确定我是Java的新手.

What am I doing wrong? My assumption is that since this is an old blog post, Jupyter has moved past supporting Javascript this way and I have to use cell and line magics now but I'm not sure as I'm new to Javascript.

推荐答案

我刚刚尝试并找出了问题所在.

I have just tried and figured out the problem.

如果您查看控制台日志,则浏览器不会解释d3.要解决它,请添加到您的代码中.

If you look at the console log, the browser do not interpret d3. To solve it add to your code.

<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>

您现在将看到漂亮的情节

You will now see your nice plot

In [1]:
from IPython.core.display import display, HTML
from string import Template
import pandas as pd
import json, random

HTML('<script src="./d3.min.js"></script>')

filename = 'https://gist.githubusercontent.com/mbostock/3887118/raw/2e68ffbeb23fe4dadd9b0f6bca62e9def6ee9e17/data.tsv'
iris = pd.read_csv(filename,sep="\t")

iris_array_of_dicts = iris.to_dict(orient='records')

css_text = '''
.axis path,
.axis line {
  fill: none;
  stroke: #000;
  shape-rendering: crispEdges;
}

.dot {
  stroke: #000;
}
'''

js_text_template = Template('''

var margin = {top: 20, right: 20, bottom: 30, left: 40},
// ****    width = 960 - margin.left - margin.right, ****
// ****    height = 500 - margin.top - margin.bottom; ****
    width = 720 - margin.left - margin.right,
    height = 375 - margin.top - margin.bottom;

var x = d3.scale.linear()
    .range([0, width]);

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

var color = d3.scale.category10();

var xAxis = d3.svg.axis()
    .scale(x)
    .orient("bottom");

var yAxis = d3.svg.axis()
    .scale(y)
    .orient("left");

// **** var svg = d3.select("body").append("svg") ****
var svg = d3.select("#$graphdiv").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
  .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

// **** d3.tsv("data.tsv", function(error, data) { ****
// ****  if (error) throw error; ****

var data = $python_data ;

  data.forEach(function(d) {
    d.sepalLength = +d.sepalLength;
    d.sepalWidth = +d.sepalWidth;
  });

  x.domain(d3.extent(data, function(d) { return d.sepalWidth; })).nice();
  y.domain(d3.extent(data, function(d) { return d.sepalLength; })).nice();

  svg.append("g")
      .attr("class", "x axis")
      .attr("transform", "translate(0," + height + ")")
      .call(xAxis)
    .append("text")
      .attr("class", "label")
      .attr("x", width)
      .attr("y", -6)
      .style("text-anchor", "end")
      .text("Sepal Width (cm)");

  svg.append("g")
      .attr("class", "y axis")
      .call(yAxis)
    .append("text")
      .attr("class", "label")
      .attr("transform", "rotate(-90)")
      .attr("y", 6)
      .attr("dy", ".71em")
      .style("text-anchor", "end")
      .text("Sepal Length (cm)")

  svg.selectAll(".dot")
      .data(data)
    .enter().append("circle")
      .attr("class", "dot")
      .attr("r", 3.5)
      .attr("cx", function(d) { return x(d.sepalWidth); })
      .attr("cy", function(d) { return y(d.sepalLength); })
      .style("fill", function(d) { return color(d.species); });

  var legend = svg.selectAll(".legend")
      .data(color.domain())
    .enter().append("g")
      .attr("class", "legend")
      .attr("transform", function(d, i) { return "translate(0," + i * 20 + ")"; });

  legend.append("rect")
      .attr("x", width - 18)
      .attr("width", 18)
      .attr("height", 18)
      .style("fill", color);

  legend.append("text")
      .attr("x", width - 24)
      .attr("y", 9)
      .attr("dy", ".35em")
      .style("text-anchor", "end")
      .text(function(d) { return d; });

// **** }); ****

''')
html_template = Template('''
<style > $css_text </style>
<div id="graph-div"></div>
<script > $js_text </script>
''')

js_text = js_text_template.substitute({'python_data': json.dumps(iris_array_of_dicts),
                                       'graphdiv': 'graph-div'})
my_plot = html_template.substitute({'css_text': css_text, 'js_text': js_text})
d3_download = """ <script src="http://d3js.org/d3.v3.min.js" charset="utf-8" > </script>"""

my_plot = d3_download + my_plot

HTML(my_plot)

Out [1]:

这篇关于为什么此D3代码在Jupyter Notebook中不产生任何输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆