简体   繁体   中英

Histogram by matplotlib.pyplot

数据表

I want to create the histogram to compare total system costs and total incentive approved.

x = np.arange(7)

y1 = ['Total System Costs']
y2 = ['Total Incentive Approved']

bar_width = 0.3

tick_label = ['2012', '2013', '2014', '2015', '2016', '2017', '2018']
 
plt.bar(x, y1, bar_width, color='salmon', label='Total System Costs')

plt.bar(x + bar_width, y2,bar_width, color='orchid', label='Total Incentive Approved')

plt.legend()

plt.xticks(x + bar_width / 2,tick_label)

plt.show()

What's wrong with my coding above?

我的结果

Your code is OK. The problem is that matplotlib does not know how to arrange the y-axis, because your data is not numeric. So it places the first "value" at 0 and the second above it (at 1). The result is that y1 = ['Total System Costs'] shows a bar of zero height, which you can't observe.

If you call ax.get_ylim() on your axis ( plt.gca().get_ylim() in your case as you don't open an axis handle explicitly), you'll note that it returns something like

(0.0, 1.05) If y1 now represents 0, it explains why you don't see something.

Even extending the limits of the y-axis (lets say plt.gca().set_ylim((-1,1.05)) ) won't help, because the height of the bar is still zero (starting at 0 to 0...).

To illustrate the theory, I added a single line with a new y-value to your code:

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(7)

y1 = ['Total System Costs']
y2 = ['Total Incentive Approved']

bar_width = 0.3
plt.bar(0,'zero',bar_width) # <<<<< additional bar plot
plt.bar(x, y1,bar_width, color='salmon', label='Total System Costs')
plt.bar(x + bar_width, y2,bar_width, color='orchid', label='Total Incentive Approved')

plt.legend()
# set tick labels
tick_label = ['2012', '2013', '2014', '2015', '2016', '2017', '2018']
plt.xticks(x + bar_width / 2,tick_label)

plt.show()

酒吧

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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