简体   繁体   中英

how to start drawing a line with a space between y-axis and it using d3js

I'm drawing a simple line chart with axes.

// Set the scales
var x = d3.scale.ordinal()
    .domain(data.map(function(d) {
        return d.labels;}))
    .rangeRoundBands([0, width], 0);

var y = d3.scale.linear()
    .domain([0, d3.max(data, function(d) { return d.values; })])
    .range([height, 0]);

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

// draw line graph
var line = d3.svg.line()
    .x(function(d) { return x(d.labels); })
    .y(function(d) { return y(d.values); })
    .interpolate("linear");

// Create the SVG 'canvas'
var svg = d3.select("body").append("svg")
        .attr("class", "chart")
        .attr("width", width + margin.left + margin.right)
        .attr("height", height + margin.top + margin.bottom).append("g")
        .attr("transform", "translate(" + margin.left + "," + margin.right + ")");

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

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

svg.append("path")
  .attr("d",line(data))
  .attr("stroke", color)
  .attr("stroke-width", 2)
  .attr("fill", "none");

Here you can see that it works, but the line starts from the y-axis so that the values don't correspond to the labels: http://jsfiddle.net/5r63j/12/ It may be fixed by replacing the .rangeRoundBands([0, width], 0); by .rangePoints([0, width], 0); , so that the values correspond to the labels and it's quite good, but there is no padding between the y-axis and the line.

Is it possible to move the start point of the line itself?

Close but not quite! :)

Instead of:

.rangePoints([0, width], 0);

you just use

.rangePoints([0, width], 0.5);

And you will get this:

在此处输入图片说明

Here is jsfiddle .

Documentation for second parameter of rangePoints() is here . Illustration for parameter meaning:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM