我正在嘗試通過此功能實作折線圖。當我嘗試添加路徑時,路徑本身并沒有顯示出來。任何幫助,將不勝感激。(代碼的最后 10 行添加了圖形的路徑)
function drawLineChart(country) {
console.log(countryValueMap[country])
var margin = {top: 60, right: 110, bottom: 50, left: 50},
width = 800 - margin.left - margin.right 50,
height = 500 - margin.top - margin.bottom 50;
// document.getElementById("my_dataviz").innerHTML = "";
const lineSvg = d3.select("#linechart")
.attr("width", width margin.left margin.right)
.attr("height", height margin.top margin.bottom)
.append("g")
.attr("transform", `translate(${margin.left},${margin.top})`);
const x = d3.scaleTime()
.range([0 , width])
.domain([new Date(1958,0,1), new Date(2011,0,1)])
lineSvg.append("g")
.attr("transform", `translate(0, ${height})`)
.call(d3.axisBottom(x).ticks(5).tickFormat(d => d.getFullYear()))
const y = d3.scaleLinear()
.domain([0,countryMaxValueMap[country]])
.range([height, 0])
lineSvg.append("g")
.call(d3.axisRight(y).tickSize(width)).call(g => g.select(".domain")
.remove())
.call(g => g.selectAll(".tick:not(:first-of-type) line")
.attr("stroke-opacity", 0.5)
.attr("stroke-dasharray", "2,2"))
.call(g => g.selectAll(".tick text")
.attr("x", 4)
.attr("dy", -4));
lineSvg.append("path")
.datum(countryValueMap[country])
.attr("fill", "none")
.attr("stroke", "steelblue")
.attr("stroke-width", 1.5)
.attr("d", d3.line()
.x(function(d) { return x(d.year) })
.y(function(d) { return y(d.gdp) })
)
}
當我嘗試執行上面的代碼時,這是我得到的輸出。
我嘗試記錄 d3.year 和 d3.gdp 的值,變數作業正常。
uj5u.com熱心網友回復:
鑒于該線位于 1970 年(紀元時間的開始),看起來年份在資料中的表示方式有問題。由于您使用的是scaleTime
,d.year
必須是日期物件。它不能只是代表年份的整數。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/326013.html
標籤:javascript d3.js 数据可视化 折线图
上一篇:使用D3.js時,如何在熱圖頂部添加文本以正確顯示每個矩形的值?
下一篇:d3-將配色方案轉換為粉彩