javascript - D3.JS - 折线图 - 响应式 - 找不到更新 Line 的 x 值的方法
问题描述
我正在尝试制作一个水平响应的 D3.JS 折线图 - 我的工作可以在这个CodePen中看到
我的问题是当图表的宽度发生变化时更新 Lines 数据点的 x 值的位置。x 轴的大小调整得很好。
在我的 Javascript 中,我有一个名为 resizeChart 的函数,当浏览器窗口的宽度发生变化时会调用它:
function resizeChart() {
currentWidth = parseInt(d3.select('#div_basicResize').style('width'), 10)
Svg.attr("width", currentWidth - 60)
x.range([20, currentWidth - 100]);
xAxis.call(d3.axisBottom(x));
var self = this;
Svg.selectAll("path")
.data(data)
.attr("x", function (d) {
return self.x(d.period);
});
}
问题在于 Svg.selectAll - 因为它似乎没有更新 Line 的 x 值。
解决方案
好吧,SVG 路径元素没有属性x
(只是一个d
属性,这是您使用上面的一些行来附加路径的属性)。
也就是说,只需命名您的选择...
var path = Svg.append("path")
//etc...
...并且,在更改 x 比例范围后,再次resizeChart
设置属性:d
path.attr("d", line);
以下是这些更改的代码:
var Svg = d3.select("#div_basicResize")
.append("svg")
.attr("height", 0)
var data = [{
"period": 2010,
"count": 166
},
{
"period": 2011,
"count": 192
},
{
"period": 2012,
"count": 158
},
{
"period": 2013,
"count": 183
},
{
"period": 2014,
"count": 174
},
{
"period": 2015,
"count": 197
},
{
"period": 2016,
"count": 201
},
{
"period": 2017,
"count": 195
},
{
"period": 2018,
"count": 203
},
{
"period": 2019,
"count": 209
},
{
"period": 2020,
"count": 208
}
]
var Svg = d3.select("#div_basicResize")
.append("svg")
.attr("height", 400);
var x = d3.scalePoint()
.domain(
data.map(function(d) {
return d.period;
})
)
.range([20, 20]);
var xAxis = Svg.append("g").attr(
"transform",
"translate(" + 20 + "," + 360 + ")"
);
var max =
d3.max(data, function(d) {
return +d.count;
}) + 10;
var min =
d3.min(data, function(d) {
return +d.count;
}) - 10;
var y = d3.scaleLinear()
.domain([min, max])
.range([360, 0]);
Svg.append("g")
.attr("transform", "translate(" + 40 + ",0)")
.call(d3.axisLeft(y));
var self = this;
var line = d3.line()
.x(function(d) {
return x(d.period) + 20;
})
.y(function(d) {
return y(+d.count);
});
var path = Svg.append("path")
.datum(data)
.attr("fill", "none")
.attr("stroke", "black")
.attr("stroke-width", 1)
.attr("d", line);
function resizeChart() {
currentWidth = parseInt(d3.select('#div_basicResize').style('width'), 10)
Svg.attr("width", currentWidth - 60)
x.range([20, currentWidth - 100]);
xAxis.call(d3.axisBottom(x));
//This is where I'm trying to update x value
path.attr("d", line);
}
resizeChart()
window.addEventListener('resize', resizeChart);
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.13.0/d3.min.js"></script>
<div id="div_basicResize"></div>
推荐阅读
- bash - 将构造命令添加到 bash 历史记录
- swift - 如何在 Swift 4 中从字符串格式化日期
- c# - EF Core 处理影子外键 DeleteBehaviour
- json - 使用变量查找值。JSON Alexa 技能
- xaml - 使用基本抽象类时,带有 ObservableCollection 的 UWP DependencyProperty 不会更新 UI
- google-tag-manager - 谷歌标签管理器无效或意外的令牌
- php - 在 laravel 表单请求验证中与 gte 一起使用时无法比较整数和浮点值
- python - 尚未实施为 fillna 指定限制
- flutter - Flutter 有编辑布局的实时预览吗?
- gnucash - GNUCash - 它可以根据某些帐户的先前条目/总数计算新交易的价值吗?