使用matplotlib将颜色渐变作为y轴上的颜色条

时间:2016-06-15 12:01:14

标签: python numpy matplotlib colorbar

我有以下色相/饱和度2D直方图。有两件事我想改变但不知道如何改变。 Hue/saturation 2D Histogram

1)是否可以用显示色调渐变的颜色条替换y轴值(0-20)?以下代码构建渐变的numpy数组。

hue_gradient = np.linspace(0, 1)
hsv = np.ones(shape=(1, len(hue_gradient), 3), dtype=float)
hsv[:, :, 0] = hue_gradient
all_hues = hsv_to_rgb(hsv)

所以问题是如何将此数组设置为颜色条并将其定位在图像左侧旁边。

2)我想将色条缩放到图像的右侧,以便它在顶部和底部不会超过它?

我希望有人可以帮助我。

编辑: 澄清我想要在y轴(Hue)看到的而不是0到20的值。 我有以下渐变。我用上面的代码生成它。我希望这个渐变可视化为颜色条而不是Hue轴的0到20值。 基本上:我如何设置all_hues(下面的渐变)作为颜色条的数据并显示它并将颜色条移动到Hue轴刻度的位置。

Hue Gradient

当前代码:

fig_synth = plt.figure("synth")
plt.imshow(synth_avrgHistogram, interpolation='nearest', vmin=0, vmax=vmax)
plt.colorbar()
plt.xlabel("Saturation")
plt.ylabel("Hue")

1 个答案:

答案 0 :(得分:1)

好的,我不知道怎么做到这一点......我能想到的最接近的事情是使用这些matplotlib示例中的AxesGridcmapedge cbar

import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import AxesGrid
import numpy as np

def demo_right_cbar(fig):
    """
    A grid of 2x1 images. Left will be the colorbar, right the image.
    """
    grid = AxesGrid(fig, 121,  # similar to subplot(122)
                    nrows_ncols=(1,2),
                    axes_pad=0.05,
                    cbar_location="right",
                    cbar_mode="edge",
                    cbar_size="7%",
                    cbar_pad="2%",
                    )
    extent = (0,200,0,200)
    Z = np.random.randint(0,200,(extent[1],extent[3]))
    gradient = np.linspace(0, 20, 100)
    gradient = np.vstack((gradient, gradient)).T
    grid[0].imshow(gradient, aspect=100./7., extent=extent)
    grid[1].set_ylabel("Hue")
    grid[0].set_xticks([])
    grid[0].set_ylabel("Hue")

    im = grid[1].imshow(Z, extent=extent, interpolation="nearest", cmap=plt.get_cmap("summer"))
    grid[1].set_xlabel("Saturation")
    print(dir(grid[0]))
    cax = grid.cbar_axes[0]
    cax.colorbar(im)
    cax.toggle_label(True)
    cax.axis[cax.orientation].set_label('Foo')

fig = plt.figure()
demo_right_cbar(fig)

plt.show()

这是我能做的最好的......你必须找到一种方法来在左边的“colorbar”中绘制你想要的颜色。