I want to change the range of an x-axis in Plotly Python plot, in which the x-axis has to two indices. I want to restrict the range from [10,2] to [12,1], but fig.update_xaxes(range=[[10,2],[12,1]])
seems not to work.
That's what I tried:
import plotly.graph_objs as go
import pandas as pd
# create data
df = pd.DataFrame({'x1': [10,10,11,11,12,12], 'x2': [1,2,1,2,1,2], 'y': [1, 2, 3, 4, 5, 6]})
# create a scatter plot
fig = go.Figure()
fig.add_trace(go.Scatter(x=[df['x1'], df['x2']], y=df['y']))
fig.show()
Now, I manipulate the x-xaxis with fig.update_xaxes(range=[[10,2],[12,1]])
,
import plotly.graph_objs as go
import pandas as pd
df = pd.DataFrame({'x1': [10,10,11,11,12,12], 'x2': [1,2,1,2,1,2], 'y': [1, 2, 3, 4, 5, 6]})
fig = go.Figure()
fig.add_trace(go.Scatter(x=[df['x1'], df['x2']], y=df['y']))
# set the range of the double-index x-axis
fig.update_xaxes(range=[[10,2],[12,1]])
fig.show()
yet nothing changes:
Anybody has any ideas what I am doing wrong? Or does Plotly not allow what I want to do? Thanks so much!
I am not sure if plotly explicitly allows you to do what you want – I believe the multiindex is interpreted by plotly as numerical x-coordinates, and that the multiindex is displayed over it so plotly doesn't really "understand" the multiindex numbering system you have.
One possibility I can suggest is an ugly hack – you first need to pip install -U kaleido
and then can retrieve the default xaxis range that plotly is using with:
x_min, x_max = fig.full_figure_for_development().layout.xaxis.range
x_min
and x_max
turn out to be equal to -0.3213166144200627
and 5.321316614420063
, respectively. Then you can find the spacing between each tick with:
tick_spacing = (x_max - x_min) / 6
I've hardcoded division by 6, but you can make this solution less brittle by dividing by the number of unique multi-indices you have in your data.
And then add or subtract multiples of this tick_spacing
to x_min and x_max. For example:
fig.update_xaxes(range=[x_min + tick_spacing, x_max - tick_spacing])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.