[英]How to make a Scatter plot with D3 using a JSON file as input
我的目標是使用 D3 制作散布 plot,我無法弄清楚如何使用數據使用 svg 成功創建 plot。 數據為 JSON 格式:
data = {
time_to_read: {0: 1.31, 1: 2.565, 2: 4.6, 3: 3.05, 4: 2.605}
sentiment: {0: -0.003816794, 1: 0.0331384, 2: 0.011956521, 3: -0.021311475,4: 0.038387716}
scrollreach_label: {0: 3, 1: 2, 2: 2, 3: 1, 4: 1}
}
在構建軸之后,我嘗試了這樣的方法來添加點:
Svg.append('g')
.selectAll("dot")
.data(data)
.enter()
.append("circle")
.attr("cx", function (d) { return x(d3.values(d['avg_scroll_reach']) )} )
.attr("cy", function (d) { return y(d3.values(d['visits'])) } )
.attr("r", 5)
但這不起作用,圖表上沒有繪制任何內容。
我找到了一個解決方案,基本上是從一開始就以不同的方式格式化數據。 最初數據采用 pandas 格式,因為我使用的是 Python 后端。 因此,不要使用將 Pandas 數據轉換為 JSON
data_json = data.to_json()
我用了
data_json = data.to_json(orient='records')
這會以我需要的格式輸出數據:
Array(32) [
0: Object {time_to_read: , sentiment: 0.1, scrollreach_label: 3}
1: Object {time_to_read: , sentiment: 0.1, scrollreach_label: 2}
2: Object {time_to_read: "Datsun 710", sentiment: 0.2, scrollreach_label: 1}
3: Object {time_to_read: "Hornet 4 Drive", sentiment: 0.1, scrollreach_label: 3}
...
]
然后,我對 plot 使用以下代碼:
Svg.append('g')
.selectAll("dot")
.data(data)
.enter()
.append("circle")
.attr("cx", d => x(d.avg_scroll_reach))
.attr("cy", d => y(d.visits) )
.attr("r", 5)
.style("fill", d => color(d['scrollreach_label']))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.