简体   繁体   English

如何更改 seaborn 线图中的 xaxis 标签

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

Below is the image of line plot i have plot.下面是 plot 行的图像,我有 plot。 Is there a way to show on x axis year from 2008 to the 2020. currently it is skipping odd ones.有没有办法在 x 轴上显示从 2008 年到 2020 年的年份。目前它正在跳过奇数。

线图

The solution depends on the type of your xaxis array.解决方案取决于您的 xaxis 数组的类型。
If your xaxis is a datetime , you can set the xaxis ticks with如果您的 xaxis 是datetime ,您可以设置 xaxis 刻度

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

as the code in this example:如本例中的代码:

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()

which provides this plot:它提供了这个 plot:

在此处输入图像描述

On the contrary, if your xaxis array is a int type, you can use相反,如果您的 xaxis 数组是int类型,则可以使用

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

as in this example:如本例所示:

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()

which gives this plot:这给出了这个 plot:

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM