Python Matplotlib figure title overlaps axes label when using twiny

前端 未结 6 1950
滥情空心
滥情空心 2020-11-27 11:42

I am trying to plot two separate quantities on the same graph using twiny as follows:

fig = figure()
ax = fig.add_subplot(111)
ax.plot(T, r, \'b-\', T, R, \'         


        
相关标签:
6条回答
  • 2020-11-27 11:52

    Just use plt.tight_layout() before plt.show(). It works well.

    0 讨论(0)
  • 2020-11-27 11:53

    Forget using plt.title and place the text directly with plt.text. An over-exaggerated example is given below:

    import pylab as plt
    
    fig = plt.figure(figsize=(5,10))
    
    figure_title = "Normal title"
    ax1  = plt.subplot(1,2,1)
    
    plt.title(figure_title, fontsize = 20)
    plt.plot([1,2,3],[1,4,9])
    
    figure_title = "Raised title"
    ax2  = plt.subplot(1,2,2)
    
    plt.text(0.5, 1.08, figure_title,
             horizontalalignment='center',
             fontsize=20,
             transform = ax2.transAxes)
    plt.plot([1,2,3],[1,4,9])
    
    plt.show()
    

    enter image description here

    0 讨论(0)
  • 2020-11-27 11:57

    I'm not sure whether it is a new feature in later versions of matplotlib, but at least for 1.3.1, this is simply:

    plt.title(figure_title, y=1.08)
    

    This also works for plt.suptitle(), but not (yet) for plt.xlabel(), etc.

    0 讨论(0)
  • 2020-11-27 12:04

    I was having an issue with the x-label overlapping a subplot title; this worked for me:

    import matplotlib.pyplot as plt
    fig, ax = plt.subplots(2, 1)
    ax[0].scatter(...)
    ax[1].scatter(...)
    plt.tight_layout()
    .
    .
    .
    plt.show()
    

    before

    after

    reference:

    • https://matplotlib.org/users/tight_layout_guide.html
    0 讨论(0)
  • 2020-11-27 12:10

    You can use pad for this case:

    ax.set_title("whatever", pad=20)
    
    0 讨论(0)
  • 2020-11-27 12:13
    ax.set_title('My Title\n', fontsize="15", color="red")
    plt.imshow(myfile, origin="upper")
    

    If you put '\n' right after your title string, the plot is drawn just below the title. That might be a fast solution too.

    0 讨论(0)
提交回复
热议问题