如何在d3js中添加垂直线到bar char?

时间:2017-03-13 11:57:08

标签: d3.js bar-chart

我是noob使用d3js我正在尝试在d3js的基本水平条形图上添加一个新的垂直。要使用codepen测试我,但不显示垂直线。

HTML文件

<head>
  <!-- Plotly.js -->
  <script src="http://d3js.org/d3.v3.min.js"></script>
  <script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
</head>
<body>
  <div id="myDiv" style="width: 480px; height: 400px;"><!-- Plotly chart will be drawn inside this DIV --></div>
 <script>
  <!-- JAVASCRIPT CODE GOES HERE -->
 </script>
</body>

JS档案

var trace1 = {
  x: [20],
  y: ['giraffes'],
  name: 'SF Zoo',
  orientation: 'h',
  marker: {
    color: 'rgba(55,128,191,0.6)',
    width: 1
 },
 type: 'bar'
};

var data = [trace1];

var layout = {
  title: 'Colored Bar Chart',
  barmode: 'stack'
};

Plotly.newPlot('myDiv', data, layout);

var y = d3.scale.linear().range([0, 400]);
var svg = d3.select(document.getElementById('myDiv'));
svg.append("line")
.attr("x1", 10)
.attr("y1", y(0))
.attr("x2", 10)
.attr("y2", y(1))
.style("stroke", "black");

1 个答案:

答案 0 :(得分:1)

您的svg变量是HTML <div>元素:

<div id="myDiv"></div>
//"myDiv" is the ID of the div

var svg = d3.select(document.getElementById('myDiv'));
//you're getting the div here -----------------^

但是,您无法将SVG行附加到HTML div。

解决方案:选择svg本身:

var svg = d3.select("svg");

现在,您的svg变量指向SVG,您可以在其中附加SVG行。

以下是您更改的代码:

var trace1 = {
  x: [20],
  y: ['giraffes'],
  name: 'SF Zoo',
  orientation: 'h',
  marker: {
    color: 'rgba(55,128,191,0.6)',
    width: 1
 },
 type: 'bar'
};

var data = [trace1];

var layout = {
  title: 'Colored Bar Chart',
  barmode: 'stack'
};

Plotly.newPlot('myDiv', data, layout);

var y = d3.scale.linear().range([0, 400]);
var svg = d3.select("svg");
svg.append("line")
.attr("x1", 10)
.attr("y1", y(0))
.attr("x2", 10)
.attr("y2", y(1))
.style("stroke", "black");
<script src="https://d3js.org/d3.v3.min.js"></script>
  <script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<body>
  <div id="myDiv" style="width: 480px; height: 400px;"><!-- Plotly chart will be drawn inside this DIV --></div>

PS:D3代码中不需要getElementById。例如,要选择该div,只需执行d3.select("#myDiv")