【问题标题】:How to change the xaxis labels in seaborn lineplot如何更改 seaborn 线图中的 x 轴标签
【发布时间】:2020-10-21 07:01:15
【问题描述】:

下面是我绘制的线图图像。有没有办法在 x 轴上显示从 2008 年到 2020 年的年份。目前它正在跳过奇数。

【问题讨论】:

  • 这取决于您在 xaxis 上的数据类型。你在密谋intdatetime...?
  • @AndreaBlengino 绘图 int.
  • @AndreaBlengino 我想通了。但是在时间序列数据的情况下无法计算。

标签: python matplotlib seaborn visualization


【解决方案1】:

解决方案取决于您的 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()

提供了这个情节:

相反,如果你的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()

这给出了这个情节:

【讨论】:

  • 这非常有效。但是,我在 2008 年之前在 1999-2007 年变黑了。我尝试添加 plt.xlim('2008-01-01,'2020-03-10') 它没有用。有没有办法避免它。
猜你喜欢
  • 2016-09-03
  • 2020-02-04
  • 2015-02-10
  • 2018-02-06
  • 1970-01-01
  • 2021-11-25
  • 2019-10-29
  • 1970-01-01
相关资源
最近更新 更多