我一直在玩matplotlib
,因为我正在学习它。所以我创建了一个带有一些值的字典,并尝试了不同的东西。目前我对滑块和不透明度有点困惑。在我的代码中,除了滑块之外,实际上存在几个问题。但这个问题是关于滑块的。
第一个错误:必须有三个滑块 - >有一个 第二个错误:不透明度不会更新。
你能解释一下(我的意思是代码有什么问题)是错误并帮助修复它们吗?
import matplotlib.pyplot as plt
from matplotlib.widgets import CheckButtons
import numpy as np
from matplotlib.pyplot import cm
from numpy.random import random
from matplotlib.widgets import Slider
dictFruit = {'apple' : [list(random(2)), list(random(2)), list(random(2))], 'pear' : [list(random(2)), list(random(2)), list(random(2))], 'cherry' : [list(random(2)), list(random(2)), list(random(2))]}
color=iter(cm.rainbow(np.linspace(0,1,len(dictFruit))))
allKeys = dictFruit.keys()
print('ALL MY KEYS', allKeys)
allItems = {}
opacityFruit = 0
fig = plt.figure(1)
ax = fig.add_subplot(111)
#NON-PLOT ELEMENTS
rax = plt.axes([0.15, 0.4, 0.1, 0.15])
sliderBox = plt.axes([0.15, 0.025, 0.65, 0.03])
### SLIDERS
def update(val):
opacity = opacitySlide.val
print('NEW OPACITY VALUE', opacity)
plt.draw()
return opacity
for item in allKeys:
opacitySlide = Slider(sliderBox, 'Opacity', 0.0, 1.0, valinit=1.0)
opacitySlide.on_changed(update)
op = update(0.5)
colorDictAll = {}
for fruit in dictFruit:
c=next(color)
colorDictAll[fruit] = c
print(dictFruit[fruit])
xAll = []
yAll = []
for idx, item in enumerate(dictFruit[fruit]):
x = item[0]
y = item[1]
xAll.append(x)
yAll.append(y)
curIt = ax.scatter(xAll, yAll, c = c, label = fruit, s = 100.0, alpha=update(1))
print(curIt)
allItems[fruit] = curIt
print(allItems)
print('CURRENT ITEMS')
print(allItems)
#CHECK BUTTONS
check = CheckButtons(rax, ('apple', 'pear', 'cherry'), (True, True, True))
def func(label):
for fruit in allKeys:
if label == fruit:
allItems[fruit].set_visible(not allItems[fruit].get_visible())
plt.draw()
for rec in check.rectangles:
idx = check.rectangles.index(rec)
print(idx)
print('REC', rec)
currentFruit = allKeys[idx]
currentFruitColor = colorDictAll[currentFruit]
rec.set_facecolor(currentFruitColor)
check.on_clicked(func)
plt.legend()
plt.show()