在 Matplotlib 中使用日期时间作为刻度

2023-12-22

我基本上是想绘制一个图表,其中 x 轴代表一年中的月份。数据存储在 numpy.array 中,具有维度k x months。下面是一个最小的例子(我的数据没那么疯狂):

import numpy
import matplotlib
import matplotlib.pyplot as plt

cmap = plt.get_cmap('Set3')
colors = [cmap(i) for i in numpy.linspace(0, 1, len(complaints))]

data = numpy.random.rand(18,12)
y = range(data.shape[1])

plt.figure(figsize=(15, 7), dpi=200)
for i in range(data.shape[0]):
    plt.plot(y, data[i,:], color=colors[i], linewidth=5)
plt.legend(loc='center left', bbox_to_anchor=(1, 0.5)) 
plt.xticks(numpy.arange(0, 12, 1))
plt.xlabel('Hour of the Day')
plt.ylabel('Number of Complaints')
plt.title('Number of Complaints per Hour in 2015')

我想要xticks作为字符串而不是数字。我想知道是否必须手动创建字符串列表,或者是否有其他方法翻译数字到月份。例如,我必须在工作日做同样的事情。

我一直在寻找这些例子:

http://matplotlib.org/examples/pylab_examples/finance_demo.html http://matplotlib.org/examples/pylab_examples/finance_demo.html http://matplotlib.org/examples/pylab_examples/date_demo2.html http://matplotlib.org/examples/pylab_examples/date_demo2.html

但我没有使用datetime.


虽然这个答案 https://stackoverflow.com/a/35467293/6188901效果很好,对于这种情况,您可以避免定义自己的FuncFormatter通过使用预定义的matplotlib对于日期,通过使用matplotlib.dates而不是matplotlib.ticker:

import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import numpy as np
import pandas as pd

# Define time range with 12 different months:
# `MS` stands for month start frequency 
x_data = pd.date_range('2018-01-01', periods=12, freq='MS') 
# Check how this dates looks like:
print(x_data)
y_data = np.random.rand(12)
fig, ax = plt.subplots()
ax.plot(x_data, y_data)
# Make ticks on occurrences of each month:
ax.xaxis.set_major_locator(mdates.MonthLocator())
# Get only the month to show in the x-axis:
ax.xaxis.set_major_formatter(mdates.DateFormatter('%b'))
# '%b' means month as locale’s abbreviated name
plt.show()

获得:

DatetimeIndex(['2018-01-01', '2018-02-01', '2018-03-01', '2018-04-01',
           '2018-05-01', '2018-06-01', '2018-07-01', '2018-08-01',
           '2018-09-01', '2018-10-01', '2018-11-01', '2018-12-01'],
          dtype='datetime64[ns]', freq='MS')
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 Matplotlib 中使用日期时间作为刻度 的相关文章

随机推荐