0

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 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.