[英]Updating D3 Axis Labels
我有三個單選按鈕,用於更改 d3 折線圖的 x 軸上的值。 我已經成功地改變了比例,但不是 x 軸標簽。 我到處看我只看到刻度標簽的信息,而不是軸標簽(在 gif“分鍾”中)。
我已經成功地更新並因此重新縮放軸,如下面的代碼,但是無法弄清楚如何更改標簽。
function updateGraph(graphData, timeScale){
yDomain = d3.extent(graphData, function(d){return Number(d.amt)});
switch(timeScale) {
case 'min':
xDomain = d3.extent(graphData, function(d){return Number(d.min)});
break;
case 'hour':
xDomain = d3.extent(graphData, function(d){return Number(d.hour)});
break;
case 'day':
xDomain = d3.extent(graphData, function(d){return Number(d.day)});
break;
default: break;
}
//Make the scale for the graphs dynamic
yScale.domain(yDomain);
xScale.domain(xDomain);
vis = d3.select('#visualisation').transition();
//add axes with proper scale, orientation, and position
var line = d3.svg.line()
.x(function(d){
switch(timeScale) {
case 'min':
return xScale(d.min);
break;
case 'hour':
return xScale(d.hour);
break;
case 'day':
return xScale(d.day);
break;
default: break;
}
})
.y(function(d){
return yScale(d.amt);
})
.interpolate('basis');
var xAxisLabel = function(){
switch(timeScale) {
case 'min':
return 'Minute';
break;
case 'hour':
return 'Hours';
break;
case 'day':
return 'Day';
break;
default: break;
}
}
vis.select('.line')
.duration(750)
.attr('d', line(graphData))
vis.select('.xaxis')
.duration(750)
.call(xAxis);
vis.select('.yaxis')
.duration(750)
.call(yAxis);
//Tried to hardcode with 'sugar' to no avail, would eventually like to use xAxisLabel declared above.
vis.select('.text')
.duration(750)
.text('sugar');
}
我在第一次使用以下代碼制作圖表時設置了文本:
vis.append('text')
.attr('text-anchor', 'middle') // this makes it easy to centre the text as the transform is applied to the anchor
.attr('transform', 'translate('+ (WIDTH/2) +','+(HEIGHT+(MARGINS.bottom/3))+')') // centre below axis
.text(xAxisLabel);
試試這個:首先,為你的文本創建一個變量。
var textLabel = vis.append("text")
.attr('text-anchor', 'middle') // this makes it easy to centre the text as the transform is applied to the anchor
.attr('transform', 'translate('+ (WIDTH/2) +','+(HEIGHT+(MARGINS.bottom/3))+')') // centre below axis
.text(xAxisLabel);
然后,更新后:
textLabel.duration(750).text(xAxisLabel)
或者,如果上述解決方案不起作用(因為vis
是一個transition()
選擇),您可以簡單地嘗試這個,因為您正在選擇一個 DOM 元素:
vis.select('.text')[0][0]
.duration(750)
.textContent = (xAxisLabel);
如果您仍然收到“不是函數”錯誤,請更改用於附加 svg 的原始變量的vis
。
編輯:不要忘記將類“文本”設置為文本。
正如 Gerardo 在評論中所建議的,在創建時給標簽類“文本”是缺失的鏈接。
var xAxisLabel = vis.append('text').attr("class", "text")//the rest of the code
然后我可以在我的更新功能中更改它,如下所示:
vis.select('.text')
.duration(750)
.text(xAxisLabel);
謝謝傑拉爾多!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.