matplotlib sharex与colorbar不起作用

Pre*_*thi 2 python matplotlib colorbar pandas subplot

在此处输入图片说明我有2个子图-1个散点图和一个条,我想要一个共享的x轴。散点图有一个色条。sharex似乎与此不兼容,因为两个图的轴不一致。我的代码:

fig, (ax, ax2) = plt.subplots(2,1, gridspec_kw = {'height_ratios':[13,2]},figsize=(15,12), sharex=True)

df_plotdata.plot(kind='scatter', ax=ax, x='index_cancer', y='index_g', s=df_plotdata['freq1']*50, c=df_plotdata['freq2'], cmap=cmap)

df2.plot(ax=ax2, x='index_cancer', y='freq', kind = 'bar')
Run Code Online (Sandbox Code Playgroud)

Imp*_*est 6

Sharex表示轴限制相同,并且轴已同步。这并不意味着它们位于彼此之上。这完全取决于您如何创建颜色栏。

就像matplotlib中的任何statndard颜色条一样,pandas scatterplot创建的颜色条是通过删除与其相关的轴的空间而创建的。因此,此轴小于网格中的其他轴。

您可以选择的选项包括:

  • 将网格的其他轴收缩与散点图轴收缩的量相同。
    这可以通过使用第一轴的位置ax.get_position()并相应地使用和设置第二轴的位置来完成。ax.set_postion()

    import matplotlib.pyplot as plt
    import pandas as pd
    import numpy as np
    import itertools as it
    
    xy = list( it.product( range(10), range(10) ) )
    df = pd.DataFrame( xy, columns=['x','y'] )
    df['score'] = np.random.random( 100 )
    
    kw = {'height_ratios':[13,2]}
    fig, (ax,ax2) = plt.subplots(2,1,  gridspec_kw=kw, sharex=True)
    
    df.plot(kind='scatter', x='x',  y='y', c='score', s=100, cmap="PuRd",
              ax=ax, colorbar=True)
    df.groupby("x").mean().plot(kind = 'bar', y='score',ax=ax2, legend=False)
    
    ax2.legend(bbox_to_anchor=(1.03,0),loc=3)
    
    pos = ax.get_position()
    pos2 = ax2.get_position()
    ax2.set_position([pos.x0,pos2.y0,pos.width,pos2.height])
    
    plt.show()
    
    Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

  • 创建一个包括用于颜色栏的轴的网格。
    在这种情况下,您可以创建4 x 4网格并将颜色栏添加到其右上轴。这需要提供散点图,fig.colorbar()并为色条指定一个轴,

    fig.colorbar(ax.collections[0], cax=cax)       
    
    Run Code Online (Sandbox Code Playgroud)

    然后卸下不需要的右下轴(ax.axis("off"))。如果需要,您仍然可以通过共享轴ax2.get_shared_x_axes().join(ax, ax2)

    import matplotlib.pyplot as plt
    import pandas as pd
    import numpy as np
    import itertools as it
    
    
    xy = list( it.product( range(10), range(10) ) )
    df = pd.DataFrame( xy, columns=['x','y'] )
    df['score'] = np.random.random( 100 )
    
    kw = {'height_ratios':[13,2], "width_ratios":[95,5]}
    fig, ((ax, cax),(ax2,aux)) = plt.subplots(2,2,  gridspec_kw=kw)
    
    df.plot(kind='scatter', x='x',  y='y', c='score', s=80, cmap="PuRd",
             ax=ax,colorbar=False)
    df.groupby("x").mean().plot(kind = 'bar', y='score',ax=ax2, legend=False)
    
    fig.colorbar(ax.collections[0], cax=cax, label="score")
    aux.axis("off")
    ax2.legend(bbox_to_anchor=(1.03,0),loc=3)
    ax2.get_shared_x_axes().join(ax, ax2)
    ax.tick_params(axis="x", labelbottom=0)
    ax.set_xlabel("")
    
    plt.show()
    
    Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明


lei*_*nby 5

根据 ImportanceOfBeingErnest 的回答,以下两个函数将对齐轴:

def align_axis_x(ax, ax_target):
    """Make x-axis of `ax` aligned with `ax_target` in figure"""
    posn_old, posn_target = ax.get_position(), ax_target.get_position()
    ax.set_position([posn_target.x0, posn_old.y0, posn_target.width, posn_old.height])

def align_axis_y(ax, ax_target):
    """Make y-axis of `ax` aligned with `ax_target` in figure"""
    posn_old, posn_target = ax.get_position(), ax_target.get_position()
    ax.set_position([posn_old.x0, posn_target.y0, posn_old.width, posn_target.height])
Run Code Online (Sandbox Code Playgroud)