1

我的 x 轴是以小时和分钟为单位的时间,我无法以 1 小时的间隔绘制,默认情况下它以 5 小时的间隔绘制。

这里x轴是“newtime”,格式如下

 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

第一次尝试这样但得到错误

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:提供给连续刻度的离散值

第二次尝试这样但出错了

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:提供给连续刻度的离散值

第三次这样尝试但出现错误

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:提供给离散刻度的连续值

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

完整的代码在这里

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)

并且数据在链接链接中

我正在尝试绘制这样的东西!https://imgur.com/vIf4a0r。我得到这样的情节!https://imgur.com/5ELyrzh

4

1 回答 1

2

使用timedeltadtype 时,您需要对这种类型使用 scale:scale_x_timedelta。但是,这可能需要一些技巧来指定中断,例如:

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

看起来像这样:

使用增量时间

或者,您可以继续使用scale_x_datetime,转换您的newtime列:

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

如果您想拥有漂亮的标签,请使用 mizani 格式化程序:

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)

结果如下:

使用日期时间

于 2019-02-16T17:08:34.753 回答