简体   繁体   English

日期时间索引值上的 Matplotlib 条形图

[英]Matplotlib bar chart on datetime index values

I'm having trouble getting the following code to display a bar chart properly.我无法让以下代码正确显示条形图。 The plot has very thin lines and are not visible until you zoom in, even then its not clear. plot 的线条非常细,在放大之前看不到,即使那样也不清楚。 I've tried to control with the width option to plt.bar but its not doing anything (eg. tried 0.1, 1, 365).我尝试使用 plt.bar 的宽度选项进行控制,但它没有做任何事情(例如尝试 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)结果 output (显示数据类型)

<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

Maybe you are trying to plot too many bars on a small plot.也许你是在尝试 plot 太多吧,小 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 = plt.figure(figsize=(12,6)以获得更大的 plot。您还可以将width=0.9传递给bar命令:

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

Output: Output:

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM