下面的代码覆盖了两个imshow的曲线图,并创建了一个更改全局变量OPACITY的值的滑块.

不幸的是,img1.set_data(y); fig.canvas.draw_idle()不会重新绘制新的不透明度.

How to make an overlay of two 100 plots with a slider to change the opacity of the 2nd layer?

enter image description here

import numpy as np, matplotlib.pyplot as plt, matplotlib.widgets as mpwidgets

OPACITY = 0.5

x = np.random.random((100, 50))
y = np.linspace(0, 0.1, 100*50).reshape((100, 50))

# PLOT
fig, (ax0, ax1) = plt.subplots(2, 1, gridspec_kw={'height_ratios': [5, 1]})
img0 = ax0.imshow(x, cmap="jet")
img1 = ax0.imshow(y, cmap="jet", alpha=OPACITY)

def update(value): 
    global OPACITY
    OPACITY = value
    print(OPACITY)
    img1.set_data(y)
    fig.canvas.draw_idle()

slider0 = mpwidgets.Slider(ax=ax1, label='opacity', valmin=0, valmax=1, valinit=OPACITY)
slider0.on_changed(update)

plt.show()

推荐答案

您可以将update函数中覆盖img1的不透明度重新设置为img1.set_alpha():

enter image description here

enter image description here

Code:

import numpy as np, matplotlib.pyplot as plt, matplotlib.widgets as mpwidgets

OPACITY = 0.5

x = np.random.random((100, 50))
y = np.linspace(0, 0.1, 100*50).reshape((100, 50))

# PLOT
fig, (ax0, ax1) = plt.subplots(2, 1, gridspec_kw={'height_ratios': [5, 1]})
img0 = ax0.imshow(x, cmap="jet")
img1 = ax0.imshow(y, cmap="jet", alpha=OPACITY)


def update(value): 
    img1.set_alpha(value)    
    fig.canvas.draw_idle()

slider0 = mpwidgets.Slider(ax=ax1, label='opacity', valmin=0, valmax=1, valinit=OPACITY)
slider0.on_changed(update)

plt.show()

Python相关问答推荐

即使在可见的情况下也不相互作用

如何请求使用Python将文件下载到带有登录名的门户网站?

cv2.matchTemplate函数匹配失败

Scrapy和Great Expectations(great_expectations)—不合作

未知依赖项pin—1阻止conda安装""

用渐近模计算含符号的矩阵乘法

为什么np. exp(1000)给出溢出警告,而np. exp(—100000)没有给出下溢警告?

如何在PySide/Qt QColumbnView中删除列

Python—转换日期:价目表到新行

具有相同图例 colored颜色 和标签的堆叠子图

从源代码显示不同的输出(机器学习)(Python)

在numpy数组中寻找楼梯状 struct

递归函数修饰器

Django Table—如果项目是唯一的,则单行

如何将返回引用的函数与pybind11绑定?

Pythonquests.get(Url)返回Colab中的空内容

Pandas 删除只有一种类型的值的行,重复或不重复

如何在Polars中将列表中的新列添加到现有的数据帧中?

组颠倒大Pandas 数据帧

pyspark where子句可以在不存在的列上工作