簡體   English   中英

如何 plot 小時:ISO 8601 時間格式的分鍾時間?

[英]How to plot hour:min time in ISO 8601 time format?

我正在嘗試根據他們的時間記錄 plot 溫度數據點。

t = ['2021-12-11T0:6:15', '2021-12-11T7:15', '2021-12-11T8:15', '2021-12-11T9:15', '2021-12-11T10:15']

temp = [33.6, 33.6, 33.6, 33.6, 33.6]

注意:正如您提到的t表示沒有hour ,原因是temp是在hour:second中收集的。

t是一個字符串,表示 ISO 8601 格式的日期和時間(參考: datetime.datetime.isoformat() ), temp是一個浮點數。 plot 的方式應該是tx-axis (表示為hour:min )和tempy-axis (表示為celcius )。 我想將變量保留為列表和 plot 圖表而不使用 Pandas 但PyQtGraph庫。

我嘗試了以下方法:

from PySide6.QtWidgets import (
    QApplication, 
    QMainWindow
    )
import pyqtgraph as pg # import PyQtGraph after Qt

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        self.graphWidget = pg.PlotWidget()
        self.setCentralWidget(self.graphWidget)

        t    = # declared above
        temp = # declared above

        # plot data: time, temp values
        self.graphWidget.plot(time, temp)

# Always start by initializing Qt (only once per application)
app = QApplication([])
window = MainWindow()
## Display the widget as a new window
window.show()
## Start the Qt event loop
app.exec_()

運行上面的代碼后,我得到了一個回溯: numpy.core._exceptions._UFuncNoLoopError: ufunc 'fmin' did not contain a loop with signature matching types (dtype('<U18'), dtype('<U18')) -> None

我知道t存在問題,因為它的值是str ,它們應該與temp的類型相同(注意: temp值應該始終保持float )。 我不知道如何解決它。

我正在使用PySide6和 PyQtGraph,其中 Python 是使用的語言。 為此,我還嘗試使用 plot 兩個變量使用matplotlib庫。 我做了以下事情:

import numpy as np
import matplotlib.pyplot as plt

x, y = t, temp

plt.plot(x, y, label='temperature fluctuation')
plt.xlabel('time (hour:min)')
plt.ylabel('temperature (C)')
plt.legend(loc='lower right')

幾個假設:

  • 您的意思是hour:minutes ,而不是書面的hour:seconds 如果有不同,請澄清你的觀點
  • 時間字符串錯誤:根據 ISO 8601 小時和分鍾應該是兩個字符的字符串塊。 您必須先清理字符串列表。 我已經手動完成了,因為 Python 腳本超出了范圍
  • 我使用了一個稍微不同的temp數組來顯示圖表中的一些可變性。 完全可以忽略不計

也就是說,一種可能的方法是:

  • 將 iso 字符串轉換為時間戳(浮點)值。 這將由pyqtgraph處理到plot numbers
  • 根據需要將完整的 ISO 字符串轉換為格式為HH:MM的字符串,並將其用作軸刻度。 您有兩個選擇在代碼中解釋(請閱讀評論)
  • PlotWidget獲取x-axis並使用setTick屬性設置您的自定義刻度。 為此,您必須創建一個包含兩個值的元組列表,即基礎數字數據和自定義字符串數據

這是代碼:

from datetime import datetime

from PySide6.QtWidgets import (
    QApplication,
    QMainWindow
    )
import pyqtgraph as pg # import PyQtGraph after Qt



class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        self.graphWidget = pg.PlotWidget()
        self.setCentralWidget(self.graphWidget)

        t_string_list = ['2021-12-11T06:15', '2021-12-11T07:15', '2021-12-11T08:15', '2021-12-11T09:15', '2021-12-11T10:15']

        # Get the timestamp value. A numeric value is needed for the underlying x-axis data
        t_time_value = [datetime.fromisoformat(t_string).timestamp() for t_string in t_string_list]

        # Get the x-axis ticks string values as HH:MM. Two ways
        # ---- straight and unsafe way - It only works if the ISO Format will end with minutes! [...THH:MM]
        t_ticks_values = [val[-5:] for val in t_string_list]

        # --- Safe and general way: create a datetime object from isoformat and then convert to string
        t_ticks_values = [datetime.fromisoformat(val).strftime('%H:%M') for val in t_string_list]

        temp = [33.6, 31.6, 35.6, 32.6, 37.6]

        # plot data: time, temp values
        self.graphWidget.plot(t_time_value, temp)

        # Get the x-axis
        x_axis = self.graphWidget.getAxis('bottom')
        # Check https://stackoverflow.com/questions/31775468/show-string-values-on-x-axis-in-pyqtgraph
        ticks = [list(zip(t_time_value, t_ticks_values))]
        x_axis.setTicks(ticks)

# Always start by initializing Qt (only once per application)
app = QApplication([])
window = MainWindow()
## Display the widget as a new window
window.show()
## Start the Qt event loop
app.exec_()

結果如下:

在此處輸入圖像描述

有關更高級的策略,例如自定義tickStrings生成器的子類化AxisItem ,請參閱此答案

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM