Matplotlib:如何使我的条形图填满整个X轴?

3

我用matplotlib画了一个条形图,如下所示: 带问题的条形图

我的x轴刻度没有覆盖整个x轴范围。我该怎么做才能实现这一点?

我的代码在这里:

def counter_proportions(counter):
    total = sum(counter.values())

    proportions = dict()
    for key, value in counter.items():
        proportions[key] = float(value)/float(total)

    return proportions

def categorical_counter_xlabels(counter):
    idxs = dict()

    for i, key in enumerate(counter.keys()):
        idxs[key] = i

    return idxs

# Use this dummy data
detailed_hosts = ['Species1' * 3, 'Species2' * 1000, 'Species3' * 20, 'Species4' * 20]
# Create a detailed version of the counter, which includes the exact species represented.
detailed_hosts = []

counts = Counter(detailed_hosts)
props = counter_proportions(counts)
xpos = categorical_counter_xlabels(counts)

fig = plt.figure(figsize=(16,10))
ax = fig.add_subplot(111)
plt.bar(xpos.values(), props.values(), align='center')
plt.xticks(xpos.values(), xpos.keys(), rotation=90)
plt.xlabel('Host Species')
plt.ylabel('Proportion')
plt.title("Proportion of Reassortant Viruses' Host Species")
plt.savefig('Proportion of Reassortant Viruses Host Species.pdf', bbox_inches='tight')

1
我正在处理一些图形数据,这些数据是预先提供的。在我能够生成“重新组合病毒”列表之前,需要执行许多步骤。 - ericmjl
1
基于 matplotlib API,如何确保居中对齐的条形图填满 x轴?我在API文档中没有找到答案,所以想在这里问一下。 - ericmjl
1
数据非常宝贵,所以我现在不能发布原始数据。 - ericmjl
1
没时间给出完整的答案,但简短的回答是 plt.axis('tight')plt.margins(0.05, 0)。如果需要更多控制,你可以根据数据手动设置坐标轴的 x 轴限制(例如 plt.xlim(x.min() - width, x.max() + width))。 - Joe Kington
@JoeKington,如果您稍后有时间发布完整答案,我会接受它 :) - ericmjl
显示剩余2条评论
1个回答

2

手动设置栏间距

您可以手动控制栏的位置(例如,它们之间的间距),您可以使用字典实现此功能 - 不过建议尝试使用整数列表来完成。

Import scipy

xticks_pos = scipy.arange( len( counts.keys() )) +1

plt.bar( xticks_pos, props.values(), align='center')

如果您没有安装scipy或者不想安装它,那么arange()函数将会产生以下结果:
In [5]: xticks_pos

Out[5]: array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10])

控制边距

上文提到了间隔问题,正如@JoeKington在评论中提到的,您还可以控制其他部分(例如,如果您不想控制间距而是想限制边距等):

plt.axis('tight')

plt.margins(0.05, 0)

plt.xlim(x.min() - width, x.max() + width))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接