Stamatis Tiniakos
Stamatis Tiniakos

Reputation: 853

How to add a forth bar on a group barchart using matplotlib and seaborn in Python?

I am trying to create a group barchart to show the accuracy, precision, recall and f1 scores achieved by different machine learning classifiers. The group bar chart works ok when I use three bars per classifier but it looks strange when I add a forth one. Specifically, the gap between the bars disappears and the forth bar overlaps with other bars. This is how it looks when I use three bars:

enter image description here

and this is how it looks when I try to add a forth one:

enter image description here

N = 9
ind = np.arange(N)  # location of groups
width = 0.27       # width of bars

fig = plt.figure()
ax = fig.add_subplot(111)

rects1 = ax.bar(ind, Precision, width, color='r')

rects2 = ax.bar(ind+width, Recall, width, color='g')

rects3 = ax.bar(ind+width*2, F1, width, color='b')

rects4 =  ax.bar(ind+width*3, Accuracy, width, color='y')

ax.set_ylabel('Scores')
ax.set_xticks(ind+width)
ax.set_xticklabels(Model,rotation=90)
ax.legend( (rects1[0], rects2[0], rects3[0]), ('Precision', 'Recall','F1 Score') )

def autolabel(rects):
    for rect in rects:
        h = rect.get_height()
        ax.text(rect.get_x()+rect.get_width()/2., 1.05*h, '%d'%int(h*100),
                ha='center', va='bottom')

autolabel(rects1)
autolabel(rects2)
autolabel(rects3)
autolabel(rects4)

fig_size = plt.rcParams["figure.figsize"]
fig_size[0] = 20
fig_size[1] = 15
plt.rcParams["figure.figsize"] = fig_size

plt.show()

I am new to Python so any help will be much appreciated.

Upvotes: 1

Views: 1152

Answers (1)

Sheldore
Sheldore

Reputation: 39072

The problem is that your current spacing is 0.27. When you have 4 bars, this results in 0.27*4 = 1.08 spacing, whereas the corresponding bars are spaced at a distance of 1. As a result, your bars start to overlap.

One hardcoded solution is to replace 0.27 by something smaller such as 0.2. This will leave a spacing of 1-0.2*4 = 0.2 between the adjacent bars.

Other smart solution would be to compute the spacing depending on the number of bars using something like spacing = 1/(nbars+1) where +1 is to add extra space

P.S: Python 2 users as pointed out by @Leporello

Use spacing = 1.0/(nbars+1)

Upvotes: 2

Related Questions