Draw average line in subplot

Viewed 550

I want to draw an average line in my bar-graph subplot. I have simplified my case with just six data sets for high an low. For these values i create the average, which is easy (not shown in my example here to Keep it short).

But I cant find a way to integrate a line in my bar-graph which shows the average values for each bar.

import tkinter as Tk
import numpy as np

from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure

root = Tk.Tk()

f = Figure(figsize=(5,4), dpi=100)
ax = f.add_subplot(111)

high = (104, 109, 113, 111, 108, 114)
low = (95, 100, 109, 103, 103, 110)

ind = np.arange(6)  # the x locations for the groups
width = 0.35

rects1 = ax.bar(ind, high, width)
rects2 = ax.bar(ind, low, width)

ax.set_yticks(np.arange(90, 121, 2))
ax.set_ylim(bottom=90)

ax.legend((rects1[0], rects2[0]), ('High', 'Low'))

canvas = FigureCanvasTkAgg(f, master=root)
canvas.show()
canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)

Tk.mainloop()
1 Answers

You can use list comprehension to first compute the average of each set of low and high bars. Then you can plot it using a dotted line for example as shown below


average = [(h+l)/2. for h, l in zip(high, low)]

rects1 = ax.bar(ind, high, width)
rects2 = ax.bar(ind, low, width)
ax.plot(ind, average, '--k')

enter image description here

Related