Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove empty "padding" in matplotlib barh plot?

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: enter image description here

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})
like image 884
minerals Avatar asked Feb 05 '16 13:02

minerals


People also ask

How do I remove the space between bars in Matplotlib?

To remove gaps between bars, we can change the align value to center in the argument of bar() method.

What is padding in Matplotlib?

pad: This parameter is used for padding between the figure edge and the edges of subplots, as a fraction of the font size. h_pad, w_pad: These parameter are used for padding (height/width) between edges of adjacent subplots, as a fraction of the font size.

What is the role of Barh () function in Matplotlib library?

barh() Function. The Axes. barh() function in axes module of matplotlib library is used to make a horizontal bar plot.


1 Answers

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)
like image 55
tmdavison Avatar answered Oct 08 '22 05:10

tmdavison