在子图中绘制平均线

时间:2019-01-15 12:32:49

标签: python matplotlib tkinter subplot

我想在条形图子图中绘制一条平均线。我只用了六个数据就简化了我的案例。对于这些值,我创建了平均值,这很容易(此处为了简短起见,此处未显示)。

但是我找不到在条形图中整合一条线的方法,该条显示每个条的平均值。

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 个答案:

答案 0 :(得分:2)

您可以使用列表推导来首先计算每组低和高柱线的平均值。然后,您可以使用虚线绘制它,例如,如下所示


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