Hi @xus72 ,
I think you can get your plot visible range both x and y axis by using min
and max
function.
For example you have a data frame as df
that have column x
and y
to make a scatter plot.
To get range of y you can use df["y"].min()
for min range , and use df["x"].max()
for max range.
For x axis range you can use df["x"].min()
and df["y"].max()
.
After that you can set range using fig.update_yaxes
and fig.update_xaxes
.
Let’s say, I create Green Shape and some Tiny Red Scatter plot before set range manually will be displayed below.
After I set The Range Manually based on visible range of the Tiny Red Scatter plot.
The code below is implementation after set y and x range manually.
import plotly.graph_objects as go
import pandas as pd
df = pd.DataFrame(dict(
x = [2.1,2.15,2.2,2.25,2.3,2.35,2.4,2.45,2.5,2.55],
y = [2.1,2.120,2.11,2.105,2.10,2.095,2.0899,2.08,2.105,2.07]
))
fig = go.Figure()
fig.add_trace(go.Scatter(
x=df["x"],
y=df["y"],
line=dict(color="red")
))
# Add shapes
fig.add_shape(type="rect",
x0=1, y0=1.5, x1=4, y1=2.5,
line=dict(
color="Green",
width=4,
),
fillcolor="SeaGreen",
layer="below"
)
# calculate min and max y
y_padding = (df["y"].max()-df["y"].min())/len(df["y"])
min_y = df["y"].min() - y_padding
max_y = df["y"].max() + y_padding
# calculate min and max x
x_padding = (df["x"].max()-df["x"].min())/len(df["x"])
min_x = df["x"].min()-x_padding
max_x = df["x"].max()+x_padding
# Set y and x range manually
## You can comment this line to see result before set y range
fig.update_yaxes(range=[min_y,max_y])
## You can comment this line to see result before set x range
fig.update_xaxes(range=[min_x, max_x])
fig.show()
Hope this help.