Plotly/D3 – Reading data from CSV into separate traces

Viewed 2470

I am attempting to utilize Plotly (based on D3) to read through a CSV and return data into three separate traces - one for each year, in this case.

This Pen depicts the intended result with the data hardcoded into the JS: ‘sales’ data (y-axis), by car dealership (x-axis) and year (essentially a “grouping” variable).

Intended Output

I have researched examples of D3 reading CSV data but am unclear how to read my data into the separate traces by year.

For what it’s worth, here is the sample data.

If anyone can point me in the right direction I would appreciate it! Thank you!

(I apologize if this is an ‘easy’ question as I am new to JavaScript and have very little Plotly or D3 experience.)

1 Answers

@etienne was able to point me in the right direction with this Pen (https://codepen.io/etpinard/pen/VrzwyP)

JS:

var years = ['2014', '2015', '2016']

Plotly.d3.csv('https://raw.githubusercontent.com/apodagrosi/datasets/master/PlotlyTest_Summary_SalesByDealerByYear.csv', (err, rows) => {
  var data = years.map(y => {
    var d = rows.filter(r => r.year === y)

    return {
      type: 'bar',
      name: y,
      x: d.map(r => r.dealer),
      y: d.map(r => r.sales)
    }
  })

  Plotly.newPlot('graph', data)
})

HTML:

<head>
  <script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
</head>
<body>
  <div id="graph"></div>
</body>

I also utilized 'category order' to order the x-axis values that did not have sales (y-axis) values.

Related