Steve.Gao
Steve.Gao

Reputation: 297

How to modify plotly axis start position?

I'm using

python3.7.6 plotly==4.9.0

trying to modify the x-range of a chart like

orginal picture

to fully use the space, like the following picture. X start from the first point without any margin modified

I can do this with

x=[1,2,3]
y=[1,2,3]

fig=px.line(x,y)
fig.update_layout(
    xaxis={
        'range':[0.99,3]
    })

But if I have a categorical axis,

import pandas as pd
import plotly.express as px
df=pd.DataFrame({
    'x':['xx','yy','zz'],
    'y':[1,2,3]})

fig=px.bar(df,x,y)

how can I set the range of axis?

Thanks

Upvotes: 0

Views: 3435

Answers (1)

jayveesea
jayveesea

Reputation: 3199

For categorical axes the range works the same as numerical, in this case the category is converted to an integer, see here and below (emphasis added).

Sets the range of this axis. If the axis type is "log", then you must take the log of your desired range (e.g. to set the range from 1 to 100, set the range from 0 to 2). If the axis type is "date", it should be date strings, like date data, though Date objects and unix milliseconds will be accepted and converted to strings. If the axis type is "category", it should be numbers, using the scale where each category is assigned a serial number from zero in the order it appears.

For your example try:

import pandas as pd
import plotly.express as px

df=pd.DataFrame({
    'x':['xx','yy','zz'],
    'y':[1,2,3]})

fig=px.bar(df,x='x',y='y')

fig.update_layout(
    xaxis={
        'range':[-.4,2.4]
    })

fig.show()

enter image description here

Upvotes: 1

Related Questions