【问题标题】:Creating a figure with plots, sliders and other widgets arranged with a gridspec layout创建一个图形,其中包含按 gridspec 布局排列的绘图、滑块和其他小部件
【发布时间】:2019-05-14 15:03:11
【问题描述】:

我想创建一个可以使用滑块和其他小部件控制参数的动画图表。我必须创建几个类似的图形,所以我想将它打包到某个类中,以便与各种参数一起重复使用。但在此之前,我想弄清楚它是如何工作的。

此代码将在图形的上部创建一个图形,并将其余部分留空。但是,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()

【问题讨论】:

    标签: python python-3.x matplotlib matplotlib-widget


    【解决方案1】:

    一些问题:

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

    【讨论】:

    • 谢谢你,你救了我。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多