Matplotlib bar chart on datetime index values

Viewed 1215

I'm having trouble getting the following code to display a bar chart properly. The plot has very thin lines which are not visible until you zoom in, but even then it's not clear. I've tried to control with the width option to plt.bar() but it's not doing anything (e.g. tried 0.1, 1, 365).

Any pointers on what I'm doing wrong would be appreciated.

Many thanks

import pandas as pd
import numpy as np
import matplotlib.pylab as plt
import matplotlib.dates as mdates

plt.close('all')

mydateparser2 = lambda x: pd.datetime.strptime(x, "%m/%d/%Y")
colnames2=['Date','Net sales', 'Cost of sales']
df2 = pd.read_csv(r'account-test.csv', parse_dates = ['Date'] , date_parser = mydateparser2, index_col='Date')
df2= df2.filter(items=colnames2)
df2 = df2.sort_values('Date')

print (df2.info())
print (df2)

fig = plt.figure()

plt.bar(df2.index.values, df2['Net sales'], color='red', label='Net sales'  )
plt.ylim(500000,2800000)
plt.show()
plt.legend(loc=4)

Resulting output (to show data types)

<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 15 entries, 2005-12-31 to 2019-12-31
Data columns (total 2 columns):
Net sales        15 non-null int64
Cost of sales    15 non-null int64
dtypes: int64(2)
memory usage: 360.0 bytes
None
            Net sales  Cost of sales
Date                                
2005-12-31    1161400         907200
2006-12-31    1193100         928300
2007-12-31    1171100         888100
2008-12-31    1324900        1035700
2009-12-31    1108300         859800
2010-12-31    1173600         891000
2011-12-31    1392400        1050300
2012-12-31    1578200        1171500
2013-12-31    1678200        1224200
2014-12-31    1855500        1346700
2015-12-31    1861200        1328400
2016-12-31    2004300        1439700
2017-12-31    1973300        1421500
2018-12-31    2189100        1608300
2019-12-31    2355700        1715300
1 Answers

Maybe you are trying to plot too many bars on a small plot. Try fig = plt.figure(figsize=(12,6) to have a bigger plot. You can also pass width=0.9 to your bar command:

fig, ax = plt.subplots(figsize=(12,6))
df.plot.bar(y='Net sales', width=0.9, ax=ax)  # modify width to your liking

Output:

enter image description here

Related