matplotlib中颜色栏的更新范围 [英] Update range of colorbar in matplotlib

查看:56
本文介绍了matplotlib中颜色栏的更新范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想更新一个函数中的 contourf 图,该方法工作正常.但是,数据范围会发生变化,因此我还必须更新颜色栏.那是我做不到的地方.

I want to update a contourf plot within a function, which works fine. However, the range of the data changes and I therefore also have to update the colorbar. That is where I fail to do so.

请参阅以下最低工作示例:

Please see following minimum working example:

import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.add_subplot(111)

# Random data
data = np.random.rand(10, 10)

# Plot data
levels = np.linspace(0., 1., 100)
plot = ax.contourf(data, levels=levels)
clist = plot.collections[:]

# Create colorbar
cbar = plt.colorbar(plot)
cbar_ticks = np.linspace(0., 1., num=6, endpoint=True)
cbar.set_ticks(cbar_ticks)

plt.show()

def update():
    # Remove old plot
    for c in clist:
        ax.collections.remove(c)
        clist.remove(c)

    # Create new data and plot
    new_data   = 2.*np.random.rand(10, 10)
    new_levels = np.linspace(0., 2., 200)
    new_plot = ax.contourf(new_data, levels=new_levels )

    # Modify colorbar
    cbar.set_clim(0., 2.)
    new_cbar_ticks = np.linspace(0., 2., num=21, endpoint=True)
    cbar.set_ticks(new_cbar_ticks)

    plt.draw()

update()

不调用 update(),我得到以下图像:

Without calling update() I get the following image:

这正是我想要的.在 update()函数中,我基本上将数据范围从 [0,1)更改为 [0,2),创建新的数据,并更新绘图.我还尝试将色条刻度中的采样加倍,以使刻度间隔为0.1,而不是0.2.这就是我得到的:

This is exactly what I want. In the update() function I basically change the range of the data from [0,1) to [0,2), create new data, and update the plot. I also tried to double the sampling in the colorbar ticks to have ticks in an interval of 0.1, instead of 0.2. This is what I get:

数据已正确绘制,数据的颜色图正确,颜色栏中的刻度和颜色正确,但颜色栏的范围仍为0到1.如何更改颜色栏以显示颜色全范围最多2个?

The data is correctly plotted, the colormap of the data is correct, the ticks and the color in the colorbar are correct, but the range of the colorbar is still from 0 to 1. How can I change the colorbar to show the full range up to 2?

推荐答案

可以使用 imshow 代替 contour 吗?在这种情况下,只需同时更新绘图和颜色栏即可.

Can you work with imshow instead of contour? In that case it is easy to just update both, the plot and the colorbar.

import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.add_subplot(111)

# Random data
data = np.random.rand(10, 10)

# Plot data
plot = ax.imshow(data)


# Create colorbar
cbar = plt.colorbar(plot)
cbar_ticks = np.linspace(0., 1., num=6, endpoint=True)
cbar.set_ticks(cbar_ticks)

plt.show(block=False)

def update():

    new_data   = 2.*np.random.rand(10, 10)

    plot.set_data(new_data)
    cbar.set_clim(vmin=0,vmax=2)
    cbar_ticks = np.linspace(0., 2., num=11, endpoint=True)
    cbar.set_ticks(cbar_ticks) 
    cbar.draw_all() 
    plt.draw()

    plt.show()

update()

这篇关于matplotlib中颜色栏的更新范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆