python 如何让matplotlib正确格式化这些datetime64对象?

ztigrdn8  于 2023-04-10  发布在  Python
关注(0)|答案(2)|浏览(92)

我尝试用Python绘制以下数据的水平条形图:
table
使用以下代码:

plt.barh(subset['sources'], width=subset['repairDate'], left=subset['appearanceDate'])

但是输出给我的x轴上的日期是某种整数。
first_chart
我试着使用一个自定义的日期格式化程序来解决这个问题,但老实说,我不知道幕后发生了什么,它只是戏剧性地增加了xticks的数量,而标签本身似乎仍然是整数:

fig, ax = plt.subplots(1, 1)

ax.barh(subset['sources'], width=subset['repairDate'], left=subset['appearanceDate'])
ax.xaxis.set_major_locator(mdates.YearLocator(1))
ax.xaxis.set_major_formatter(mdates.ConciseDateFormatter(ax.xaxis.get_major_locator()))
ax.set_xticklabels(ax.get_xticks(), rotation=90);

attempt 1

avwztpqn

avwztpqn1#

如果你看过matplotlib文档,你必须使用这样的语法:

matplotlib.pyplot.barh(y, width, height=0.8, left=None,*,align='center',**kwargs)

而不是仅仅使用plt.barh。抱歉,如果这不起作用,这只是一个建议。

z31licg0

z31licg02#

您需要宽度为delta,这在Matplotlib中可以正常工作。但是,barh不会触发日期时间单位机制(这似乎是一个疏忽),因此您需要手动执行:

import numpy as np
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
start = np.array([np.datetime64('2012-01-01'), np.datetime64('2012-02-01'), np.datetime64('2012-01-15')])
stop = np.array([np.datetime64('2012-02-07'), np.datetime64('2012-02-13'), np.datetime64('2012-02-12')])
# force x axis to be times:
l, = ax.plot(stop, [0, 1, 3], '.')
ax.barh([0,1, 3], width=stop-start, left=start)
l.remove()

注意,我使用了numpy.datetim64,但我认为pandas时间增量也应该可以工作(我没有使用pandas,所以不能很容易地进行测试)。

相关问题