python - 带有日期和时间的 reportlab LinePlot 轴

标签 python reportlab

我想使用 reportlab 在 LinePlot 中可视化数据。数据具有格式为 YYYYMMDDHHMMSS 的 x 轴值(时间戳)。我知道 reportlab x 轴类 NormalDateXValueAxis 存在,但它只需要日期 (YYYYMMDD) 并且不允许使用时间。

一个问题是reportlab 是否已经支持我尚未找到的任何类?

我尝试的另一种方法是简单地使用时间戳字符串作为 x 轴值并为这些值定义格式化程序。一个例子是:

from reportlab.graphics.charts.lineplots import LinePlot
from reportlab.graphics.shapes import Drawing, _DrawingEditorMixin
from datetime import datetime


def formatter(val):
    dtstr = str(int(val))
    print(dtstr)
    dt = (datetime.strptime(str(int(val)), "%Y%m%d%H%M%S")).strftime("%d.%m.%Y %H:%M:%S")
    return dt

class Test(_DrawingEditorMixin, Drawing):

    def __init__(self,width=258,height=150,*args,**kw):
        Drawing.__init__(self,width,height,*args,**kw)
        # font
        fontSize = 7
        # chart
        self._add(self,LinePlot(),name='chart',validate=None,desc=None)
        self.chart.y                = 16
        self.chart.x                = 32
        self.chart.width            = 212
        self.chart.height           = 90
        # x axis
        self.chart.xValueAxis.labels.fontSize       = fontSize-1
        self.chart.xValueAxis.labelTextFormat       = formatter
        # y axis
        self.chart.yValueAxis.labels.fontSize       = fontSize -1
        # sample data
        self.chart.data = [
            [
                (20200225130120, 100),
                (20200225130125, 0),
                (20200225130130, 300),
                (20200225130135, 0),
                (20200225130140, 500),
                (20200225130145, 0),
                (20200225130150, 700),
                (20200225130155, 0),
                (20200225130315, 900)
            ]
        ]

if __name__=="__main__": #NORUNTESTS
    Test().save(formats=['pdf'],outDir='.',fnRoot=None)

但是这个方法有两个问题。

  1. 赋予格式化程序的值是不可预测的(至少对我而言)。 Reportlab 似乎以它认为最好的方式修改了刻度。结果有时是一些值不是有效的时间戳并且不能被 datetime 解析。我有时会遇到异常,即秒数必须在 0 到 59 之间。Reportlab 创建了一个值为 20200225136000 的刻度。

  2. 由于 x 轴不知道这些值是时间戳,所以它仍然为 2020022513596120200225135965 等留有空间。结果是在图。

enter image description here

最佳答案

One question is does reportlab already support this with any class that I have not found yet?

据我所知,我认为您可以通过 ValueAxis 实现您想要的。如果您可以更改库,我建议您使用 matplotlib正如我所见previous working examples .你也可以试试看有没有PYX (这也是 ReportLab 的一个很好的替代品)处理这种情况,但我没有找到。

关于python - 带有日期和时间的 reportlab LinePlot 轴,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60396477/

相关文章:

Python偏导数容易

arabic - 在 ReportLab 中使用阿拉伯语 (RTL)

python - reportlab:如何设置初始/默认 View ?

python - 如何在 reportlab Canvas 中绘制 matplotlib 图?

python - reportlab 值错误 : Invalid color value 'initial'

python - 如何在没有互联网连接的情况下安装tensorflow?

python - 按字母顺序排序数据框的索引

python - Google PubSub 消息重复

python - SQLITE3 - 将数据放入带有循环的列中

Python Reportlab 合并段落