extend x and y axis length in scatterplot, d3js

北战南征 提交于 2021-02-05 07:09:35

问题


I am trying to extend the x and y axis length and add the arrow at the end. Here is my code and plunker. I need x axis to extend beyond 4.6 and y-axis beyond "AS" and add an arrow at the end. Kindly help. 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:


Easiest way is to just tack on a custom path to the end of the axis:

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");

Updated plunker.



来源:https://stackoverflow.com/questions/36989524/extend-x-and-y-axis-length-in-scatterplot-d3js

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!