【问题标题】:Draw average line in subplot在子图中绘制平均线
【发布时间】:2019-06-09 11:17:38
【问题描述】:

我想在我的条形图子图中画一条平均线。我已经简化了我的案例,只使用了六个高低数据集。对于这些值,我创建平均值,这很容易(在我的示例中未显示以保持简短)。

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

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()

【问题讨论】:

    标签: python matplotlib tkinter subplot


    【解决方案1】:

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


    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')
    

    【讨论】:

    • 非常感谢,一切正常。但我还不够准确。我希望这条线连接到条形图中每个条的每个平均值。对此感到抱歉。我如何做到这一点?
    • 每个平均值是指每组柱的最低价和最高价的平均值?
    • 完美!非常感谢!
    • @K-Doe:检查我编辑的答案。希望这是你想要的。很高兴能提供帮助。
    猜你喜欢
    • 2013-04-17
    • 2018-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-01
    • 2022-01-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多