简体   繁体   中英

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

I have a bar plot drawn in matplotlib as such: 条形图有问题

The x-ticks do not span the entire range of x axis. How do I make that happen?

My code is here:

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

Manual bar spacing

You can gain manual control over where the locations of your bars are positioned (eg spacing between them), you did that but with a dictionary - instead try doing it with a list of integers.

Import scipy

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

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

If you lack scipy and cannot be bothered to install it, this is what arange() produces:

In [5]: xticks_pos

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

Controlling the margins

Above deals with spacing between bars, and as @JoeKington mentioned in comments the other parts you can control (eg if you do not want to control spacing and instead want to restrict margins, etc.):

plt.axis('tight')

plt.margins(0.05, 0)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM