更改日期时间轴的刻度频率

时间:2019-12-18 20:08:20

标签: python pandas date matplotlib

我有以下数据框:

    Date        Prod_01  Prod_02
19  2018-03-01  49870    0.0
20  2018-04-01  47397    0.0
21  2018-05-01  53752    0.0
22  2018-06-01  47111    0.0
23  2018-07-01  53581    0.0
24  2018-08-01  55692    0.0
25  2018-09-01  51886    0.0
26  2018-10-01  56963    0.0
27  2018-11-01  56732    0.0
28  2018-12-01  59196    0.0
29  2019-01-01  57221    5.0
30  2019-02-01  55495    472.0
31  2019-03-01  65394    753.0
32  2019-04-01  59030    1174.0
33  2019-05-01  64466    2793.0
34  2019-06-01  58471    4413.0
35  2019-07-01  64785    6110.0
36  2019-08-01  63774    8360.0
37  2019-09-01  64324    9558.0
38  2019-10-01  65733    11050.0

我需要绘制“ Prod_01”列的时间序列。

“日期”列为熊猫的日期时间格式。

所以我使用了以下命令:

plt.figure(figsize=(10,4))
plt.plot('Date', 'Prod_01', data=test, linewidth=2, color='steelblue')
plt.xticks(rotation=45, horizontalalignment='right');

输出:

enter image description here

但是,我想将xticks的频率更改为一个月,所以我每个月得到一个刻度和一个标签。

我尝试了以下命令:

plt.figure(figsize=(10,4))
plt.plot('Date', 'Prod_01', data=test, linewidth=2, color='steelblue')
plt.xticks(np.arange(1, len(test), 1), test['Date'] ,rotation=45, horizontalalignment='right');

但是我明白了: enter image description here

如何解决此问题? 预先感谢。

1 个答案:

答案 0 :(得分:0)

我对熊猫数据框不是很熟悉。但是,我看不到为什么这不适用于任何pyplot:

根据 ImportanceOfBeingErnest 的相关post的最高SO答案:

  

刻度标签之间的间距专门由轴上刻度之间的间距确定。

因此,要更改刻度线和标签之间的距离,可以执行以下操作:

假设一个以10为底的中心凌乱的人显示以下图形: Cluttered

它需要以下代码并导入 matplotlib.ticker

import numpy as np
import matplotlib.pyplot as plt
# Import this, too
import matplotlib.ticker as ticker


# Arbitrary graph with x-axis = [-32..32]
x = np.linspace(-32, 32, 1024)
y = np.sinc(x)

# -------------------- Look Here --------------------
# Access plot's axes
axs = plt.axes()
# Set distance between major ticks (which always have labels)
axs.xaxis.set_major_locator(ticker.MultipleLocator(5))
# Sets distance between minor ticks (which don't have labels)
axs.xaxis.set_minor_locator(ticker.MultipleLocator(1))
# -----------------------------------------------------

# Plot and show graph
plt.plot(x, y)
plt.show()



要更改标签的放置位置,可以更改“主要刻度”之间的距离。您还可以更改之间没有数字的较小的“较小刻度”。例如,在时钟上,小时刻度上有数字,并且较大(较大的刻度),而在标记分钟(较小的刻度)之间则较小,没有标签的刻度。

通过将--- Look Here ---部分更改为:

# -------------------- Look Here --------------------
# Access plot's axes
axs = plt.axes()
# Set distance between major ticks (which always have labels)
axs.xaxis.set_major_locator(ticker.MultipleLocator(8))
# Sets distance between minor ticks (which don't have labels)
axs.xaxis.set_minor_locator(ticker.MultipleLocator(4))
# -----------------------------------------------------

您可以在下面生成更简洁,更精美的图形: Clean

希望有帮助!

相关问题