Reputation: 135
My DF looks like this:
ID Ctg Value_1 Result_1 Result_2 Result_3
1 Car 0.5 100 105 80
2 Bike 0.35 200 150 130
3 Plane 0.51 45 70 77
4 Car ... ... ... ...
5 Plane ... ... ... ...
6 Plane ... ... ... ...
7 Bike ... ... ... ...
8 Car ... ... ... ...
9 Car ... ... ... ...
distinct_Ctg = data.Ctg.unique()
for loop_count, i in enumerate(distinct_Ctg):
# Subset for each category
data_graph_sub = data.loc[data['Ctg'] == i]
X = np.arange(len(data_graph_sub ))
fig = plt.figure()
ax = fig.add_axes([0,0,1,1])
ax.set_facecolor('#E6E6E6')
bar_1 = ax.bar(X - 0.25, data_graph_sub['Result_1'], color = 'steelblue', width = 0.25)
bar_2 = ax.bar(X, data_graph_sub['Result_2'], color = 'orange', width = 0.25)
bar_3 = ax.bar(X + 0.25, data_graph_sub['Result_3'], color = 'indianred', width = 0.25)
plt.ylabel('Unit')
plt.title(i +': This is my title')
plt.grid(color='w', linestyle='solid')
for spine in ax.spines.values():
spine.set_visible(False)
ax.set_axisbelow(True)
ax.set_xticks(X)
ax.set_xticklabels(data_graph_sub.ID, rotation = 40, fontsize = 'small', ha = 'right')
ax.xaxis.tick_bottom()
ax.yaxis.tick_left()
blue_patch = mpatches.Patch(color='steelblue', label='Result from Programm 1')
green_patch = mpatches.Patch(color='orange', label='Result from Programm 2')
red_patch = mpatches.Patch(color='indianred', label='Result from Programm 3')
plt.legend(handles = [blue_patch, green_patch, red_patch])
# plt.show()
plt.savefig(r'graphs/' + str(loop_count) + '.png', bbox_inches='tight', pad_inches=0)
With this I create one figure for each type in Ctg and the results look good to me so far.
I'd now like to add Value_1 from my DF to one of the three bars (to the steelblue bar coming from data_graph_sub['Result_1']) like here: https://matplotlib.org/3.1.1/gallery/lines_bars_and_markers/barchart.html, but in this example the value is the height of the bar and it's plotted to all bars.
How can i realize this?
EDIT: I added this, but it's not correct yet...
for z in bar_1:
plt.text(z.get_x(), z.get_height(), data_graph_sub['Value_1'], size = 10)
How can I link the specific bar to the correct value in data_graph_sub['Value_1']?
Upvotes: 0
Views: 33
Reputation: 80554
With zip you can loop simultaneously through the bars and values:
for bar, val in zip(bar_1, data_graph_sub['Value_1']):
ax.text(bar.get_x() + bar.get_width()/2, bar.get_height(), f'{val:0.2f}\n',
size=10, ha='center', va='center')
Upvotes: 1