0

I have the same problem as the person in this post:

My matplotlib.pyplot legend is being cut off

namely that my legend gets cut off at the side of the figure when I use plt.show(). enter image description here

The post above handles that problem using this code plt.savefig(bbox_inches = 'tight')

My problem is that it only works for the saved figure. Is there a simple way to adjust the axes of the plot like that for the method plt.show() as well? I searched but could not find an answer that does not require tedious trial and error rescaling.

Edit: My code here for reference. I did not include it at first because there are various variables at play that might be confusing.

def xhertz_plot(xhertz_df, nmc_nr, EIS_nr, id_nr, temp, SoC, hertz):
    y = 3
    ax = plt.gca()
    xhertz = xhertz_df.T.to_numpy()

    ax.plot(xhertz[y], xhertz[0], c = 'red', label = 'Realteil')
    ax.plot(xhertz[y], xhertz[1], c = 'blue', label = 'Imaginärteil')
    ax.scatter(xhertz[y], xhertz[0], c ='red')
    ax.scatter(xhertz[y], xhertz[1], c ='blue')
    
    ax.set_ylabel('Impedanz (m$\Omega$)', fontsize = 'small')
    ax.set_xlabel('Zeit in Tagen')

    handles, labels = ax.get_legend_handles_labels()

    ax.legend(loc = 'upper left', frameon = False, bbox_to_anchor = (1, 1.08),
              title = 'Impedanz EIS{EIS_nr}:'.format(nmc_nr = nmc_nr, EIS_nr = EIS_nr),
              fontsize = 'small',
              )
    
    plt.title('Impedanz Plot von ID{id_nr} NMC{nmc_nr} bei {x} Hertz'.format(id_nr = id_nr, temp = temp, SoC = SoC, nmc_nr = nmc_nr, x=hertz))
    plt.savefig('Impedanz Plot von ID{id_nr} NMC{nmc_nr} bei {x} Hertz'.format(id_nr = id_nr, temp = temp, SoC = SoC, nmc_nr = nmc_nr, x=hertz),
                bbox_inches = 'tight', dpi = 600)
    
    plt.show()
lpnorm
  • 459
  • 3
  • 10
  • Did you try plt.tight_layout just before plt.plot? – JohanC Mar 15 '21 at 11:35
  • I did now, but it actually made the figure even more tight in a literal sense. Not even the labels are visible now. – lpnorm Mar 15 '21 at 11:38
  • Without seeing the code it's hard to guess what you are doing. Do you create the plot via the object-oriented plt.subplots interface? Note that the post you're linking to is extremely old. Try the online official matplotlib tutorials. – JohanC Mar 15 '21 at 11:41
  • Post your code so we can help. – pakpe Mar 15 '21 at 12:05
  • @JohanC I linked to it because I wanted to show that I searched the site to avoid immediatly getting flagged as a duplicate. – lpnorm Mar 15 '21 at 12:20
  • If the posted code is the only code that calls matplotlib, then adding `plt.tight_layout()` just before `plt.show()` should really fit everything nicely into the plot. If that doesn't work, you might want to edit your post and add some dummy data. Note that a pandas dataframe is not needed to show how the plotting works. You could just use `xhertz = np.random.rand(4, 20)` or so. – JohanC Mar 15 '21 at 15:28

0 Answers0