我想创建一个动画图,可以使用滑块和其他小部件来控制参数。我必须创建几个相似的图形,因此我要将其打包在某个类中,以便与各种参数一起重用。但在此之前,我想弄清楚它的工作原理。
此代码将在图的上部创建一个图形,其余部分保留为空白。但是,x和y轴的绘制范围是[-0.05,0.05],而不是下面的预定义范围。
如何确定图形按所需比例绘制?
我不知道的另一件事是如何向布局添加小部件?我想将它们插入gridspec而不用硬编码坐标和尺寸,以使它们适应给定的空间。
我在下面尝试了一些方法,但是显然没有用。 我该如何使其按需运行?
import matplotlib.gridspec as gridspec
import numpy as np
from matplotlib import pyplot as plt
PI = np.pi
# Half width of the graph x-axis
x_axis = 4*PI
# x_axis offset
x_offset = 0
# Half height of the graph y-axis
y_axis = 8
# y_axis offset
y_offset = -1
fig = plt.figure()
mainGrid = gridspec.GridSpec(2, 1)
graphCell = plt.subplot(mainGrid[0, :])
graphCell.plot(xlim=(-x_axis-x_offset, x_axis-x_offset), ylim=(-y_axis-y_offset, y_axis-y_offset))
controlCell = mainGrid[1, :]
controlGrid = gridspec.GridSpecFromSubplotSpec(1, 7, controlCell)
sliderCell = controlGrid[0, 0]
sliderCount = 7
sliderGrid = gridspec.GridSpecFromSubplotSpec(sliderCount, 1, sliderCell)
sliders = []
for i in range(0, sliderCount):
pass
#sliders[i] = Slider(sliderGrid[0, i], "Test {}".format(i), 0.1, 8.0, valinit=2, valstep=0.01)
x_data = np.linspace(-x_axis-x_offset, x_axis-x_offset, 512)
y_data = [x for x in x_data]
line = plt.plot([], [])[0]
line.set_data(x_data, y_data)
plt.show()
答案 0 :(得分:2)
一些问题:
plot
没有任何xlim
参数。总共
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
from matplotlib.widgets import Slider
# Half width of the graph x-axis
x_axis = 4*np.pi
# x_axis offset
x_offset = 0
# Half height of the graph y-axis
y_axis = 8
# y_axis offset
y_offset = -1
fig = plt.figure()
mainGrid = gridspec.GridSpec(2, 1)
ax = plt.subplot(mainGrid[0, :])
ax.set(xlim=(-x_axis-x_offset, x_axis-x_offset), ylim=(-y_axis-y_offset, y_axis-y_offset))
controlCell = mainGrid[1, :]
sliderCount = 7
sliderGrid = gridspec.GridSpecFromSubplotSpec(sliderCount, 1, controlCell)
sliders = []
for i in range(0, sliderCount):
sliderax = plt.subplot(sliderGrid[i, 0])
slider = Slider(sliderax, "Test {}".format(i), 0.1, 8.0, valinit=2, valstep=0.01)
sliders.append(slider)
x_data = np.linspace(-x_axis-x_offset, x_axis-x_offset, 512)
y_data = [x for x in x_data]
line = ax.plot([], [])[0]
line.set_data(x_data, y_data)
plt.show()