从matplotlib中的数字中删除colorbar

Ada*_*ser 24 python matplotlib colorbar

这应该很容易,但我很难用它.基本上,我在matplotlib中有一个子图,我在每次调用函数时都会绘制一个hexbin图,但每次调用该函数时我都会得到一个新的颜色条,所以我真正想做的就是更新colorbar .不幸的是,这似乎不起作用,因为colorbar附加的对象正在由subplot.hexbin重新创建.

def foo(self):
   self.subplot.clear()
   hb = self.subplot.hexbin(...)
   if self.cb:
      self.cb.update_bruteforce() # Doesn't work (hb is new)
   else:
      self.cb = self.figure.colorbar(hb)
Run Code Online (Sandbox Code Playgroud)

我现在正处于这个烦人的地方,我试图完全删除颜色条轴并简单地重新创建它.不幸的是,当我删除颜色条轴时,子图轴不会回收空间,调用self.subplot.reset_position()并没有按照我的想法进行.

def foo(self):
   self.subplot.clear()
   hb = self.subplot.hexbin(...)
   if self.cb:
      self.figure.delaxes(self.figure.axes[1])
      del self.cb
      # TODO: resize self.subplot so it fills the 
      #    whole figure before adding the new colorbar
   self.cb = self.figure.colorbar(hb)
Run Code Online (Sandbox Code Playgroud)

有没有人有什么建议?

非常感激!亚当

Vin*_*ooo 20

我认为问题在于del你取消变量,而不是引用的对象颜色条.如果你想从绘图中删除颜色条并消失,你必须使用remove颜色条实例的方法,为此你需要在变量中有颜色条,你有两个选择:

  1. 在创建时将颜色条保持在一个值中,如其他答案所示,例如 cb=plt.colorbar()
  2. 检索现有的颜色条,您可以执行以下(和upvoting :))我在这里写的:如何从matplotlib中的图中检索colorbar实例 然后:

cb.remove() plt.draw() #update plot


Ada*_*ser 11

好的,这是我的解决方案.不是非常优雅,但也不是一个可怕的黑客.

def foo(self):
   self.subplot.clear()
   hb = self.subplot.hexbin(...)
   if self.cb:
      self.figure.delaxes(self.figure.axes[1])
      self.figure.subplots_adjust(right=0.90)  #default right padding
   self.cb = self.figure.colorbar(hb)
Run Code Online (Sandbox Code Playgroud)

这适用于我的需求,因为我只有一个子图.在使用多个子图或在不同位置绘制颜色条时遇到相同问题的人需要进行调整.


Ale*_*hez 8

如果你有一个 matplotlib 图形对象,你只需要这样做fig.delaxes(fig.axes[1])

例如:

用颜色条绘图

import matplotlib.pyplot as plt

# setup some generic data
N = 37
x, y = np.mgrid[:N, :N]
Z = (np.cos(x*0.2) + np.sin(y*0.3))

# mask out the negative and positive values, respectively
Zpos = np.ma.masked_less(Z, 0)
Zneg = np.ma.masked_greater(Z, 0)

fig, ax1 = plt.subplots(figsize=(13, 3), ncols=1)

# plot just the positive data and save the
# color "mappable" object returned by ax1.imshow
pos = ax1.imshow(Zpos, cmap='Blues', interpolation='none')

# add the colorbar using the figure's method,
# telling which mappable we're talking about and
# which axes object it should be near
fig.colorbar(pos, ax=ax1)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

删除颜色条

import matplotlib.pyplot as plt

# setup some generic data
N = 37
x, y = np.mgrid[:N, :N]
Z = (np.cos(x*0.2) + np.sin(y*0.3))

# mask out the negative and positive values, respectively
Zpos = np.ma.masked_less(Z, 0)
Zneg = np.ma.masked_greater(Z, 0)

fig, ax1 = plt.subplots(figsize=(13, 3), ncols=1)

# plot just the positive data and save the
# color "mappable" object returned by ax1.imshow
pos = ax1.imshow(Zpos, cmap='Blues', interpolation='none')

# add the colorbar using the figure's method,
# telling which mappable we're talking about and
# which axes object it should be near
fig.colorbar(pos, ax=ax1)

fig.delaxes(fig.axes[1])
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


ken*_*sur 5

我设法使用Fig.clear()和display.clear_output()解决了同样的问题

import matplotlib.pyplot as plt
import IPython.display as display
import matplotlib.tri as tri
from pylab import *
%matplotlib inline

def plot_res(fig):
    ax=fig.add_axes([0,0,1,1])
    ax.set_xlabel("x")
    ax.set_ylabel('y')
    plotted=ax.imshow(rand(250, 250))
    ax.set_title("title")
    cbar=fig.colorbar(mappable=plotted)
    display.clear_output(wait=True)
    display.display(plt.gcf())
    fig.clear()

fig=plt.figure()
N=20
for j in range(N):
    plot_res(fig)
Run Code Online (Sandbox Code Playgroud)


Gui*_*ute 5

我的解决方案包括使用一个轴,其唯一目的是保持颜色条,并在需要时完全清除它。

例如,定义一次:

figure, ax = plt.subplots() # All the plotting is done on `ax`.
cax = ax.inset_axes([1.03, 0, 0.1, 1], transform=ax.transAxes) # Colorbar is held by `cax`. 
Run Code Online (Sandbox Code Playgroud)

然后根据需要多次执行此操作:

cax.clear()
colorbar = figure.colorbar(mpl.cm.ScalarMappable(norm=norm, cmap=cmap),
                           ax=ax,
                           cax=cax,
                           **kwargs)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

  • 你的方法对我有帮助,谢谢 (2认同)