簡體   English   中英

如何使用 JSON 文件作為輸入使用 D3 制作 Scatter plot

[英]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)

但這不起作用,圖表上沒有繪制任何內容。

我需要創建的 plot 應該大致如下(在這種情況下使用更多數據): 在此處輸入圖像描述

我找到了一個解決方案,基本上是從一開始就以不同的方式格式化數據。 最初數據采用 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM