简体   繁体   中英

Matplotlib subplot: imshow + plot

I want to create a plot that looks like the image below. There are two unique plots in the figure. img1 was generated using plt.imshow() , while img2 was generated using plt.plot() . The code I used to generate each of the plots is provided below

plt.clf()
plt.imshow(my_matrix)
plt.savefig("mymatrix.png")

plt.clf()
plt.plot(x,y,'o-')
plt.savefig("myplot.png")

The matrix used in img1 is 64x64 . The same range for img2 's x-axis ( x=range(64) ). Ideally, the x-axes of the two img2 's align with the axes of img1 .

It is important to note that the final image is reminiscent of seaborn's jointplot() , but the marginal subplots ( img2 ) in the image below do not show distribution plots.

带注释的理想输出

You can use the make_axes_locatable functionality of the mpl_toolkits.axes_grid1 to create shared axes along both directions of the central imshow plot.

Here is an example:

import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
import numpy as np; np.random.seed(0)

Z = np.random.poisson(lam=6, size=(64,64))
x = np.mean(Z, axis=0)
y = np.mean(Z, axis=1)

fig, ax = plt.subplots()
ax.imshow(Z)

# create new axes on the right and on the top of the current axes.
divider = make_axes_locatable(ax)
axtop = divider.append_axes("top", size=1.2, pad=0.3, sharex=ax)
axright = divider.append_axes("right", size=1.2, pad=0.4, sharey=ax)
#plot to the new axes
axtop.plot(np.arange(len(x)), x, marker="o", ms=1, mfc="k", mec="k")
axright.plot(y, np.arange(len(y)), marker="o", ms=1, mfc="k", mec="k")
#adjust margins
axright.margins(y=0)
axtop.margins(x=0)
plt.tight_layout()
plt.show()

在此处输入图片说明

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