简体   繁体   中英

Matplotlib subplot title overlaps with x ticks

I have the following code to generate the visuals for feature importance of a model.

def plot_featu_imp(ax,df,plot_title='feature_imp'):
    feature_imp = df
    ax = feature_imp.plot(ax=ax,kind='barh',
                          x='feature_names',y='importn',color='g',sort_columns=True) #figsize=(12,10),
    rects = ax.patches

    for rect in rects:
        # Get X and Y placement of label from rect.
        x_value = rect.get_width()
        y_value = rect.get_y() + rect.get_height() / 2

        # Number of points between bar and label. Change to your liking.
        space = 5
        # Vertical alignment for positive values
        ha = 'left'

        # If value of bar is negative: Place label left of bar
        if x_value < 0:
            # Invert space to place label to the left
            space *= -1
            # Horizontally align label at right
            ha = 'right'

        # Use X value as label and format number with one decimal place
        label = "{:.3f}".format(x_value)

        # Create annotation
        ax.annotate(
            label,                      # Use `label` as label
            (x_value, y_value),         # Place label at end of the bar
            xytext=(space, 0),          # Horizontally shift label by `space`
            textcoords="offset points", # Interpret `xytext` as offset in points
            va='center',                # Vertically center label
            ha=ha,
            fontsize=15,
            color='tab:grey')                     

    ax.spines['top'].set_visible(True)
    ax.spines['right'].set_visible(False)
    ax.spines['bottom'].set_visible(False)
    ax.spines['left'].set_visible(False)

    ax.legend().set_visible(False)
    ax.tick_params(top=True, labeltop=True, bottom=False, left=False, right=False, labelleft=True, labelbottom=False,labelsize=20)
    ax.set_xlabel('Importance ',fontsize=20)
    ax.set_ylabel('Feature names',fontsize=20)
    ax.set_title(plot_title,fontsize=25)

    ax.title.set_position([0.1,1])
    return ax

I want to generate this visual for a series of models. For example.

fig, ax = plt.subplots(2,1, figsize=(20,10), facecolor='w', edgecolor='k')
# plt.tight_layout()
for i in range(2):
    df=pd.DataFrame({'feature_names':['a','b','c'],'importn':[0.1,0.3,0.6]})
    plot_featu_imp(ax[i],df,'model'+str(i))
plt.show()

绘图输出 Now the problem is having a overlap between the title and x-ticks I have tried setting the position of the title using set_position but it did not work. Is there any way to create clearance between those two.

Thanks in advance.

You set the position yourself to y=1, which is precisely on top of the axes. If you had chosen a larger number here, you would get the title further away,

ax.title.set_position([0.1,1.25])

However I would rather set the padding within the call to set_title :

ax.set_title(plot_title,fontsize=25, loc="left", pad=30)

在此处输入图片说明

Here, fig.tight_layout() has been used in addition.

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