Reputation: 336
I use the following code to generate the following image.
import numpy as np
import matplotlib.pyplot as plt
labels = ['G1', 'G2']
men_means = [20, 35]
women_means = [25, 32]
men_std = [2, 3]
women_std = [3, 5]
width = 0.25 # the width of the bars: can also be len(x) sequence
fig, ax = plt.subplots()
ax.bar(labels, men_means, width, yerr=men_std, label='Men')
ax.bar(labels, women_means, width, yerr=women_std, bottom=men_means,
label='Women')
ax.set_ylabel('Scores')
ax.set_title('Scores by group and gender')
ax.legend()
plt.show()
The two bars are too far from each other. How can I make them come closer but still be centered? Can I add some padding on the left and right?
Upvotes: 0
Views: 1211
Reputation: 908
You can manually set the positions of the bars in the x axis. You then have to add the tick labels manually:
import numpy as np
import matplotlib.pyplot as plt
men_means = [20, 35]
women_means = [25, 32]
men_std = [2, 3]
women_std = [3, 5]
width = 0.25 # the width of the bars: can also be len(x) sequence
fig, ax = plt.subplots()
# Define positions for each bar... just random here
# Change the 2nd argument to move bars around; play with bar widths also
positions = (0.5, 0.8)
# Here the first argument is the x position for the bars
ax.bar(positions, men_means, width, yerr=men_std, label='Men')
ax.bar(positions, women_means, width, yerr=women_std, bottom=men_means,
label='Women')
# Now set the ticks and the corresponding labels
labels = ('G1', 'G2')
plt.xticks(positions, labels)
ax.set_ylabel('Scores')
ax.set_title('Scores by group and gender')
ax.legend()
plt.show()
Result:
You can play around with the bar widths and the 2nd argument in positions
to get the distance you'd like.
Upvotes: 1
Reputation: 150725
Increase the width
?
width = 0.6 # the width of the bars: can also be len(x) sequence
Output:
Upvotes: 0