簡體   English   中英

Matplotlib:如何讓我的條形圖填充整個x軸?

[英]Matplotlib: How do I make my bar plot fill the entire x-axis?

我有一個在matplotlib中繪制的條形圖: 條形圖有問題

x-ticks不跨越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')

手動條間距

您可以手動控制條形位置的位置(例如它們之間的間距),您可以使用字典進行操作 - 而是嘗試使用整數列表。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM