Black Lives Matter. Please consider donating to Black Girls Code today.

Custom Sorting X-axis - line chart

Hi all,

I’m trying to create a line chart which will display a metric on Y axis and time on X axis. When displaying data for last 7 days on X axis data is sorted in numerical ascending order rather than on logical order which should be 23 feb , 24 feb , 25 feb , 26 … 1 Mar, 2 Mar. Any pointers on how to custom sort X axis will be helpful.

Code, pasting only the graph part … results is a Pandas Data Frame loaded from sql db.

import plotly.graph_objs as go

def draw_graph(results):
dates = results[‘row_type’] # x axis last 7 days data
points = results[‘metric1’] # Y axis metric
figure = go.Figure(
data=[go.Scatter(x=dates, y=points, mode=‘lines+markers’,name=‘lines’)],


It’s hard to suggest an exact solution without knowing the type of the x value. A general approach is to do something like

dates = sorted(results[‘row_type’], key=lambda x: ____)

By providing an appropriate function to the key param, the sorted function will apply the lambda function to each x value and use its return value to sort on, rather than the original value. You just need to fill in the blank, which is the return value of the lambda according to the data type of that column so that it will be sorted appropriately.

Sometimes the reverse=True param for the sorted function is also useful, but less likely here probably.

1 Like