问题描述
我正在处理级联图(中的内容这种样式)使用matplotlib.我想使所有宽度不同的条相互齐平,但我希望底部的刻度线从1到7定期增加,而与条无关.但是,此刻,它看起来像这样:
I'm working on a cascade chart (something in this style) using matplotlib. I'd like to get all of my bars of varying widths flush with each other, but I'd like the ticks at the bottom to increase regularly from 1 to 7, independent of the bars. However, at the moment, it looks like this:
到目前为止,这是我所拥有的:
So far this is what I've got:
python
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator, FormatStrFormatter
n_groups = 6
name=['North America','Russia','Central & South America','China','Africa','India']
joules = [33.3, 21.8, 4.22, 9.04, 1.86, 2.14]
popn=[346,143,396,1347,1072,1241]
fig, ax = plt.subplots()
index = np.arange(n_groups)
bar_width = [0.346,.143,.396,1.34,1.07,1.24]
opacity = 0.4
rects1 = plt.bar(index+bar_width, joules, bar_width,
alpha=opacity,
color='b',
label='Countries')
def autolabel(rects):
# attach some text labels
for ii,rect in enumerate(rects):
height = rect.get_height()
ax.text(rect.get_x()+rect.get_width()/2., 1.05*height, '%s'%(name[ii]),
ha='center', va='bottom')
plt.xlabel('Population (millions)')
plt.ylabel('Joules/Capita (ten billions)')
plt.title('TPEC, World, 2012')
plt.xticks(1, ('1', '2', '3', '4', '5','6')
autolabel(rects1)
plt.tight_layout()
plt.show()
到目前为止,我尝试过的所有调整条间距的变化都导致了类似的问题.有任何想法吗?
And all the variations I've tried so far to adjust the bar spacing have resulted in similar issues. Any ideas?
推荐答案
目前的问题是您的index
是规则序列,因此每个小节的左边缘均以规则间隔定位.您想要的是index
作为小节x值的连续总计,以便每个小节的左边缘与上一个小条的右边缘对齐.
At the moment the problem is that your index
is a regular sequence, so the left hand edges of each bar are positioned at regular intervals. What you want is for index
to be a running total of the bar x-values, so that the left hand edge of each bar lines up with the right hand edge of the previous one.
您可以使用np.cumsum()
:
...
index = np.cumsum(bar_width)
...
现在index
将以bar_width[0]
开始,因此您需要将条形图的左边缘设置为index - bar_width
:
Now index
will start at bar_width[0]
, so you'll need to set the left hand edge of the bars to index - bar_width
:
rects1 = plt.bar(index-bar_width, ...)
结果:
当然,您需要尝试使用轴限制和标签位置以使其看起来不错.
You'll of course want to play around with the axis limits and label positions to make it look nice.
这篇关于如何在matplotlib中独立于刻度线设置条宽度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!