1

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()

plot output 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.

4
  • did you try changing figsize=(20,10) parameter? Commented Nov 16, 2018 at 9:29
  • Yes, I tried but it didnot affect the overlap Commented Nov 16, 2018 at 9:40
  • Fiddle with the width and height values of fig.figure.tight_layout(w_pad, h_pad), it works for me usually. Edit: or use the plt.tight_layout() you have commented out, place it just before plt.show() and again play with the parameters if needed. Commented Nov 16, 2018 at 10:20
  • It seems to adjust the spacing between the subplots only. The problem here is within the subplot Commented Nov 16, 2018 at 10:23

2 Answers 2

3

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)

enter image description here

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

Sign up to request clarification or add additional context in comments.

Comments

0

Here are the two cents of chatgpt which actually worked for me, placed just before plt.show():

plt.subplots_adjust(hspace = .5)

This can be used to adjust height space between subplots. More info here: https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.subplots_adjust.html

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.