在散点图中扩展x和y轴长度,d3js

时间:2016-05-02 18:50:33

标签: d3.js

我正在尝试延长x和y轴长度并在末尾添加箭头。这是我的代码和plunker。我需要x轴延伸超过4.6和y轴超过" AS"并在末尾添加一个箭头。请帮助。 https://plnkr.co/edit/tA6oyKQCCmhNadbARR89?p=preview

var margin = {top: 20, right: 20, bottom: 20, left: 40},
width = 420 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;

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

var y = d3.scale.ordinal().rangePoints([height, 0])

var color = d3.scale.category10();

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

var yAxis = d3.svg.axis()
.scale(y).tickSize(-width).outerTickSize(0)
.orient("left");

var svg = d3.select("body").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;

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

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

svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + (height) + ")")
.call(xAxis);

svg.append("g")
.attr("class", "y axis")
.call(yAxis);

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("text")
.attr("x", width - 24)
.attr("y", 9)
.attr("dy", ".35em")
.style("text-anchor", "end")
.text(function(d) { return d; });
});

1 个答案:

答案 0 :(得分:3)

最简单的方法是直接指向轴末端的自定义路径:

svg.append("g")
  .attr("class", "x axis")
  .attr("transform", "translate(0," + (height) + ")")
  .call(xAxis)
  .append("path")
  // add extension arrow
  .attr("d", "M" + width + ",0L" + (width + 20) + ",0L" + (width + 20) + ",-5L" + (width + 30) + ",0L"  + (width + 20) + ",5L" + (width + 20) + ",0L");

svg.append("g")
  .attr("class", "y axis")
  .call(yAxis)
  .append("path")
  // add extension arrow
  .attr("d", "M0,0L0,-20L-5,-20L0,-30L5,-20,L0,-20Z");

更新了plunker