1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

[Python] Gaps and inconsistent ordering in plotly express bar chart

Discussão em 'Python' iniciado por Stack, Outubro 7, 2024.

  1. Stack

    Stack Membro Participativo

    I have a dataframe that consists of 3 columns, Date, Name, Number. With 5 dates (may change depending on time data extract is run) and 10 names per date. The same name can appear in multiple dates, or may only appear in one date. Numbers can be positive or negative. The data is ordered by Date (ascending=True) and then by Number (ascending=False).

    I am trying to plot a chart using plotly express, that has number on Y axis and Date on Axis, with bars coloured by reporter. Bars should be ordered from largest to smallest number per date.

    When using this code the ordering is correct for the first date, but after that there are gaps between some bars and the ordering is wrong, for example positive bars being plotted after negative ones.

    fig = px.bar(df, x="Date", y="Number", color="Name", barmode="group")


    I have tried using fig.update_layout(yaxis={'categoryorder': 'total ascending'}) but this doesn't seem to do anythng.

    Please can someone help me format this chart so that there are no gaps and the ordering is correct for all dates.

    On further investigation it appears the ordering is set on the first value of the x axis (eg. Day1) and is then kept the same. So if a name is in Day1, but not in Day2, then there will be an empty space in Day2. If a name doesn't appear in Day1, but is in Day2, then that bar will appear and the end, even if it represents a larger Number than the previous bar.

    Essentially I need to force Plotly Express to order the bars for each X value independently of eachother.

    Continue reading...

Compartilhe esta Página