简体   繁体   English

Matplotlib 在 imshow 和 plot 之间共享 x 轴

[英]Matplotlib share x-axis between imshow and plot

I am trying to plot two imshow and one plot above each other sharing their x-axis.我正在尝试 plot 两个 imshow 和一个 plot 在彼此上方共享它们的 x 轴。 The figure layout is set up using gridspec.图形布局是使用 gridspec 设置的。 Here is a MWE:这是一个MWE:

    import matplotlib as mpl
    from matplotlib import pyplot as plt
    import numpy as np
    fig = plt.figure(figsize=(10,8))
    gs = fig.add_gridspec(3,2,width_ratios=(1,2),height_ratios=(1,2,2), left=0.1,right=0.9,bottom=0.1,top=0.99, wspace=0.1, hspace=0.1)
    ax=fig.add_subplot(gs[2,1])
    ax2=fig.add_subplot(gs[2,0], sharey=ax)
    ax3=fig.add_subplot(gs[1,0])
    ax4=fig.add_subplot(gs[1,1], sharex=ax, sharey=ax3)
    ax5=fig.add_subplot(gs[0,1], sharex=ax)
    
    dates = pd.date_range("2020-01-01","2020-01-10 23:00", freq="H")
    xs = mpl.dates.date2num(dates)
    ys = np.random.random(xs.size)
    N = 10
    arr = np.random.random((N, N))
    arr2 = np.random.random((N, N))
    
    norm=mpl.colors.Normalize(0, arr.max()) # change the min to stretch the color spectrum
    pcm = ax.imshow(arr, extent=[xs[0],xs[-1],10,0],norm=norm,aspect='auto')
    cax = fig.colorbar(pcm, ax=ax, extend='max') # , location='left'
    ax.set_xlabel('date')
    cax.set_label('fraction [-]')
    # ax.xaxis_date()
    myFmt = mpl.dates.DateFormatter('%d.%m')
    ax.xaxis.set_major_formatter(myFmt)
    
    norm=mpl.colors.Normalize(0, arr2.max()) # change the min to stretch the color spectrum
    pcm = ax4.imshow(arr2, extent=[xs[0],xs[-1],1,0],norm=norm,aspect='auto')
    cax4 = fig.colorbar(pcm, ax=ax4, extend='max')
    cax4.set_label('fraction [-]')
    
    ax5.plot(xs,ys)

    con1 = ConnectionPatch(xyA=(ax2.get_xlim()[0],1), xyB=(ax2.get_xlim()[0],1), 
                       coordsA="data", coordsB="data", connectionstyle=mpl.patches.ConnectionStyle("Bar", fraction=-0.05),
                       axesA=ax2, axesB=ax3, arrowstyle="-", color='r')
    
    con2 = ConnectionPatch(xyA=(ax2.get_xlim()[0],0), xyB=(ax2.get_xlim()[0],0), 
                       coordsA="data", coordsB="data", connectionstyle=mpl.patches.ConnectionStyle("Bar", fraction=-0.02),
                       axesA=ax2, axesB=ax3, arrowstyle="-", color='r')
    
    fig.add_artist(con1)
    fig.add_artist(con2)

The plot ends up like this: plot 最终是这样的: 阴谋

While the axes seem to be linked (date format applied to all of them), they do not have the same extent.虽然轴似乎是链接的(日期格式适用于所有轴),但它们的范围不同。

NOTE: The two left axes must not share the same x-axis.注意:两个左轴不得共享同一个 x 轴。

EDIT: Added ConnectionPatch connections which break when using constrained_layout.编辑:添加了在使用 constrained_layout 时会中断的 ConnectionPatch 连接。

Constrained_layout was specifically designed with this case in mind. Constrained_layout 是专门为这种情况而设计的。 It will work with your gridspec solution above, but more idiomatically:它将与您上面的 gridspec 解决方案一起使用,但更惯用:

import datetime as dt
import matplotlib as mpl
from matplotlib import pyplot as plt
import numpy as np
import pandas as pd

fig, axs = plt.subplot_mosaic([['.', 'plot'], ['empty1', 'imtop'],
                               ['empty2', 'imbottom']],
                              constrained_layout=True,
                              gridspec_kw={'width_ratios':(1,2),'height_ratios':(1,2,2)})

axs['imtop'].sharex(axs['imbottom'])
axs['plot'].sharex(axs['imtop'])

dates = pd.date_range("2020-01-01","2020-01-10 23:00", freq="H")
xs = mpl.dates.date2num(dates)
ys = np.random.random(xs.size)
N = 10
arr = np.random.random((N, N))
arr2 = np.random.random((N, N))

norm=mpl.colors.Normalize(0, arr.max()) # change the min to stretch the color spectrum
pcm = axs['imtop'].imshow(arr, extent=[xs[0],xs[-1],10,0],norm=norm,aspect='auto')
cax = fig.colorbar(pcm, ax=axs['imtop'], extend='max')

norm=mpl.colors.Normalize(0, arr2.max()) # change the min to stretch the color spectrum
pcm = axs['imbottom'].imshow(arr2, extent=[xs[0],xs[-1],1,0],norm=norm,aspect='auto')
cax4 = fig.colorbar(pcm, ax=axs['imbottom'], extend='max')

axs['plot'].plot(xs,ys)

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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