0
votes

I have a bar chart in Python on which I want to plot some other values (representing, for example the average values) as segments.

Consider the following code which plots a simple bar chart:

import matplotlib.pyplot as plt

h = plt.bar([0,1,2], [4,5,6],width=0.5)
plt.legend((h,), ("vals",))
plt.show()

This plots the following image:

following image

For each bar, I have an average value that I want to plot over the corresponding bar as a segment. The desired plot is something like the following:

enter image description here

How can I plot values over bars as segments in matplotlib?

1

1 Answers

2
votes

How about this?

import matplotlib.pyplot as plt

indices = [0, 1, 2]
values = [4, 5, 6]
averages = [3.5, 5.5, 4.75]
pad = 0.3

fig, ax = plt.subplots()

b = ax.bar(indices, values, width=0.5, label='vals')

for index, average in zip(indices, averages):
    l = ax.plot([index - pad, index + pad], [average, average], color='red')

ax.legend([b, l[0]], ['vals', 'avg'])

enter image description here