【问题标题】:How to plot evenly spaced values on the x axis while plotting using matplotlib如何在使用 matplotlib 绘图时在 x 轴上绘制均匀间隔的值
【发布时间】:2019-10-10 11:15:37
【问题描述】:

我想要绘制一个包含超过 100 000 行的系列。我的图形的 x 轴有问题。由于我的 x 轴由多个日期组成,因此如果将它们全部绘制出来,您将看不到任何东西。

如何选择仅显示 x 轴上每个 x 中的 1 个?

这是一个生成带有丑陋 x 轴的图形的代码示例:

sr = pd.Series(np.array(range(15)))
sr.index = [ '2018-06-' + str(x).zfill(2) for x in range(1,16)]
Out : 
2018-06-01     0
2018-06-02     1
2018-06-03     2
2018-06-04     3
2018-06-05     4
2018-06-06     5
2018-06-07     6
2018-06-08     7
2018-06-09     8
2018-06-10     9
2018-06-11    10
2018-06-12    11
2018-06-13    12
2018-06-14    13
2018-06-15    14

fig = plt.plot(sr)
plt.xlabel('Date')
plt.ylabel('Sales')

【问题讨论】:

标签: python python-3.x pandas matplotlib


【解决方案1】:

使用xticks可以达到想要的效果:

在你的例子中:

sr = pd.Series(np.array(range(15)))
sr.index = [ '2018-06-' + str(x).zfill(2) for x in range(1,16)]
fig = plt.plot(sr)
plt.xlabel('Date')
plt.xticks(sr.index[::4]) #Show one in every four dates
plt.ylabel('Sales')

输出:

另外,如果你想设置刻度数,你可以使用locator_params

sr.plot(xticks=sr.reset_index().index)
plt.locator_params(axis='x', nbins=5) #Show five dates
plt.ylabel('Sales')
plt.xlabel('Date')

输出:

【讨论】:

  • 感谢这对我有帮助!但是您的代码的第一部分不会产生您放置的图形。我必须将行更改为: plt.xticks(sr.index[::4], sr.index[::4]) 才能使其工作。没有它你能用吗?
  • 这很奇怪,它对我有用,就像我最后发布的一样。也许不同的matplotlib版本?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-04-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-02
  • 2016-06-24
相关资源
最近更新 更多