Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to scale x-axis with intervals of 1 hour with x data type being timedelta64[ns]

My x-axis being time in hours and minutes, I am not able to plot in intervals of 1 hour, by default it is plotting in interval of 5 hours.

Here x-axis is "newtime" which is in the format below

 00:00:00
 00:15:00
 00:30:00
 00:45:00
 01:00:00
 01:15:00
 01:30:00
 01:45:00
 02:00:00
 02:15:00
 02:30:00
     .
     .
     .
 23:45:00

First tried like this but got error

ggplot(data = temp1)+
aes(x="newtime", y="SALES" ,color="newdate")+
geom_line()+
labs(x = "Time", y = "SALES", title = s)+
scale_x_datetime(breaks="1 hour")

TypeError: Discrete value supplied to continuous scale

Second tried like this but got error

ggplot(data = temp1)+
aes(x="newtime", y="SALES" ,color="newdate")+
geom_line()+
labs(x = "Time", y = "SALES", title = s)+
scale_x_continuous(breaks=range(0,24,1))

TypeError: Discrete value supplied to continuous scale

Third tried like this but got error

ggplot(data = temp1)+
aes(x="newtime", y="SALES" ,color="newdate")+
geom_line()+
labs(x = "Time", y = "SALES", title = s)+
scale_x_discrete(breaks=range(0,24,1))

TypeError: Continuous value supplied to discrete scale

ggplot(data = temp1)+
aes(x="newtime", y="SALES" ,color="newdate")+
geom_line()+
labs(x = "Time", y = "SALES", title = s)

The entire code is here

import pandas as pd
from plotnine import *
import numpy as np

temp1=pd.read_excel("C:\\Users\\Desktop\\2019\\DATA.xlsx")
a=temp1.Date.astype(str)
temp1["newdate"]=a
b=pd.to_timedelta(temp1.Hour, unit='h') + pd.to_timedelta(temp1.Min, 
unit='m')
temp1["newtime"]=b
v=(
 ggplot(data = temp1)+
 aes(x="newtime", y="SALES" ,color="newdate")+
 geom_line()+
 labs(x = "Time", y = "SALES", title = "s")+
 scale_x_datetime(breaks="1 hour")

  )
print(v)

And the data is in the link link

I'm trying to plot something like this !https://i.sstatic.net/xOMRE.jpg. I'm getting plot like this !https://i.sstatic.net/Mr9cb.jpg.

like image 217
Srihari Uttanur Avatar asked Sep 06 '25 21:09

Srihari Uttanur


1 Answers

When using timedelta dtype you need to use scale for this type: scale_x_timedelta. However, this may require some tricks to specify breaks, e.g.:

scale_x_timedelta(
    breaks=lambda x: pd.to_timedelta(
        pd.Series(range(0, 10)),
        unit='h'
    )
)

Which looks like this:

using deltatime

Alternatively, you could keep using scale_x_datetime, converting your newtime column:

temp1.newtime = pd.to_datetime(temp1.newtime)

And if you want to have nice labels, use mizani formatters:

from mizani.formatters import date_format

v = (
    ggplot(data=temp1)
    + aes(x="newtime", y="SALES", color="newdate")
    + geom_line()
    + scale_x_datetime(
        breaks="1 hour",
        labels=date_format('%H:%M') # for nice labels
    )
)
print(v)

And here is the result:

using datetime

like image 158
krassowski Avatar answered Sep 08 '25 12:09

krassowski