gpt4 book ai didi

python - 无法在 Jupyter QtConsole : No mappable was found . 中绘制颜色条 .. 错误

转载 作者:行者123 更新时间:2023-11-28 22:38:54 32 4
gpt4 key购买 nike

我看到以下示例同时绘制图像和颜色图:

enter image description here

代码:

imgplot = plt.imshow(lum_img)
plt.colorbar()

来自这里:http://matplotlib.org/users/image_tutorial.html

但是当我从控制台执行此操作时,我得到:

enter image description here

即图像立即显示,不等待第二个命令,第二个命令后出现以下错误:

RuntimeError: No mappable was found to use for colorbar creation. First define a mappable such as an image (with imshow) or a contour set (with contourf).

最佳答案

发生这种情况是因为您分别运行了这两个命令。

在第一个命令中,图像被创建并内联显示。然后图形对象被丢弃,不能再改变。

第二个命令现在适用于不包含图像的新图形。

有几种可能的解决方案:

示例1:普通模式

这将在单独的窗口中显示图形。所有操作都适用于同一个图形,该图形在使用 plt.show() 显示之前一直不可见。然后此函数会阻止脚本,直到图窗关闭。

In [1]: import matplotlib.pyplot as plt

In [2]: import matplotlib.image as mpimg

In [3]: img = mpimg.imread('/tmp/stinkbug.png')

In [4]: lum_img = img[:, :, 0]

In [5]: plt.imshow(lum_img)
Out[5]: <matplotlib.image.AxesImage at 0x7f1a24057748>

In [6]: plt.colorbar()
Out[6]: <matplotlib.colorbar.Colorbar at 0x7f1a24030a58>

In [7]: plt.show()

示例2:交互模式

这与示例 1 相同,但图形窗口会立即显示并通过连续的绘图调用进行更新。 (对我来说,这在 IPython 中有效,但我在 Jupyter QtConsole 中只得到一个黑色窗口。)

In [1]: import matplotlib.pyplot as plt

In [2]: import matplotlib.image as mpimg

In [3]: plt.ion()

In [4]: img = mpimg.imread('/tmp/stinkbug.png')

In [5]: lum_img = img[:, :, 0]

In [6]: plt.imshow(lum_img)
Out[6]: <matplotlib.image.AxesImage at 0x7f7f2061e9b0>

In [7]: plt.colorbar()
Out[7]: <matplotlib.colorbar.Colorbar at 0x7f7f20605128>

示例 3:内联绘图

如果你想要内联模式,你可以简单地在一个输入行中执行多个命令,就像这样。

enter image description here

示例 4:高级内联绘图

手动创建图形对象。对该对象执行操作(创建子图、绘制图像、添加颜色条)并随时通过在命令行中键入其名称来显示内联图形。

enter image description here

关于python - 无法在 Jupyter QtConsole : No mappable was found . 中绘制颜色条 .. 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35291301/

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