D3:如何在数据的最小/最大值和轴的最小/最大值之间增加边距? [英] D3: How to add a margin between min/max from data and min/max from axis?

查看:100
本文介绍了D3:如何在数据的最小/最大值和轴的最小/最大值之间增加边距?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在最小/最大值和我的最小/最大轴值之间添加一些空间?

这是一个小提琴 https://jsfiddle.net/ftgbhyqj/21/./p>

如您所见,最小值和最大值始终用于y轴上的最小值/最大值.如何在数据的最大值与y轴的最大值之间添加一些额外的空间(例如可用高度的5%)?

请参见以下屏幕截图.在数据的最大值和最大可用图表区域之间有一些额外的空间.

我不是在谈论margin.topmargin.bottom,因为这也会使轴变小.

解决方案

我认为最好直接操作比例域,而不要单独依赖d3.extent()函数:https://jsfiddle.net/ftgbhyqj/21/.

As you can see the min and max values are always used for the min/max on the y axis. How can I add some extra space, like 5% of the available height, between my max value from the data and the max value on the y axis?

See the following screenshot. Between the maximum from the data and the maximum available chart area is some extra space.

I'm not talking about margin.top or margin.bottom since this would also make the axis smaller.

解决方案

I think it's best to manipulate the scale domains directly rather than rely on the d3.extent() function alone: https://jsfiddle.net/wmLd3r8z/. You can probably do something cleaner on the x axis with the time series data, but hopefully this gives you what you need.

const x_extent = d3.extent(data, d => d.ts);

const x = d3.scaleTime()
    .domain([x_extent[0] -1000, x_extent[1] + 1000])
    .range([0, w]);

const y_extent = d3.extent(data, d => d.value);
const y_extent_diff = 0.05 * Math.abs(y_extent[1] - y_extent[0]);

const y = d3.scaleLinear()
    .domain([y_extent[0] - y_extent_diff, y_extent[1] + y_extent_diff])
    .range([h, 0])

这篇关于D3:如何在数据的最小/最大值和轴的最小/最大值之间增加边距?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆