如何实现滑块小部件,matplotlib

问题描述 投票:1回答:1

这是我的代码。拜托,我无法实现滑块。当我更改“ y”时,条形图中的列应更改其颜色,水平线也应更改其位置。我试过使用一个函数,但没有任何反应。请帮助

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors
from matplotlib.widgets import Slider
%matplotlib notebook

np.random.seed(12345)

df = pd.DataFrame([np.random.normal(32000,200000,3650), 
               np.random.normal(43000,100000,3650), 
               np.random.normal(43500,140000,3650), 
               np.random.normal(48000,70000,3650)], 
              index=[1992,1993,1994,1995])


y = 40000

mean = list(df.mean(axis=1))
std = list(df.std(axis=1))
variance = [1.96*(std[i]/len(df.T)**0.5) for i in range(len(df))]

#figure
fig, ax = plt.subplots()
plt.subplots_adjust(left=0.25, bottom=0.2)
barplot = plt.bar(list(df.index), mean, yerr=variance)
plt.xticks(list(df.index))

#adding hline
ax.axhline(y=y, color = 'black')
ax.text(1995.68, y, '{}'.format(y), va='center', ha="left", bbox=dict(facecolor="w",alpha=0.5))

#changing colors
bars = barplot.get_children()
for bar, mean, var in zip(bars, mean, variance):
    bar.set_color(((y<mean), 0, (y>mean), min(1, abs(y-mean)/var)))
    bar.set_edgecolor('black')

#slider
slider = plt.axes([0.25, 0.1, 0.65, 0.03], facecolor = 'lightgoldenrodyellow')
slider_y = Slider(slider,
                label='y',
                valmin=0.0,
                valmax=50000,
                valinit=40000,
                valfmt='%1.0f')

“截图”

python-3.x matplotlib
1个回答
0
投票

由于您正在笔记本中进行编辑,因此建议您实施ipywidgets

ipywidgets

这应该起作用!

© www.soinside.com 2019 - 2024. All rights reserved.