0

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

line plot

However, if instead I do a bar plot, I now get something quite horrible:

df.plot(kind='bar',figsize=(12,4)),

bar plot

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.

4
  • This should help you :matplotlib.org/gallery/api/date_index_formatter.html Commented Apr 19, 2020 at 4:57
  • @Rajat: Thanks. Yes, I understand that I can manually pick a DateTime format. There are two problems with this: First, it requires a lot of work. Second, how would I generate the same nice format that I get with the line plot? Commented Apr 19, 2020 at 17:21
  • Is there a way to take the axis generated by the line plot and re-use it for the bar plot? I tried doing that (by copying locations and formats from xticks), but I was not successful. I think the reason is that the ticks structure for the bar plot is different than the line plot. Commented Apr 19, 2020 at 17:26
  • May be this could help stackoverflow.com/questions/30133280/… Commented Apr 19, 2020 at 17:55

1 Answer 1

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

enter image description here

Sign up to request clarification or add additional context in comments.

1 Comment

Yes, that is about how far I got as well. It's still not as nice as the one from the line plot...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.