Matplotlib线与条形图DateTime轴格式 [英] Matplotlib Line vs. Bar plot DateTime axis formatting
问题描述
我有一个带有DateTime索引的DataFrame:
I have a DataFrame with a DateTime index:
import pandas as pd
from random import randrange
dates = pd.date_range(start="2020-02-01",end='2020-04-18',freq='1d')
df = pd.DataFrame(index=dates,data=[randrange(10000) for i in range(78)]
现在,当我将数据绘制为线图时,matplotlib会生成格式正确的x轴:
Now when I plot the data as a line plot, matplotlib produces a nicely formatted x axis:
df.plot(figsize=(12,4))
然而,如果我做一个条形图,我现在会得到一些非常可怕的东西:
However, if instead I do a bar plot, I now get something quite horrible:
df.plot(kind='bar',figsize=(12,4)),
这是很令人不安的,因为它是相同的DataFrame.我想要的是具有条形图,但具有格式正确的DateTime轴.
This is quite disconcerting, as it is the same DataFrame. What I want is to have the bar plot, but with the nicely formatted DateTime axis.
有没有简单的方法来实现这一目标?我尝试直接使用 bar 命令,但这会产生另一种 x 轴格式,不如使用 Pandas 方法绘图生成的格式好.
Is there an easy way to achieve that? I tried using the bar command directly, but that produces yet another x axis format, not as nice as the one generated by plotting with a pandas method.
推荐答案
您可以执行以下操作:
In [23]: fig, ax = plt.subplots(figsize=(12, 12))
Attribute Qt::AA_EnableHighDpiScaling must be set before QCoreApplication is created.
In [27]: ax.bar(df.index.values,
...: df[0],
...: color='purple')
Out[27]: <BarContainer object of 78 artists>
In [29]: import matplotlib.dates as mdates
...: from matplotlib.dates import DateFormatter
In [30]: date_form = DateFormatter("%m-%d")
...: ax.xaxis.set_major_formatter(date_form)
...:
...: # Ensure a major tick for each week using (interval=1)
...: ax.xaxis.set_major_locator(mdates.WeekdayLocator(interval=1))
...: plt.show()
这篇关于Matplotlib线与条形图DateTime轴格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!