Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/windows/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在matplotlib中设置独立于刻度的条形宽度?_Python_Graph_Matplotlib_Spacing - Fatal编程技术网

Python 如何在matplotlib中设置独立于刻度的条形宽度?

Python 如何在matplotlib中设置独立于刻度的条形宽度?,python,graph,matplotlib,spacing,Python,Graph,Matplotlib,Spacing,我正在使用matplotlib制作级联图(中的某些内容)。我想让所有不同宽度的条彼此齐平,但我希望底部的刻度有规律地从1增加到7,与条无关。然而,目前看起来是这样的: 到目前为止,我得到的是: python import numpy as np import matplotlib.pyplot as plt from matplotlib.ticker import MultipleLocator, FormatStrFormatter n_groups = 6 name=['North

我正在使用matplotlib制作级联图(中的某些内容)。我想让所有不同宽度的条彼此齐平,但我希望底部的刻度有规律地从1增加到7,与条无关。然而,目前看起来是这样的:

到目前为止,我得到的是:

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()

到目前为止,我尝试调整棒间距的所有变化都导致了类似的问题。有什么想法吗

目前的问题是,您的
索引是一个规则序列,因此每个条的左边缘都是按规则间隔定位的。您需要的是将
索引
作为条形图x值的运行总和,以便每个条形图的左边缘与上一条条形图的右边缘对齐

您可以使用
np.cumsum()
执行此操作:

现在,
索引
将从
条形宽度[0]
开始,因此需要将条形的左边缘设置为
索引-条形宽度

rects1 = plt.bar(index-bar_width, ...)
结果:


当然,您会想通过调整轴限制和标签位置使其看起来更美观。

去除记号,只需使用
text
annotate
添加标签即可。您也可以使用
align='center'
rects1 = plt.bar(index-bar_width, ...)