【发布时间】:2021-10-14 06:11:36
【问题描述】:
假设我想通过读取三个 .xlsx 文件来显示三个模拟。 接下来,我想设计一个滑块来选择要显示的模拟。 如果我将滑块移动到 0,那么 0 将是函数“update()”的输入。将显示第一个模拟。
以下是代码:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.widgets import Slider
import pandas as pd
import ipywidgets as wg
# input files
rm = pd.read_excel("test_3d.xlsx", header = None)
rm1 = pd.read_excel("test_3d1.xlsx", header = None)
rm2 = pd.read_excel("test_3d2.xlsx", header = None)
rec = np.shape(rm)
X = np.arange(1,rec[1]+1,1)
Y = np.arange(1,rec[0]+1,1)
x , y = np.meshgrid(X,Y)
# Set 3D plots
fig = plt.figure()
ax1 = fig.add_axes([0, 0, 1, 0.8], projection = '3d')
# Choose which 3D plots to show
def update(val):
if val == 0:
ax1.cla()
ax1.plot_surface(x, y, rm, cmap = cm.coolwarm, linewidth = 0, antialiased = False)
elif val == 1:
ax1.cla()
ax1.plot_surface(x, y, rm1, cmap = cm.coolwarm, linewidth = 0, antialiased = False)
elif val == 2:
ax1.cla()
ax1.plot_surface(x, y, rm2, cmap = cm.coolwarm, linewidth = 0, antialiased = False)
ax1.set_zlim(-110, -80)
# Design a slider to choose which simulation to show
slider = wg.IntSlider(value=1, min=0, max=2, description='this is slider')
slideroutput = wg.Output()
display(slider, slideroutput)
numberonslider = []
def on_value_change(change):
with slideroutput:
numberonslider.append(change['new'])
print(numberonslider[-1])
ddd = slider.observe(on_value_change, names='value')
update(ddd)
如果我移动滑块,“ddd”会给你一个 0、1 或 2 的列表。
但是,3D 模拟没有出现。如何修改代码?
【问题讨论】:
-
您的 IDE 是否允许您拥有 matplotlib 动画?例如 Jupyter 需要
%matplotlib widget或%matplotlib inline导入才能工作 -
@Karina 是的,我刚刚修改了我的代码。
标签: python matplotlib 3d slider