[英]stacked bar chart - space between y-axis and first bar: matplotlib.pyplot
I am just starting out with matplotlib.pyplot and am a little stuck. 我刚开始使用matplotlib.pyplot并且有点卡住了。
Using the example in the matpltlib.pyplot documentation, I have created a stacked bar chart 使用matpltlib.pyplot文档中的示例,我创建了一个堆积条形图
using the following code:
使用以下代码:
import numpy as np
import matplotlib.pyplot as plt
N = 7
OECD = (242, 244, 255, 263, 269, 276, 285)
NonOECD = (282, 328, 375, 417, 460, 501, 535)
Sum = ('524', '572', '630', '680', '729', '777', '820')
ind = np.arange(N)
width = 0.5
p1 = plt.bar(ind, NonOECD, width, color = 'r')
p2 = plt.bar(ind, OECD, width, color = 'b', bottom = NonOECD)
plt.ylabel('Quadrillion Btu')
plt.title('World Total Energy Consumption 2010 - 2040')
plt.xticks(ind+width/2., ('2010', '2015', '2020', '2025', '2030', '2035', '2040'))
plt.yticks(np.arange(0, 1001, 200))
plt.legend((p1[0], p2[0]), ('Non - OECD', 'OECD'), loc = 2, frameon = 'false')
plt.tick_params(top = 'off', bottom = 'off', right = 'off')
plt.grid(axis = 'y', linestyle = '-')
plt.show()
However, I would prefer it if the first bar (2010) is not right up against the y-axis. 但是,如果第一个柱(2010)没有正对着y轴,我宁愿这样做。
I have tried simply adding 1 to ind in both of plt1 and plt2 我试过在plt1和plt2中简单地添加1到ind
ie 即
p1 = plt.bar(ind+1, NonOECD, width, color = 'r')
p2 = plt.bar(ind+1, OECD, width, color = 'b', bottom = NonOECD)
But, I am unable to work out the equivalent change for the ticklabels. 但是,我无法确定ticklabels的等效变化。 So, thus far, all I produce is:
所以,到目前为止,我所生产的是:
Having said that, I can fudge this by making N = 8, adding an additional zero first term in both the tuples? 话虽如此,我可以通过使N = 8来捏造这个,在两个元组中增加额外的零第一项? OECD and NonOECD and adding a blank xticklabel:
OECD和NonOECD并添加空白xticklabel:
ie 即
N = 8
OECD = (0, 242, 244, 255, 263, 269, 276, 285)
NonOECD = (0, 282, 328, 375, 417, 460, 501, 535)
Sum = (0, '524', '572', '630', '680', '729', '777', '820')
plt.xticks(ind+width/2., ('', '2010', '2015', '2020', '2025', '2030', '2035', 2040'))
However, I am unable to use this fudge as I want to display the totals on top of the stacks .... 但是,我无法使用这个软糖,因为我想在堆栈顶部显示总数....
You want to use the "margins" function. 您想使用“边距”功能。 Your code modified:
您的代码已修改:
fig = plt.figure()
ax = fig.add_subplot(111)
# the first argument is the margin of the x-axis, the second of the y-axis
ax.margins(0.04, 0)
p1 = ax.bar(ind, NonOECD, width, color = 'r')
p2 = ax.bar(ind, OECD, width, color = 'b', bottom = NonOECD)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.