从matplotlib.widgets使用滑块后,如何获得条形图值?

时间:2019-03-12 06:41:58

标签: python matplotlib slider bar-chart

我有一个条形图,其中有坏的(即负数)和好的值(即正数)。这些值由阈值决定。请参阅Postive_Negative_Circles

条形图输出为Bar_Chart

显示为:不良= 3472,良好= 664,阈值= 164.094

如果我更改阈值,则这些值应更改。到目前为止,这是我所做的:

import matplotlib.pyplot as plt
import pylab as p
from matplotlib.widgets import Slider, Button

axcolor = 'lightgoldenrodyellow'
axthreshold = plt.axes([0.2, 0.001, 0.65, 0.03], facecolor=axcolor)
sthreshold = Slider(axthreshold, 'Threshold', 0.0, 300, 
                    valinit=threshold, valstep=None)

fig_text1 = p.figtext(0.5, 0.65,  str(sthreshold.val))
def update(val):
    thresh = int(sthreshold.val)
    data = [np.sum(values <= thresh), np.sum(values > thresh)]
    ax.clear ()
    ax.bar(labels, data, color=colors)
    np.set_printoptions(precision=2)
    fig_text1.set_text(str(sthreshold.val))

    fig.canvas.draw_idle()

sthreshold.on_changed(update)
resetax = plt.axes([0.7, 0.001, 0.1, 0.04])
button = Button(resetax, 'Reset', color=axcolor, hovercolor='0.975')

def reset(event):
    sthreshold.reset()

button.on_clicked(reset)

上面的代码工作正常,条形图也发生了变化,但是不幸的是,在Slider更新后,我无法显示条形图的值。我只能显示阈值。

现在,我已使用matplotlib中的Slider小部件将阈值设置为114.24,条形图应显示值:好= 2543和坏=1593。如您所见,显示阈值,但不显示条形图值

Bar_Chart_after_Changed_Threshold

请忽略滑块顶部的“重置”按钮。我试图更改“重置”按钮的位置,但不起作用。我猜%matplotlib笔记本有问题。

有人可以帮我吗?我在网上寻找解决方案(例如matplotlib演示或StackOverflow等),但找不到我想要的东西。条形图在Slider更新中很少有StackOverflow问题,但没有人谈论条形图的值。另外,如果您需要有关代码的更多信息,请告诉我。

如果您知道任何好的来源或解决方案,请告诉我。谢谢

更新:

这是我尝试过的方法,它不起作用:

def update(val):
    thresh = int(sthreshold.val)
    print(thresh)
    data = [np.sum(values <= thresh), np.sum(values > thresh)]
    ax.clear ()
    bars = ax.bar(labels, data, color=colors)

    for rect in bars:
        height = rect.get_height()
        plt.text(rect.get_x() + rect.get_width()/2.0, height, '%d' % 
                   int(height), ha='center', va='bottom')

   np.set_printoptions(precision=2)
   fig_text1.set_text(str(sthreshold.val))

   fig.canvas.draw_idle()

1 个答案:

答案 0 :(得分:1)

import matplotlib.pyplot as plt
from matplotlib.widgets import Slider

fig,ax = plt.subplots()

labels = ['good','bad']
colors = ['C0','C1']
values = np.random.normal(0,1,size=(1000,))
threshold = 0.

axcolor = 'lightgoldenrodyellow'
axthreshold = plt.axes([0.2, 0.001, 0.65, 0.03], facecolor=axcolor)
sthreshold = Slider(axthreshold, 'Threshold', -1., 1., 
                    valinit=threshold, valstep=None)


def update(val):
    data = [np.sum(values <= val), np.sum(values > val)]
    ax.clear()
    ax.bar(labels, data, color=colors)
    thr_txt = ax.text(0.5, 0,  '{:.2f}'.format(val))
    good_label = ax.text(0,data[0], 'good={:d}'.format(data[0]), ha='center')
    bad_label = ax.text(1,data[1], 'bad={:d}'.format(data[1]),ha='center')
    fig.canvas.draw_idle()
sthreshold.on_changed(update)
update(threshold)

enter image description here