Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib: How to get space between bars?

Hi I have started using matplotlib and have been trying to adapt the example code on the website to suit my needs. I have the code below which does what I want apart from the 3rd bar in each group overlaps the first of the next group of bars. Internet isnt good enough to add picture but any help would be great and if you could explain what my error is that would be appreciated.

Thanks, Tom

"""
Bar chart demo with pairs of bars grouped for easy comparison.
"""
import numpy as np
import matplotlib.pyplot as plt


n_groups = 3

means_e1 = (20, 35, 30)
std_e1 = (2, 3, 4)

means_e2 = (25, 32, 34)
std_e2 = (3, 5, 2)

means_e3 = (5, 2, 4)
std_e3 = (0.3, 0.5, 0.2)

fig, ax = plt.subplots()

index = np.arange(n_groups)
bar_width = 0.35

opacity = 0.4
error_config = {'ecolor': '0.3'}

rects1 = plt.bar(index , means_e1, bar_width,
                 alpha=opacity,
                 color='b',
                 yerr=std_e1,
                 error_kw=error_config,
                 label='Main')

rects2 = plt.bar(index + bar_width + 0.1, means_e2, bar_width,
                 alpha=opacity,
                 color='r',
                 yerr=std_e2,
                 error_kw=error_config,
                 label='e2')

rects3 = plt.bar(index + bar_width + bar_width + 0.2, means_e3, bar_width,
                 alpha=opacity,
                 color='g',
                 yerr=std_e3,
                 error_kw=error_config,
                 label='e3')

plt.xlabel('Dataset type used')
plt.ylabel('Percentage of reads joined after normalisation to 1 million reads')
plt.title('Application of Thimble on datasets, showing the ability of each stitcher option.')
plt.xticks(index + bar_width + bar_width, ('1', '2', '3'))
plt.legend()

plt.tight_layout()
plt.show()
like image 250
Tom Avatar asked Sep 11 '14 17:09

Tom


People also ask

How do I create a space between bars in Matplotlib?

The space between bars can be added by using rwidth parameter inside the “plt. hist()” function. This value specifies the width of the bar with respect to its default width and the value of rwidth cannot be greater than 1.

Which argument of bar () lets you set the thickness of bar?

The width of the bars can be controlled by width argument of the bar() function.


1 Answers

The bar_width + bar_width + 0.2 is 0.9. Now you add another bar of bar_width (0.35), so overall you have 1.25, which is greater than 1. Since 1 is the distance between subsequent points of the index, you have overlap.

You can either increase the distance between index (index = np.arange(0, n_groups * 2, 2)), or reduce the bar width to something smaller, say 0.2.

like image 174
Shashank Agarwal Avatar answered Oct 31 '22 17:10

Shashank Agarwal