【问题标题】:How to scale x-axis with intervals of 1 hour with x data type being timedelta64[ns]如何以 1 小时为间隔缩放 x 轴,x 数据类型为 timedelta64[ns]
【发布时间】:2019-02-13 19:47:33
【问题描述】:

我的 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)

并且数据在链接link

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

【问题讨论】:

  • 欢迎来到 SO!请提供一个Minimal, Complete, and Verifiable example,其中将包含一个示例数据框来演示该问题。否则,我只能向您保证 scale_x_datetime 对我有用。
  • 这仍然不是一个可重现的例子。 s 是什么?你的数据是什么类型的?如何创建数据框?
  • 嗨@krassowski 该帖子已被编辑。如果您能够重现该问题,请告诉我。
  • 仍然对我有用。您可能需要提供一个可重现的(如复制粘贴运行)示例(可能还有 plotnine/pandas/numpy 的版本)。
  • 嗨@krassowski 我已经编辑了帖子,提供了整个代码和数据集。如果您能够重现该问题,请告诉我。

标签: python-3.x pandas plotnine


【解决方案1】:

使用timedelta dtype 时,您需要为此类型使用比例: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)

结果如下:

【讨论】:

    猜你喜欢
    • 2018-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-30
    • 1970-01-01
    • 2022-07-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多