Home > OS >  Adjusting python pcolor chart over the picture
Adjusting python pcolor chart over the picture

Time:09-23

I want to put a pcolor chart on the picture. Do you know a way to automatically match/adjust the colormap to a picture?

Example code:

import matplotlib.pyplot as plt
import numpy as np

# my image
im = plt.imread('salad.png')

# example pcolor chart
values = np.random.rand(6, 10)
p = plt.pcolor(values)

Image:

enter image description here

Pcolor chart:

enter image description here

I tried this:

# Create Figure and Axes objects
fig,ax = plt.subplots(1)

# display the image on the Axes
implot = ax.imshow(image)

# plot the pcolor on the Axes. Use alpha to set the transparency
p = ax.pcolor(values, alpha = 0.5, cmap='viridis')  

# Add a colorbar for the pcolor field
fig.colorbar(p, ax=ax)

As a result I have this below and that's not what I'm looking for. Color map does not fit in the whole image range:

enter image description here

Is there a way to automatically adjust the pcolor chart to the image size? Or image to pcolor chart size?

I mean an example result like here:

enter image description here

Thanks in advance for any ideas.

CodePudding user response:

You need to fix the extent of either the image or the pcolor overlay (i.e. the coordinate range over which they will be plotted).

As you can see, your image has limits of 0 to ~190 in both the x and y direction, but the pcolor has limits of 10 and 6 in the x and y direction.

One option is to define new x- and y-coordinates to pass into the pcolor function.

For example:

import matplotlib.pyplot as plt
import numpy as np

# my image
im = plt.imread('stinkbug.png')

# example pcolor chart
values = np.random.rand(6, 10)
#p = plt.pcolor(values)

# Create Figure and Axes objects
fig,ax = plt.subplots(1)

# display the image on the Axes
implot = ax.imshow(im)

# Define the x and y coordinates for the pcolor plot
x = np.linspace(0, im.shape[1], values.shape[1] 1)   # add 1 because we need the define the nodal coordinates
y = np.linspace(0, im.shape[0], values.shape[0] 1)

# plot the pcolor on the Axes. Use alpha to set the transparency
p = ax.pcolor(x, y, values, alpha = 0.5, cmap='viridis')  

# Add a colorbar for the pcolor field
fig.colorbar(p, ax=ax)

plt.show()

enter image description here

Alternatively, you could leave the pcolor extent alone, and modify the imshow extent, but that has the effect of changing the aspect ratio of the imshow image:

implot = ax.imshow(im, extent=[0, values.shape[1], 0, values.shape[0]])

p = ax.pcolor(values, alpha = 0.5, cmap='viridis')  

enter image description here

  • Related