我可以使用 Kivy 和 Matplotlib 很好地生成 2D 曲面图.我正在尝试在单击按钮时更新 Z 值.这如何实现?
I can generate a 2D surface plot very nicely with Kivy and Matplotlib. I am trying to update the Z values on a button click. How may this be accomplished?
我注意到我可以发出一个 plt.clf() 来清除绘图,但是执行 plt.gcf() 来显示当前绘图不起作用.
I noticed that I can issue a plt.clf() which will clear the plot but doing the plt.gcf() to display the current plot doesn't work.
任何建议将不胜感激.
import matplotlib
matplotlib.use('module://kivy.garden.matplotlib.backend_kivy')
from matplotlib.figure import Figure
from numpy import arange, sin, pi
from kivy.app import App
import numpy as np
from matplotlib.mlab import griddata
from kivy.garden.matplotlib.backend_kivy import FigureCanvas,
NavigationToolbar2Kivy
# from backend_kivy import FigureCanvasKivy as FigureCanvas
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.boxlayout import BoxLayout
from matplotlib.transforms import Bbox
from kivy.uix.button import Button
from kivy.graphics import Color, Line, Rectangle
import matplotlib.pyplot as plt
from matplotlib import cm
from mpl_toolkits.mplot3d import Axes3D
fig, ax = plt.subplots()
X = np.arange(-508, 510, 203.2)
Y = np.arange(-508, 510, 203.2)
X, Y = np.meshgrid(X, Y)
Z = np.random.rand(6, 6)
plt.contourf(X, Y, Z, 100, zdir='z', offset=1.0, cmap=cm.hot)
plt.colorbar()
ax.set_ylabel('Y [mm]')
ax.set_title('NAILS surface')
ax.set_xlabel('X [mm]')
canvas = fig.canvas
def callback(instance):
fig, ax = plt.subplots()
X = np.arange(-508, 510, 203.2)
Y = np.arange(-508, 510, 203.2)
X, Y = np.meshgrid(X, Y)
Z = np.random.rand(6, 6)
plt.contourf(X, Y, Z, 100, zdir='z', offset=1.0, cmap=cm.hot)
plt.colorbar()
ax.set_ylabel('Y [mm]')
ax.set_title('NAILS surface')
ax.set_xlabel('X [mm]')
canvas = fig.canvas
canvas.draw()
class MatplotlibTest(App):
title = 'Matplotlib Test'
def build(self):
fl = BoxLayout(orientation="vertical")
a = Button(text="press me", height=40, size_hint_y=None)
a.bind(on_press=callback)
fl.add_widget(canvas)
fl.add_widget(a)
return fl
if __name__ == '__main__':
MatplotlibTest().run()
代码第 45 行:
fig, ax = plt.subplots()
创建一个新图形,从而创建一个新画布.此画布从未添加到 BoxLayout
中,因此从未显示.重新使用旧画布可能是一个更好的主意.把回调函数改成这样:
creates a new figure and hence a new canvas. This canvas is never added to the BoxLayout
and hence never shown. It's probably a better idea to re-use the old canvas. Change the callback function to this:
def callback(instance):
# Clear the existing figure and re-use it
plt.clf()
X = np.arange(-508, 510, 203.2)
Y = np.arange(-508, 510, 203.2)
X, Y = np.meshgrid(X, Y)
Z = np.random.rand(6, 6)
plt.contourf(X, Y, Z, 100, zdir='z', offset=1.0, cmap=cm.hot)
plt.colorbar()
ax.set_ylabel('Y [mm]')
ax.set_title('NAILS surface')
ax.set_xlabel('X [mm]')
canvas.draw_idle()
这篇关于Kivy 和 Matplotlib 试图更新按钮回调的情节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!