0

I need to plot data using chart.js but the data keeps on changing from the original data from python. At this point, I don't know what to do because my charts don't look anything alike between python and chart.js.

Quick context: I have a python script that's generating data that I want to plot using chart.js on a site. For this, I use Django to pass the data as context to an HTML template where I plot it using chart.js. However, I noticed a significant difference between plots displayed by python and javascript. I took a quick look at the data itself and noticed that it changed.

So I pass the data like that :

var X = {{ X }}
var F = {{ F }}
console.log(F)
var F_ridge = {{ F_ridge }}
var F_lasso = {{ F_lasso }}
var F_elastic = {{ F_elastic }}

Here's the output for the first item of my python array :

>>> 1.00024861720107

and here's the output of the first item of my javascript array :

1.0002486171243539

I know that it is a very little difference but it is enough to cause discrepancies in the plots. Do you know what causes the change and how to prevent it from happening?

1 Answers1

0

It looks like your javascript uses more decimals to represent a float. As you may know, not every floating point number can be represented using a binary structure, therefore the last x amount of digits are less precise than the first digits. If those digits matter that much for your plot, you might want to try to multiply your result by a large number (something like 10^12) and work with integers or with only a few decimals. You can always divide them again in your javascript later, but you may end up with the same problems then.

Another option is to use pyplot for plotting your data (since you are using django anyway) and use the resulting image in your webpage. You don't actually need to generate the graph with javascript.

Danagon
  • 395
  • 5
  • 15