How to obtain generated x-axis and y-axis range in plotly plot?
If you have no access to the input data, but to the trace:
x_min = min(trace.x)
x_max = max(trace.x)
If you have no access to the trace but to the figure handle the following should work (I assume this is the usual case):
x_mins = []
x_maxs = []
for trace_data in fig.data:
x_mins.append(min(trace_data.x))
x_maxs.append(max(trace_data.x))
x_min = min(x_mins)
x_max = max(x_maxs)
I assume fig.layout.xaxis.range
is None
if the axis range is automatic.
Getting the axis range from a plotly plot is not possible within the python implementation. You can only retrieve the range if you specify the axis range in your layout (but then you really don't need it).
So if you try print(fig.layout.xaxis.range)
you will get None
.
If you need the limits then you'll need to make your own and apply it to the layout:
- get the min and max of the x-values:
xmin
,xmax
- pad these values with some factor:
xlim = [xmin*.95, xmax*1.05]
- update the layout:
fig.update_layout(xaxis=dict(range=[xlim[0],xlim[1]]))
Now if you try print(fig.layout.xaxis.range)
you'll get the axis range.
This was bugging me a great deal so I had to dig deeper, credit goes to @Emmanuelle on the plotly forums for confirming this reality.
UPDATE 20210129: Plotly has added .full_figure_for_development() method.
The .full_figure_for_development() method provides Python-level access to the default values computed by Plotly.js. This method requires the Kaleido package, which is easy to install and also used for static image export.
So now you can:
full_fig = fig.full_figure_for_development()
print(full_fig.layout.xaxis.range)