简体   繁体   中英

d3 line graph - how to start line to the right of Y axis?

I have a line graph with dates representing the X-Axis. Rather than my line start on the Y-axis, I'd like to move it over to the right slightly so that it's a bit more readable. If possible, I'd also like to add a date to my list of X-Axis ticks. So basically, if I have an array of 5 dates such as:

{'March 19, 2018', 'April 24, 2018', 'May 19, 2018', 'June 4, 2018', 'July 6, 2018'}

I would want March 19, 2018 to NOT show up directly on the X-axis = 0. However, I'd still like to have a tick value on the X-axis = 0 such as the first date in my array minus one month. Does this make sense? Is this something that can easily be done with d3?

const circleLabelDrawDuration = 700;
const minDate = data[0].pullDate.setMonth(data[0].pullDate.getMonth() - 4);
const maxDate = data[data.length - 1].pullDate;

const xAxis = d3.scaleTime().domain([minDate, maxDate]).range([0, width]);

svg.append('g').call(d3.axisBottom(xAxis).ticks(pullDates.length).tickValues(pullDates).tickFormat(d3.timeFormat("%b %Y")))
.attr('transform', `translate(0,${height})`).selectAll('text')
.style('text-anchor', 'end').attr('dx', '-.8em').attr('dy', '-.15em').attr('transform', 'rotate(-50)');

I would do something like the following when setting your x-domain. I find offsets to be quite useful. Using some d3 functions to make it easier.

const monthInMs = 2.628e+9 // this is 1 month in ms
const xMin = +d3.min(dataArray, (d) => d.timestamp) - monthInMs;
const xMax = +d3.max(dataArray, (d) => d.timestamp) + monthInMs;
xScale.domain([xMin, xMax]);

I added the + in front of d3.min to ensure that the returned value is a number and not a date object. I gave both min and max so that you could have some padding on both sides, but you only really need to use the ones that you would like.

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