Search code examples
pythonplotlyplotly-python

Plotly ticks are weirdly aligned


Let's take the following pd.DataFrame as an example

df = pd.DataFrame({
    'month': ['2022-01', '2022-02', '2022-03'],
    'col1': [1_000, 1_500, 2_000],
    'col2': [100, 150, 200],
}).melt(id_vars=['month'], var_name='col_name')

which creates

    month   col_name    value
-----------------------------
0   2022-01 col1        1000
1   2022-02 col1        1500
2   2022-03 col1        2000
3   2022-01 col2        100
4   2022-02 col2        150
5   2022-03 col2        200

Now when I would use simple seaborn

sns.barplot(data=df, x='month', y='value', hue='col_name');

I would get:

enter image description here

Now I would like to use plotly and the following code

import plotly.express as px
fig = px.histogram(df, 
                   x="month", 
                   y="value",
                   color='col_name', barmode='group', height=500, width=1_200)
fig.show()

And I get:

enter image description here

So why are the x-ticks so weird and not simply 2022-01, 2022-02 and 2022-03?

What is happening here?

I found that I always have this problem with the ticks when using color. It somehow messes the ticks up.


Solution

  • You can solve it by customizing the step as 1 month per tick with dtick="M1", as follows:

    import pandas as pd
    import plotly.express as px
    
    df = pd.DataFrame({
        'month': ['2022-01', '2022-02', '2022-03'],
        'col1': [1000, 1500, 2000],
        'col2': [100, 150, 200],
    }).melt(id_vars=['month'], var_name='col_name')
    
    
    fig = px.bar(df, 
                       x="month", 
                       y="value",
                       color='col_name', barmode='group', height=500, width=1200)
    
    
    fig.update_xaxes(
                    tickformat = '%Y-%m',   
                    dtick="M1",
            )
    
    fig.show()
    

    enter image description here