在d3中添加刻度线

时间:2017-07-26 20:06:05

标签: javascript d3.js

我是d3.js的新手有一个水平div,我也想添加刻度线。使用一个例子,我能够在垂直线上创建刻度线,但是当我尝试将其附加到#barvar svg = d3.select("#bar")刻度线消失。如何在div附加刻度线?

var svg = d3.select("svg"),
    margin = {top: 20, right: 0, bottom: 20, left: 0},
    width = svg.attr("width") - margin.left - margin.right,
    height = svg.attr("height") - margin.top - margin.bottom,
    g = svg.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")");

var x = d3.scalePoint()
    .domain([0, 1, 2])
    .range([0, width])
    .padding(1);

var y = d3.scaleLinear()
    .domain([0, 1000])
    .range([250, 0]);

g.append("g")
    .attr("transform", "translate(" + x(0) + ",0)")
    .attr("class", "axis")
    .call(d3.axisLeft(y)
        .ticks(6, ));
  #bar {
  width: 250px;
  height: 20px;
  top: 20px;
  border: 0 px solid black;
  background: rgba(12, 12, 12, 0.8);
  color: #eee;
  font-family: 'Open Sans', sans-serif;
}
<script src="//d3js.org/d3.v4.min.js"></script>
<svg width="960" height="500"></svg>
<div id = 'bar'></div>

1 个答案:

答案 0 :(得分:0)

@GerardoFurtado是正确的,你只能将它们添加到svg。您可以采用已应用于y轴的内容并将其修改为x轴。

您可以为路径指定一个类,然后使用svg style attributes

对其进行样式设置

&#13;
&#13;
var svg = d3.select("svg"),
    margin = {top: 20, right: 0, bottom: 20, left: 0},
    width = svg.attr("width") - margin.left - margin.right,
    height = svg.attr("height") - margin.top - margin.bottom,
    g = svg.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")");

var x = d3.scalePoint()
    .domain([0, 1, 2])
    .range([0, width])
    .padding(1);

var y = d3.scaleLinear()
    .domain([0, 1000])
    .range([250, 0]);

g.append("g")
    .attr("transform", "translate(" + x(0) + ",0)")
    .attr("class", "axis")
    .call(d3.axisLeft(y)
        .ticks(6, ));
        
g.append("g")
    .attr("transform", "translate(" + x(0) + ",250)")
    .attr("class", "bar")
    .call(d3.axisBottom(x)
        .ticks(6, ));
&#13;
.bar path{
  fill: rgba(12, 12, 12, 0.8);;
  stroke: #eee;
  stroke-width: 1;
}

.bar .tick text{
  fill: darkgrey;
}

.bar .tick line{
  opacity: 0;
}
&#13;
<script src="//d3js.org/d3.v4.min.js"></script>
<svg width="960" height="500"></svg>
&#13;
&#13;
&#13;