I'm new to Python and I'm trying to plot some data with the help of matplotlib.
I'm trying to group the data but the problem is that the groups overlap each other. Here is a picture which describes my problem: Problem

Here is my code:
import numpy as np
import matplotlib.pyplot as plt
n_groups = 3
credits = (market[0], market[1], market[2])
debits = (dmarket[0], dmarket[1], dmarket[2])
profits = (pmarket[0], pmarket[1], pmarket[2])
fig, ax = plt.subplots()
index = np.arange(n_groups)
bar_width = 0.45
opacity = 0.4
error_config = {'ecolor': '0.3'}
rectsCredits = plt.bar(index, credits, bar_width,
alpha=opacity,
color='b',
error_kw=error_config,
label='Credit')
rectsDebits = plt.bar(index + bar_width, debits, bar_width,
alpha=opacity,
color='r',
error_kw=error_config,
label='Debit')
rectsProfits = plt.bar(index + 2*bar_width, profits, bar_width,
alpha=opacity,
color='g',
error_kw=error_config,
label='Profits')
plt.xticks(index + bar_width/2, ('Tariff Market', 'Wholesale Market', 'Balancing Market'))
plt.legend()
plt.tight_layout()
def autolabel(rects):
"""
Attach a text label above each bar displaying its height
"""
for rect in rects:
height = rect.get_height()
ax.text(rect.get_x() + rect.get_width() / 2.,
1.01 * height,
'%d' % int(height),
ha='center', va='bottom')
autolabel(rectsCredits)
autolabel(rectsDebits)
autolabel(rectsProfits)
plt.show()
I don't know what to do. I think there is only a little logic problem which I don't see right now!
The position of the bars is a bit off. You insert the first label group at [0, 1, 2] (index), the second on [0.45, 1.45, 2.45] (index + bar_width) and the third at [0.9, 1.9, 2.9] (index + 2*bar_width). Each bar has a width of 0.45 so no wonder these overlap.
For the following part I chose just some data for visualization, you have to insert or use the correct values.
If you change bar_width to 1/3 then there's no empty space between the groups:
bar_width = 1 / 3

If you choose something like 1/4 then it will have exactly the space for one additional bar between each group:
bar_width = 1 / 4

But the label isn't centered correctly yet, but that can be easily fixed by using a new index in plt.xticks:
bar_width = 1 / 4
plt.xticks(index + bar_width, ('Tariff Market', 'Wholesale Market', 'Balancing Market'))

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With