Black Lives Matter. Please consider donating to Black Girls Code today.

Plotly.js scatter plot not displaying

Hi,

I am trying to plot an extremely simple scatter plot using Plotly.js, loading from a CSV:

https://jsfiddle.net/sw6Lw7zk/

The axes generate, but nothing is visible. Why is this? I have used document.writeln(JSON.stringify(data)); to check that the data variable is formatted correctly, and it seems to be… so I don’t understand why nothing is displaying!

Any ideas?

Something must not be formatted correctly.

Unfortunately, I can’t run your jsFiddle. Looks like the URL where you’re fetching your data isn’t valid anymore, so I can’t help any further.

Hmm… I just checked the link and it worked for me (screenshot). Here’s the direct link to the file:

https://www.dropbox.com/scl/fi/ginn90potjmn1131qp9qx/test.csv?raw=1

It’s just a 4x4 anyway—here’s the content:

account_name,ap_score,l_score,colour
a,10,70,#f79c82
b,60,20,#f79c82
c,80,80,#007ee5
d,5,5,#e5e6eb

Ok well something is up with your unpack routine.

Something like:

function unpack(rows, key) {
  var index = rows[0].indexOf(key)
  return rows.slice(1).map(function(row) { return row[index] })
}

should make it work.

The unpack routine comes from this Plotly demo—did I do something wrong?

This is what the data variable comes out as if I use JSON.stringify to write it:

[{“type”:“scatter”,“x”:10,“y”:70,“color”:"#f79c82",“name”:“a”,“text”:“a”,“mode”:“markers+text”},{“type”:“scatter”,“x”:60,“y”:20,“color”:"#f79c82",“name”:“b”,“text”:“b”,“mode”:“markers+text”},{“type”:“scatter”,“x”:80,“y”:80,“color”:"#007ee5",“name”:“c”,“text”:“c”,“mode”:“markers+text”},{“type”:“scatter”,“x”:5,“y”:5,“color”:"#e5e6eb",“name”:“d”,“text”:“d”,“mode”:“markers+text”}]

Does that look right? If not, what’s wrong? If it is right, any idea why it doesn’t visualise?

That unpack routine only works for a certain type of data input i.e. it won’t work for all csv files. You’ll have to adapt it to your needs.

Plotly expects data like:

Plotly.plot('graph', [{
  type: 'scatter',
  x: [1,2,3],
  y: [2,1,2]
}])

when the x and y keys are not linked to arrays, plotly won’t draw anything - as in your case. For more example, please look at https://plot.ly/javascript/line-charts/

1 Like

Ahh… I hadn’t realised x and y had to be arrays even if they were single digits! It works perfectly now.

Thank you so much for your help and patience—I hope you are having a great weekend! :slight_smile: