gpt4 book ai didi

javascript - d3.js 图表不考虑边距

转载 作者:行者123 更新时间:2023-11-30 23:59:45 26 4
gpt4 key购买 nike

所以我在这里定义边距:

  const svg1 = d3.select(graphElement1.current);
const margin = {top: 0, right: 30, bottom: 10, left: 10};
const width = 650 - margin.left - margin.right;
const height = 100 - margin.top - margin.bottom;

在此处绘制图表

    const data = timeseries;

const x = d3.scaleTime()
.domain(d3.extent(data, function(d) {
return new Date(d['date']+'2020');
}))
.range([0, width]);

const y = d3.scaleLinear()
.domain([0, d3.max(data, function(d) {
return +d['totalconfirmed'];
})])
.range([height, 0]);

svg1.append('g')
.attr('transform', 'translate(0,' + height + ')')
.attr('class', 'axis')
.call(d3.axisBottom(x));

svg1.append('path')
.datum(data)
.attr('fill', 'none')
.attr('stroke', '#ff073a99')
.attr('stroke-width', 5)
.attr('cursor', 'pointer')
.attr('d', d3.line()
.x(function(d) {
return x(new Date(d['date']+'2020'));
})
.y(function(d) {
return y(d['totalconfirmed'])-5;
})
.curve(d3.curveCardinal),
);

svg1.selectAll('.dot')
.data(data)
.enter()
.append('circle')
.attr('fill', '#ff073a')
.attr('stroke', '#ff073a')
.attr('r', 3)
.attr('cursor', 'pointer')
.attr('cx', function(d) {
return x(new Date(d['date']+'2020'));
})
.attr('cy', function(d) {
return y(d['totalconfirmed'])-5;
})
.on('mouseover', (d, i) => {
d3.select(d3.event.target).attr('r', '5');
setDatapoint(d);
setIndex(i);
})
.on('mouseout', (d) => {
d3.select(d3.event.target).attr('r', '3');
});

这是图表的 div 结构:

        <div className="svg-parent">
<div className="stats">
<h5>Confirmed {datapoint['date']}</h5>
<div className="stats-bottom">
...
</div>
</div>
<svg ref={graphElement1} width="650" height="100" viewBox="0 0 650 100" preserveAspectRatio="xMidYMid meet"/>
</div>

这是 CSS:

  .svg-parent {
display: flex;
flex: 0.9;
flex-direction: row;
justify-content: center;
width: 100%;
svg {
align-self: center;
}
}

我已经尝试了很多 CSS 规则来允许 svg 尊重边距定义,但我似乎无法使其工作。结果我也无法显示 x 轴。

这就是现在的样子,但是右边距是有效的,

[已编辑;即使设置左值后,图形也不会右移]

最佳答案

this tutorial 中所述:

These margins will be used to inset the ranges of our scales. Rather than extending from 0 to the full width and height of the chart, the starts and ends of the ranges are moved inward by the corresponding margins.

因此,对于 x 轴比例,请将 .range([0, width]) 替换为:

.range([margin.left, width])

类似地,对于 y 轴,请尝试以下范围定义:

.range([height, margin.top])

关于javascript - d3.js 图表不考虑边距,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60810870/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com