Lynn
Lynn

Reputation: 4408

Plotly axis is showing dates in reverse order (recent to earliest) -Python

I have created a visualization utilizing the plotly library within Python. Everything looks fine, except the axis is starting with 2020 and then shows 2019. The axis should be the opposite of what is displayed.

Here is the data (df):

   date      percent   type
   3/1/2020  10        a
   3/1/2020  0         b
   4/1/2020  15        a
   4/1/2020  60        b
   1/1/2019  25        a
   1/1/2019  1         b
   2/1/2019  50        c 
   2/1/2019  20        d

This is what I am doing

 import plotly.express as px
 px.scatter(df, x = "date", y = "percent", color = "type", facet_col = "type")

How would I make it so that the dates are sorted correctly, earliest to latest? The dates are sorted within the raw data so why is it not reflecting this on the graph?

Any suggestion will be appreciated.

Here is the result:

enter image description here

Upvotes: 2

Views: 2435

Answers (2)

Sander van den Oord
Sander van den Oord

Reputation: 12858

Your date column seems to be a string. If you convert it to a datetime you don't have to sort your dataframe: plotly express will set the x-axis to datetime:

Working code example:

import pandas as pd
import plotly.express as px
from io import StringIO

text = """
date      percent   type
   3/1/2020  10        a
   3/1/2020  0         b
   4/1/2020  15        a
   4/1/2020  60        b
   1/1/2019  25        a
   1/1/2019  1         b
   2/1/2019  50        c 
   2/1/2019  20        d
"""

df = pd.read_csv(StringIO(text), sep='\s+', header=0)

px.scatter(df, x="date", y="percent", color="type", facet_col="type")

plotly express showing datetime axis

Upvotes: 2

noah
noah

Reputation: 2786

It is plotting in the order of your df. If you want date order then sort so in date order.

df.sort_values('date', inplace=True)

A lot of other graphing utilities (Seaborn, etc) by default sort when plotting. Plotly Express does not do this.

Upvotes: 3

Related Questions