【问题标题】:matplotlib: any way to get existing colorbars?matplotlib:有什么方法可以获取现有的颜色条?
【发布时间】:2020-04-22 21:53:45
【问题描述】:

在 matplotlib 的面向对象风格中,您可以获取现有图形中的当前轴、线和图像:

fig.axes
fig.axes[0].lines
fig.axes[0].images

但是我还没有找到获取现有颜色条的方法,我必须在第一次创建颜色条时为其指定一个名称:

cbar = fig.colorbar(image)

如果我没有为颜色条对象指定名称,有什么方法可以获取给定图形中的颜色条对象?

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    问题是颜色条被添加为“只是另一个”轴,因此它将与“正常”轴一起列出。

    import matplotlib.pyplot as plt
    import numpy as np
    
    data = np.random.rand(6,6)
    fig = plt.figure(1)
    fig.clf()
    ax = fig.add_subplot(1,1,1)
    cax = ax.imshow(data, interpolation='nearest', vmin=0.5, vmax=0.99)
    print "Before adding the colorbar:"
    print fig.axes
    fig.colorbar(cax)
    print "After adding the colorbar:"
    print fig.axes
    

    对我来说,这给出了结果:

    Before adding the colorbar:
    [<matplotlib.axes._subplots.AxesSubplot object at 0x00000000080D1D68>]
    After adding the colorbar:
    [<matplotlib.axes._subplots.AxesSubplot object at 0x00000000080D1D68>,
    <matplotl ib.axes._subplots.AxesSubplot object at 0x0000000008268390>]
    

    也就是说,你的图中有两个轴,第二个是新的颜色条。

    编辑:代码基于此处给出的答案: https://stackoverflow.com/a/2644255/2073632

    【讨论】:

      猜你喜欢
      • 2021-10-30
      • 2018-07-24
      • 1970-01-01
      • 1970-01-01
      • 2012-10-31
      • 1970-01-01
      • 2016-03-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多