Matplotlib subplot title overlaps with x ticks












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.










share|improve this question























  • did you try changing figsize=(20,10) parameter?

    – AkshayNevrekar
    Nov 16 '18 at 9:29











  • Yes, I tried but it didnot affect the overlap

    – AI_Learning
    Nov 16 '18 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.

    – Guimoute
    Nov 16 '18 at 10:20













  • It seems to adjust the spacing between the subplots only. The problem here is within the subplot

    – AI_Learning
    Nov 16 '18 at 10:23
















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.










share|improve this question























  • did you try changing figsize=(20,10) parameter?

    – AkshayNevrekar
    Nov 16 '18 at 9:29











  • Yes, I tried but it didnot affect the overlap

    – AI_Learning
    Nov 16 '18 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.

    – Guimoute
    Nov 16 '18 at 10:20













  • It seems to adjust the spacing between the subplots only. The problem here is within the subplot

    – AI_Learning
    Nov 16 '18 at 10:23














1












1








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.










share|improve this question














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.







python matplotlib






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 16 '18 at 9:27









AI_LearningAI_Learning

4,08021035




4,08021035













  • did you try changing figsize=(20,10) parameter?

    – AkshayNevrekar
    Nov 16 '18 at 9:29











  • Yes, I tried but it didnot affect the overlap

    – AI_Learning
    Nov 16 '18 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.

    – Guimoute
    Nov 16 '18 at 10:20













  • It seems to adjust the spacing between the subplots only. The problem here is within the subplot

    – AI_Learning
    Nov 16 '18 at 10:23



















  • did you try changing figsize=(20,10) parameter?

    – AkshayNevrekar
    Nov 16 '18 at 9:29











  • Yes, I tried but it didnot affect the overlap

    – AI_Learning
    Nov 16 '18 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.

    – Guimoute
    Nov 16 '18 at 10:20













  • It seems to adjust the spacing between the subplots only. The problem here is within the subplot

    – AI_Learning
    Nov 16 '18 at 10:23

















did you try changing figsize=(20,10) parameter?

– AkshayNevrekar
Nov 16 '18 at 9:29





did you try changing figsize=(20,10) parameter?

– AkshayNevrekar
Nov 16 '18 at 9:29













Yes, I tried but it didnot affect the overlap

– AI_Learning
Nov 16 '18 at 9:40





Yes, I tried but it didnot affect the overlap

– AI_Learning
Nov 16 '18 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.

– Guimoute
Nov 16 '18 at 10:20







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.

– Guimoute
Nov 16 '18 at 10:20















It seems to adjust the spacing between the subplots only. The problem here is within the subplot

– AI_Learning
Nov 16 '18 at 10:23





It seems to adjust the spacing between the subplots only. The problem here is within the subplot

– AI_Learning
Nov 16 '18 at 10:23












1 Answer
1






active

oldest

votes


















2














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.






share|improve this answer
























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53334892%2fmatplotlib-subplot-title-overlaps-with-x-ticks%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    2














    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.






    share|improve this answer




























      2














      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.






      share|improve this answer


























        2












        2








        2







        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.






        share|improve this answer













        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.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 16 '18 at 10:51









        ImportanceOfBeingErnestImportanceOfBeingErnest

        140k13162241




        140k13162241
































            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53334892%2fmatplotlib-subplot-title-overlaps-with-x-ticks%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Bressuire

            Vorschmack

            Quarantine