簡體   English   中英

如何更改 seaborn 線圖中的 xaxis 標簽

[英]How to change the xaxis labels in seaborn lineplot

下面是 plot 行的圖像,我有 plot。 有沒有辦法在 x 軸上顯示從 2008 年到 2020 年的年份。目前它正在跳過奇數。

線圖

解決方案取決於您的 xaxis 數組的類型。
如果您的 xaxis 是datetime ,您可以設置 xaxis 刻度

plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%Y'))
plt.gca().xaxis.set_major_locator(mdates.YearLocator(base = 1))

如本例中的代碼:

import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import pandas as pd
import numpy as np

requestYear = pd.date_range(start = '2008-01-01', end = '2021-01-01', freq = 'Y')
value = np.random.rand(len(requestYear))

plt.plot(requestYear, value)

plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%Y'))
plt.gca().xaxis.set_major_locator(mdates.YearLocator(base = 1, month = 12, day = 31))
plt.gca().set_xlim(requestYear[0], requestYear[-1])

plt.show()

它提供了這個 plot:

在此處輸入圖像描述

相反,如果您的 xaxis 數組是int類型,則可以使用

plt.gca().set_xticks(np.arange(requestYear[0], requestYear[-1] + 1, 1))

如本例所示:

import matplotlib.pyplot as plt
import numpy as np

requestYear = np.arange(2008, 2021)
value = np.random.rand(len(requestYear))

plt.plot(requestYear, value)

plt.gca().set_xticks(np.arange(requestYear[0], requestYear[-1] + 1, 1))
plt.gca().set_xlim(requestYear[0], requestYear[-1])

plt.show()

這給出了這個 plot:

在此處輸入圖像描述

暫無
暫無

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

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