Facet plots in Plotly gives wrong order on x-axis in Python

Question:

I want to have a facet plot with a plot per day given a certain value for every 15 minutes. The part where it goes wrong is when I have the starting time on day 1 at 06:15:00 and the next day at 06:00:00. This results in the following figure:

Value per day

The Tuesday plots a line with the value of 06:00:00 at the end. I want to have the 06:00:00 value at the beginning.

The following code is used to create this graph. I created a subset of the data I actually have, which contains more days and more timestamps.

import pandas as pd
import plotly.express as px

df = pd.DataFrame({'Date Time':['2022-11-28 06:15:00', '2022-11-28 06:30:00', '2022-11-28 06:45:00','2022-11-28 07:00:00', 
                                '2022-11-29 06:00:00', '2022-11-29 06:15:00', '2022-11-29 06:30:00', '2022-11-29 06:45:00', '2022-11-29 07:00:00'
                                ],
                   'Time':['06:15:00', '06:30:00', '06:45:00','07:00:00',
                           '06:00:00', '06:15:00', '06:30:00', '06:45:00', '07:00:00'],
                   'Day of Week':['Monday','Monday','Monday','Monday','Tuesday','Tuesday','Tuesday','Tuesday','Tuesday'],
                   'Value':[0,0.2,0.8,1,0,0.1,0.3,0.8,1]})


fig = px.line(df,
                x='Time',
                y='Value',
                facet_col = 'Day of Week',
                category_orders={'Time': df['Time']},
                title='Example Graph')

I tried several things:

  • Use the column ‘Date Time’ as the x axis, this results in an unreadable graph as the x axis becomes continious.
  • Format the date time to only hh:mm:ss with dt.strftime, but this gives an object column and therefore results in the same problem
  • Using catgery_orders as stated in this question link
Asked By: Frank

||

Answers:

In this case, if the x-axis is a time series, first update the x-axis values to a time series. Then, in the x-axis setting, set the axis type to date and specify the interval in dtick in milliseconds; if it is in 15-minute increments, set it to ‘900000’ since 1000 milliseconds x 60 seconds x 15 minutes.

df['Time'] = pd.to_datetime(df['Time'])

fig = px.line(df,
              x='Time',
              y='Value',
              facet_col='Day of Week',
              category_orders={'Time': df['Time']},
              title='Example Graph',
              facet_col_spacing=0.05,
              )

fig.update_xaxes(type='date', dtick='900000', tickformat='%H:%M')
fig.show()

enter image description here

Answered By: r-beginners
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.