gpt4 book ai didi

python - Kivy 和 Matplotlib 尝试更新按钮回调的绘图

转载 作者:太空宇宙 更新时间:2023-11-04 05:26:07 26 4
gpt4 key购买 nike

我可以使用 Kivy 和 Matplotlib 非常好地生成 2D 表面图。我正在尝试通过单击按钮更新 Z 值。如何实现?

我注意到我可以发出一个 plt.clf() 来清除绘图,但是执行 plt.gcf() 来显示当前绘图不起作用。

如有任何建议,我们将不胜感激。

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

创建一个新图形,从而创建一个新 Canvas 。此 Canvas 永远不会添加到 BoxLayout 中,因此永远不会显示。重新使用旧 Canvas 可能是一个更好的主意。将回调函数更改为:

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

关于python - Kivy 和 Matplotlib 尝试更新按钮回调的绘图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38624168/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com