Search code examples
pythonpandasnumpyplotly-pythonscipy-optimize

Invalid value of type 'numpy.float64' received for the 'y' property of scatter


I am having the subject error when I try to use add_trace function from plotly. I have 2 independent variables (x1 and x2) and a dependent variable(y). I used curve_fit for data fitting and want to add a trace line to the graph. Be noted this is a random dataset so the result doesn't make sense at all.

Below is the code and the error. Any advice or suggestion would be greatly appreciated

import pandas as pd
import numpy as np
import plotly.graph_objects as go  
from scipy.optimize import curve_fit

np.random.seed(0)
x1 = np.random.randint(0, 100, 100)
x2 = np.random.randint(0, 100, 100)
y = np.random.randint(0, 100, 100)

def func(x, a, b, c, d, e, f, g):
    return (a * x[0]**3 + b * x[0]**2 + c * x[0]) + (d * x[1]**3 + e * x[1]**2 + f * x[1]) + g

def inv(x1, x2, y):
    (a, b, c, d, e, f, g), _ = curve_fit(func, np.stack([x1, x2]), y)

    # create graph
    x3 = [sum(i) for i in zip(x1, x2 )]  
    x = np.linspace(min(x3), max(y), 1000)

    fig = go.Figure(go.Scatter(x=x3, y=y, name='data'))
    fig.add_trace(go.Scatter(x=x, y=func(x, a, b, c, d, e, f, g), name='fit'))
    fig.show()
    
    return  (a, b, c, d, e, f, g)

inv(x1, x2, y)

ValueError: 
Invalid value of type 'numpy.float64' received for the 'y' property of scatter
    Received value: 49.464592654826

The 'y' property is an array that may be specified as a tuple,
list, numpy array, or pandas Series

Solution

  • The problem in you pass a single value as parameter y to plotly.
    This is not supported anymore since version 3 see migration-guide-plotly.

    So in your case the simple fix would be to replace fig.add_trace(go.Scatter(x=x, y=func(x, a, b, c, d, e, f, g), name='fit')) with fig.add_trace(go.Scatter(x=x, y=[func(x, a, b, c, d, e, f, g)], name='fit')).

    I had a very similar problem lately where the predictions of my models could either be a list or a number. For this I used np.array(current_predictions) as parameter for y.

    I know this won't help you anymore but maybe someone else stumbles upon it :)