Reputation: 6548
I want to remove/reduce the empty top and bottom padding
space (marked with red squares) in the matplotlib.pyplot.barh
plot. How can I do it?
Here is an example of my plot:
Here is the code:
import matplotlib.pyplot as plt
from collections import Counter
import random
values = sorted(tags_dic.values())
labels = sorted(tags_dic, key=tags_dic.get)
bars = plt.barh(range(len(tags_dic)), values, align='center')
plt.yticks(range(len(tags_dic)), labels)
plt.xlabel('Count')
plt.ylabel('POS-tags')
plt.grid(True)
random.shuffle(COLLECTION)
for i in range(len(tags_dic)):
bars[i].set_color(COLLECTION[i])
print COLLECTION[i]
plt.show()
Random test data:
tags_dic = Counter({u'NNP': 521, u'NN': 458, u'IN': 450, u'DT': 415, u'JJ': 268, u'NNS': 244, u'VBD': 144, u'CC': 138, u'RB': 103, u'VBN': 98, u'VBZ': 69, u'VB': 65, u'TO': 64, u'PRP': 57, u'CD': 51, u'VBG': 50, u'VBP': 48, u'PRP$': 26, u'POS': 26, u'WDT': 20, u'WP': 20, u'MD': 19, u'EX': 11, u'WRB': 10, u'JJS': 7, u'RP': 6, u'JJR': 6, u'RBR': 5, u'NNPS': 5, u'FW': 4, u'SYM': 1, u'UH': 1})
Upvotes: 14
Views: 4150
Reputation: 69164
You can control this with plt.margins
. To completely remove the whitespace at the top and bottom, you can set:
plt.margins(y=0)
As an aside, I think you also have an error in your plotting script: you sort the values from your dictionary, but not the keys, so you end up with labels that don't correspond to the value they represent.
I think you can fix this as follows:
labels = sorted(tags_dic, key=tags_dic.get)
plt.yticks(range(len(tags_dic)), labels)
Upvotes: 19