How to add a line to a figure? I tried figure.add_, but I do not know what to use for a line. When I reversed the order and used figure.add_scatter, I obtained an error:
The 'cliponaxis' property must be specified as a bool (either True, or False)
import plotly.express as px
import numpy as np
import pandas as pd
from plotly.graph_objs import *
import plotly.graph_objects as go
data_n = np.loadtxt('f.dat', unpack=True, usecols=[0, 2, 5, 7])
data = data_n.tolist()
d = {'A': data[0], 'B': data[1]}
fig = px.scatter(df, x='A', y='B')
x_new = ...
y_new = ...
d_fit = {'x': x_new, 'y': y_new}
df_fit = pd.DataFrame(data=d_fit)
fig = px.line(df_fit, x='x', y='y') # to add
fig.show()
When you call px.scatter
or px.line
, you pass the DataFrame, and the names of the columns to the parameters x
and y
. When you call go.Scatter
you have to pass column slice sof the DataFrame directly to the x
and y
parameters. The add_scatter
function is a convenience method that performs the same function as adding a graph_object, NOT a plotly express
object. Therefore, you have to pass the same parameters to add_scatter
as you would to go.Scatter
.
For example, using two sample DataFrames, the following code works:
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
## sample DataFrames
df1=pd.DataFrame({'A':[1,2,3],'B':[4,5,6]})
df2=pd.DataFrame({'x':[1,2,3],'y':[7,8,9]})
fig = px.scatter(df1, x='A', y='B')
fig.add_scatter(x=df2['x'], y=df2['y'])
fig.show()
But if I replace fig.add_scatter(x=df2['x'], y=df2['y'])
with fig.add_scatter(df2, x='x', y='y')
, I will get an error:
ValueError:
Invalid value of type 'pandas.core.frame.DataFrame' received for the 'cliponaxis' property of scatter
Received value: x y
0 1 7
1 2 8
2 3 9
The 'cliponaxis' property must be specified as a bool
(either True, or False)
By the way, I would recommend not using the import statement from plotly.graph_objs import *
as this imports all of the functions and classes from plotly including ones you don't need.