繁体   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