add axhline to plotly 3d expressp lot in python

To add a horizontal line (axhline) to a Plotly 3D express plot in Python, you can use the scatter.

First, create a 3D scatter plot using express:

main.py
import plotly.express as px
df = px.data.iris()
fig = px.scatter_3d(df, x='sepal_length', y='sepal_width', z='petal_width',
                    color='species')
161 chars
5 lines

Then, to add axhline, you can create a new trace with the desired y-value:

main.py
import numpy as np
y_value = np.mean(df['sepal_width']) # or any other desired value
fig.add_trace(px.scatter_3d(df, x=[df['sepal_length'].min(), df['sepal_length'].max()], 
                            y=[y_value, y_value],
                            z=[df['petal_width'].min(), df['petal_width'].max()], 
                            mode='lines').data[0])
358 chars
7 lines

In the code above, we created a new trace with the desired y-value, using minimal and maximal sepal_length and petal_width. Here we assumed that the data is sorted and continuous.

Now the figure fig includes the desired axhline trace.

Finally, we can use fig.show() to show the plot.

main.py
fig.show()
11 chars
2 lines

gistlibby LogSnag