简体   繁体   中英

How to plot image over colormesh plot in Matplotlib?

I want to plot bool density

plt.imshow(rectangle, extent=extent, cmap=ListedColormap([[1, 1, 1, 0], [0, 0, 0, 1]]))

over colormesh

plt.pcolormesh(x_ticks, y_ticks, np.transpose(potential))

How to do this?

Currently I see only FIRST plot, despite I would expect anything else.


Here is an example code:

import matplotlib
from matplotlib.colors import ListedColormap
import matplotlib.pyplot as plt
import numpy as np

x_ticks = np.linspace(-10, 10, 100, dtype=np.float32)
y_ticks = np.linspace(-10, 10, 100, dtype=np.float32)

x, y = np.meshgrid(x_ticks, y_ticks, indexing='ij')

# density plot of some circular function
r = np.sqrt(x ** 2 + y ** 2)
z = np.where(r != 0, np.sin(r) / r, 1)

plt.figure(1)
plt.pcolormesh(x_ticks, y_ticks, z)
plt.show()

# image of rectangle, white color is transparent
rectangle = np.logical_and(np.abs(x) < 2,  np.abs(y) < 2)
extent = [x_ticks[0], x_ticks[-1], y_ticks[0], y_ticks[-1]]

plt.figure(2)
plt.imshow(rectangle, extent=extent, cmap=ListedColormap([[1, 1, 1, 0], [0, 0, 0, 1]]))
plt.show()

# now I want both on the same plot superimposed
plt.figure(3)
plt.pcolormesh(x_ticks, y_ticks, z)
plt.imshow(rectangle, extent=extent, cmap=ListedColormap([[1, 1, 1, 0], [0, 0, 0, 1]]))
plt.show()

I am getting this:

在此处输入图片说明

But I wished this (drew in Photoshop):

在此处输入图片说明

You have to set an explicit zorder in one of the plotting calls to put that on top/bottom:

plt.pcolormesh(x_ticks, y_ticks, z)
plt.imshow(rectangle, extent=extent, cmap=ListedColormap([[1, 1, 1, 0], [0, 0, 0, 1]]), zorder=1)

结果

Andra's answer is correct of course. You can simplify your code a bit and neglect the extent or zorder keyword if you use pcolormesh to plot the rectangle as well:

plt.pcolormesh(x_ticks, y_ticks, z)
plt.pcolormesh(x_ticks, y_ticks, rectangle,cmap=ListedColormap([[1, 1, 1, 0], [0, 0, 0, 1]]))

In this way you know immediately what your coordinate system is ( z and rectangle must have the same shape).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM