maxkra
maxkra

Reputation: 87

Hue gradient as colorbar on y axis with matplotlib

I have the following Hue/Saturation 2D-Histogram. There are two things i like to change but don't know how. Hue/saturation 2D Histogram

1) Is it possible to replace the y-axis values (0-20) with a colorbar that shows a hue-gradient?The following code builds a numpy array of the gradient.

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)

So the question is how to set this array as a colorbar and locate it next to the left side of the image.

2) I want to scale the colorbar to the right of the image, so that it does not exceed it on top and bottom?

I hope somebody can help me.

EDIT: To clarify what I want to see at the y-axis (Hue) instead of the values 0 to 20. I have following gradient. I generate it with the code above. And I want this gradient visualized as a colorbar instead of the values 0 to 20 of the Hue axis. Basically: How can i set all_hues (Gradient posted below) as data for a colorbar and show it and move the colorbar to the location of the Hue axis ticks.

Hue Gradient

Current code:

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

Upvotes: 1

Views: 1224

Answers (1)

Silmathoron
Silmathoron

Reputation: 2001

Ok, I don't know how to do this exactly... the closest thing I can think of is to use AxesGrid from these matplotlib examples: cmap and edge 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()

This is the best I can do... you'll have to find a way to plot the colors you want in the left "colorbar".

Upvotes: 1

Related Questions