Matplotlib Line vs. Bar plot DateTime axis formatting

ⅰ亾dé卋堺 提交于 2021-02-11 12:29:30

问题


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)]

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)),

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.

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.


回答1:


You can do something like this :

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()



来源:https://stackoverflow.com/questions/61299634/matplotlib-line-vs-bar-plot-datetime-axis-formatting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!