D3 的直方图,条形图不适合 svg 的高度
Histogram with D3 , bars are not fitting hight of svg
我正在根据数据(动态变化)绘制直方图,但一些条的高度不适合 svg 区域(超出 svg 区域)
这是一段我有疑问的代码:
private drawBars(data: any[]): void {
let f = Math.min.apply(Math, this.fixedData.map(function (o) {
return o.xAxis;
}));
/** Create the X-axis band scale */
const x = d3.scaleBand()
.range([f, 240])
.domain(data.map(d => d.xAxis))
.padding(0);
/** Create the Y-axis band scale */
const y = d3.scaleLinear()
.domain([0, this.axisMax])
.range([this.height, 0])
.nice();
/** Create and fill the bars */
this.svg.selectAll("*").remove()
this.svg.selectAll("bars")
.data(data, d => d)
.enter()
.append("rect")
.attr("x", d => x(d.xAxis))
.attr("y", d => y(d.yAxis))
.attr("width", x.bandwidth())
.attr("height", (d) => this.height - y(d.yAxis))
.attr("fill", (d) => this.colorPicker(d))
}
这是这种奇怪行为的证明:
任何想法,我将不胜感激!
您的问题是由于 this.axisMax
设置得太低造成的,这里:
const y = d3.scaleLinear()
.domain([0, this.axisMax])
.range([this.height, 0])
.nice();
您需要根据现有数据重新计算。
比例尺的域包含它接受的可能值的范围,但是,至少对于 scaleLinear
、scaleTime
和其他一些值,超出该范围不会引发错误甚至 return NaN
。对于这些类型的尺度,域用于识别输入值和输出像素之间的线性变换。
例如
假设您有一个范围为 [0, 10] 和范围 [0, 100] 的线性比例尺。然后,x = 0
给出像素值0
,x = 10
给出100
。但是,x = 20
给出的像素值200
,超出了给定的范围。
我正在根据数据(动态变化)绘制直方图,但一些条的高度不适合 svg 区域(超出 svg 区域) 这是一段我有疑问的代码:
private drawBars(data: any[]): void {
let f = Math.min.apply(Math, this.fixedData.map(function (o) {
return o.xAxis;
}));
/** Create the X-axis band scale */
const x = d3.scaleBand()
.range([f, 240])
.domain(data.map(d => d.xAxis))
.padding(0);
/** Create the Y-axis band scale */
const y = d3.scaleLinear()
.domain([0, this.axisMax])
.range([this.height, 0])
.nice();
/** Create and fill the bars */
this.svg.selectAll("*").remove()
this.svg.selectAll("bars")
.data(data, d => d)
.enter()
.append("rect")
.attr("x", d => x(d.xAxis))
.attr("y", d => y(d.yAxis))
.attr("width", x.bandwidth())
.attr("height", (d) => this.height - y(d.yAxis))
.attr("fill", (d) => this.colorPicker(d))
}
这是这种奇怪行为的证明:
任何想法,我将不胜感激!
您的问题是由于 this.axisMax
设置得太低造成的,这里:
const y = d3.scaleLinear()
.domain([0, this.axisMax])
.range([this.height, 0])
.nice();
您需要根据现有数据重新计算。
比例尺的域包含它接受的可能值的范围,但是,至少对于 scaleLinear
、scaleTime
和其他一些值,超出该范围不会引发错误甚至 return NaN
。对于这些类型的尺度,域用于识别输入值和输出像素之间的线性变换。
例如
假设您有一个范围为 [0, 10] 和范围 [0, 100] 的线性比例尺。然后,x = 0
给出像素值0
,x = 10
给出100
。但是,x = 20
给出的像素值200
,超出了给定的范围。