python matplotlib 中带有日期时间的 barplot 的奇怪行为

Weird behavior of barplot from python matplotlib with datetime

import matplotlib.pyplot as plt
import datetime
x = [datetime.datetime(1943,3, 13,12,0,0),
     datetime.datetime(1943,3, 13,12,5,0),
     datetime.datetime(1943,3, 13,12,10,0),
     datetime.datetime(1943,3, 13,12,15,0),
     datetime.datetime(1943,3, 13,12,20,0),
     datetime.datetime(1943,3, 13,12,25,0),
     datetime.datetime(1943,3, 13,12,30,0),
     datetime.datetime(1943,3, 13,12,35,0)]
y = [1,2,3,4,2,1,3,4]

# plot the data out but does not provide sufficient detail on the lower    values
plt.figure()
plt.bar(x,y)

# plot the data out but ommit the datetime information
plt.figure()
plt.bar(range(0,len(x)),y)

大家好,我刚开始使用 matplotlib 从 matlab 过渡到 python。但是,我遇到了 matplotlib 的奇怪行为,因为它无法显示数据以及日期时间元素。 我的问题是两个条形图的输出会产生两个不同的结果。

第一个直接将数据转换为某种连续数据,而第二个更像是分类数据。有没有人遇到过与我类似的问题并且不介意分享他们解决这个问题的方法?

P/s:我试过 seaborn 并且它有效,但不知何故不能很好地与双轴绘图一起使用。我也用谷歌搜索了类似的问题,但不知何故不是这样的问题?

我不确定如何解决 matplotlibdatetime 的问题,但是 pandas 可以很好地处理 datetime 对象。你可以考虑一下。例如,您可以执行以下操作:

import pandas as pd
df = pd.DataFrame({'date': x, 'value': y})
df.set_index('date').plot.bar()
plt.show()

而且改进也很容易:

df = pd.DataFrame({'date': x, 'value': y})
df['date'] = df['date'].dt.time 
df.set_index('date').plot.bar(rot=0, figsize=(10, 5), alpha=0.7)
plt.show()

我不确定我是否会将观察到的行为称为意外行为。在第一种情况下,您为条形图的 x 变量提供日期,因此它将在这些日期绘制条形图。在第二种情况下,您向 x 变量提供了一些数字,因此它将绘制这些数字。

由于您没有说出您真正喜欢哪一个,解决方案是使它们在视觉上相同。不过各自的概念还是不一样的。

import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter
import datetime
x = [datetime.datetime(1943,3, 13,12,0,0),
     datetime.datetime(1943,3, 13,12,5,0),
     datetime.datetime(1943,3, 13,12,10,0),
     datetime.datetime(1943,3, 13,12,15,0),
     datetime.datetime(1943,3, 13,12,20,0),
     datetime.datetime(1943,3, 13,12,25,0),
     datetime.datetime(1943,3, 13,12,30,0),
     datetime.datetime(1943,3, 13,12,35,0)]
y = [1,2,3,4,2,1,3,4]

# plot numeric plot
plt.figure()
plt.bar(x,y, width=4./24/60) # 4 minutes wide bars
plt.gca().xaxis.set_major_formatter(DateFormatter("%H:%M"))

# Plot categorical plot
plt.figure()
plt.bar(range(0,len(x)),y, width=0.8) # 0.8 units wide bars
plt.xticks(range(0,len(x)), [d.strftime("%H:%M") for d in x])

plt.show()

然而,当使用不同的数据时,概念之间的差异会更加明显,

x = [datetime.datetime(1943,3, 13,12,0,0),
     datetime.datetime(1943,3, 13,12,5,0),
     datetime.datetime(1943,3, 13,12,15,0),
     datetime.datetime(1943,3, 13,12,25,0),
     datetime.datetime(1943,3, 13,12,30,0),
     datetime.datetime(1943,3, 13,12,35,0),
     datetime.datetime(1943,3, 13,12,45,0),
     datetime.datetime(1943,3, 13,12,50,0)]