Search code examples
pythonplotlylinechartplotly-pythonplotly-express

plot line chart, regardless the order of x axis python


i have a dataframe with two columns. MachineID and Value. I sort the dataframe to descending order(machines with high values first) and plot the line chart. But still, it shows the x axis(MachineID 1 to 60, rather than taking the highest values MachineID first.)

To solve this error, changed the machineID column to string but still couldn't get the machines with High values first.

Sample dataframe:

MachineID   Value
    33     6.962754
    16     6.955913
    44     6.722355
    31     6.320854
    1      6.243701
    9      5.894093

Mycode:

import plotly.express as px
fig = px.line(data, x="MachineID", y="Values")
fig.show()

Output for above code:

enter image description here

Required Output:

Machines with high values first and so on.


Solution

  • If you want to use a line plot and show the machine with the highest value first, you have to:

    • sort your df on highest value
    • and tell plotly to view the x-axes with the machine id's as a categorical axis by using fig.update_xaxes(type='category')

    Example code:

    import pandas as pd
    import plotly.express as px
        
    data = {
        'MachineID': {0: 33, 1: 16, 2: 44, 3: 31, 4: 1, 5: 9},
        'Value': {0: 6.962754, 1: 6.955913, 2: 6.722355, 
                  3: 6.320854, 4: 6.243701, 5: 5.894093},
    }
        
    df = pd.DataFrame(data)
      
    # sort your df on highest value, descending  
    df = df.sort_values(by='Value', ascending=False)
        
    fig = px.line(df, x='MachineID', y='Value')
    
    # set x-axis as categorical:
    fig.update_xaxes(type='category')
    

    Resulting plot:

    categorical x-axis line plot, highest value first

    You can find more info on categorical axes here:
    https://plotly.com/python/categorical-axes/