簡體   English   中英

在 matplotlib 中將軸從小時更改為月

[英]Change axis from hours to months in matplotlib

我是一名初級程序員,我正在使用 matplotlib 繪制數據。 該圖應該顯示幾個小時內的氮含量。 但是,由於模型運行了幾個月,因此最好在 x 軸上顯示月份而不是小時。

當前的情節可以在這里看到

所以,我的問題是:如何將 x 軸從幾小時更改為幾個月?

謝謝! 代碼如下所示。


plt.figure()
plt.title( 'Nitrogen content')
plt.plot(sugar_kelp_field.N_content_list)
plt.plot(720, 0.0150, 'bo')
plt.plot(1440, 0.0205, 'bo')
plt.plot(2160, 0.0265, 'bo')
plt.plot(2880, 0.0283, 'bo')
plt.plot(3600, 0.0234, 'bo')
plt.plot(4320, 0.0181, 'bo')
plt.plot(5040, 0.0142, 'bo')
plt.plot(5760, 0.0097, 'bo')
plt.plot(6480, 0.0083, 'bo')
plt.xlabel("time [h]")
plt.ylabel("nitrogen content [fraction of dw]")

plt.show()

顯然,您可以通過將小時數除以730來獲得月數的近似值:

小時到月的公式

import matplotlib.pyplot as plt


def hours_to_months_approximation(hours: int) -> float:
    return round(hours / 730, 2)


def main() -> None:
    plt.figure()
    plt.title('Nitrogen content')
    plt.plot(sugar_kelp_field.N_content_list)
    plt.plot(hours_to_months_approximation(720), 0.0150, 'bo')
    plt.plot(hours_to_months_approximation(1440), 0.0205, 'bo')
    plt.plot(hours_to_months_approximation(2160), 0.0265, 'bo')
    plt.plot(hours_to_months_approximation(2880), 0.0283, 'bo')
    plt.plot(hours_to_months_approximation(3600), 0.0234, 'bo')
    plt.plot(hours_to_months_approximation(4320), 0.0181, 'bo')
    plt.plot(hours_to_months_approximation(5040), 0.0142, 'bo')
    plt.plot(hours_to_months_approximation(5760), 0.0097, 'bo')
    plt.plot(hours_to_months_approximation(6480), 0.0083, 'bo')
    plt.xlabel('time [months]')
    plt.ylabel('nitrogen content [fraction of dw]')
    plt.show()


if __name__ == '__main__':
    main()

假設您在列表中有 hours 和 h 值:

hours=[720, 1440 ,2160, 2880, 3600, 4320, 5040, 5760, 6480]
v=[0.0150, 0.0205, 0.0265, 0.0283, 0.0234, 0.0181, 0.0142, 0.0097, 0.0083]

calendar允許您獲取月份名稱:

import calendar
m_str=[calendar.month_name[int(x/(30*24))] for x in hours]  
>>>['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September']

然后這段代碼:

plt.figure()
plt.title( 'Nitrogen content')
plt.plot(m_str, v, 'bo')
plt.xticks(rotation = 45)
plt.show()

會得到想要的結果:

在此處輸入圖像描述

暫無
暫無

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

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