简体   繁体   中英

Overplotting contours over subplots in matplotlib

I have 2 sets of data, one that I have to display in bar subplots like this: 条形图

and second set is just data from which I need to draw contours. Is there a way in matplotlib to draw contours on the same figure as bar subplots over them to get effect like this:

想要的效果

Code I use to generate subplots:

nl = 0
fig, axs = plt.subplots(16,16, sharex='col', sharey='row', gridspec_kw={'hspace': 0, 'wspace': 0}, dpi = 300)
for p in range(16):
    for r in range(16):
        axs[p,r].set_ylim(0,1.1)
        axs[p,r].set_xlim(-150,150)
        axs[p,r].xaxis.set_ticklabels([])
        axs[p,r].yaxis.set_ticklabels([])
        axs[p,r].xaxis.set_ticks([])
        axs[p,r].xaxis.set_ticks([])
        axs[p,r].tick_params(width=0)
        axs[p,r].bar(xp,wid[nl], width = 10)
        nl += 1

Also I would be really thankful for suggestions how to make those subplots square (like on the 2nd image)

You can simply create a new subplot with geometry (1,1,1), that is to say, occupying all the available space for the subplots and therefore covering all the other subplots.

You'll have to be sure to hide the background patch of that top axes if you want to see the subplots below (using ax.patch.set_visible(False) ). Or since you see to remove all ticks from the axes, you can use set_axis_off() which removes all spines and decorations, including the background patch.

As for square subplots, you get square subplots if you create a square figure

N = 5  # for demonstration
w = 4

fig, axs = plt.subplots(N,N, sharex='col', sharey='row', gridspec_kw={'hspace': 0, 'wspace': 0}, dpi=100, figsize=(w,w))
for ax in axs.flat:
    ax.set_ylim(0,1.1)
    ax.set_xlim(-150,150)
    ax.xaxis.set_ticklabels([])
    ax.yaxis.set_ticklabels([])
    ax.xaxis.set_ticks([])
    ax.xaxis.set_ticks([])
    ax.tick_params(width=0)
    #ax.bar(xp,wid[nl], width = 10)

# create another axes over the grid
ax0 = fig.add_subplot(111)
ax0.set_axis_off()  # hides all axes decoration (also hides the background)
#ax0.patch.set_visible(False)  # hides the background of the axes


# plot contour
# code from https://matplotlib.org/3.1.1/gallery/images_contours_and_fields/contour_demo.html#sphx-glr-gallery-images-contours-and-fields-contour-demo-py
delta = 0.025
x = np.arange(-3.0, 3.0, delta)
y = np.arange(-2.0, 2.0, delta)
X, Y = np.meshgrid(x, y)
Z1 = np.exp(-X**2 - Y**2)
Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2)
Z = (Z1 - Z2) * 2

CS = ax0.contour(X, Y, Z)

在此处输入图像描述

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