简体   繁体   English

d3折线图 - 如何从Y轴右侧开始直线?

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

I have a line graph with dates representing the X-Axis. 我有一个日线代表X轴的折线图。 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. 而不是我的线从Y轴开始,我想稍微向右移动它,以便它更具可读性。 If possible, I'd also like to add a date to my list of X-Axis ticks. 如果可能的话,我还想在我的X轴刻度列表中添加一个日期。 So basically, if I have an array of 5 dates such as: 所以基本上,如果我有一个包含5个日期的数组,例如:

{'March 19, 2018', 'April 24, 2018', 'May 19, 2018', 'June 4, 2018', 'July 6, 2018'} {'2018年3月19日','2018年4月24日','2018年5月19日','2018年6月4日','2018年7月6日'}

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. 我希望2018年3月19日不会直接显示在X轴上= 0.但是,我仍然希望在X轴上有一个刻度值= 0,例如我的数组中的第一个日期减去一个月。 Does this make sense? 这有意义吗? Is this something that can easily be done with d3? 这是否可以用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. 在设置x域时,我会执行以下操作。 I find offsets to be quite useful. 我发现偏移非常有用。 Using some d3 functions to make it easier. 使用一些d3函数使其更容易。

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. 我在d3.min前添加了+以确保返回的值是数字而不是日期对象。 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. 我给了最小值和最大值,这样你可以在两边都有一些填充,但你只需要使用你想要的那些。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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