I wrote a code which requires some manual formatting of the legend to get what I want. Based on a question I posted yesterday and some more googling, I got the legend to look exactly how I want when it displays using plt.show(). Unfortunately, now when I save the image using plt.savefig(dpi=300), the legend gets totally screwed up. It looks like when I save it from the plt.show window it is at 200dpi, but I would like to save it at at least 300 or more dpi.
What plots when I use plt.show is this:
But when I save it in plt.savefig and change the dpi to 300, it's this:
I see posts, like this one, that say there is a resolution difference between plt.show and plt.savefig, but I don't understand how to actually resolve the issue for me. I have tried setting the figure size, but once I change the dpi in savefig it screws it up again. I have also tried adding bbox_inches='tight' into savefig, it doesn't make a difference.
Here is a code to test it:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.legend_handler import HandlerTuple
x = np.arange(3)
y = np.arange(3)
c1= plt.plot(x,y, color = 'blue' , label= "blue")
c2 = plt.plot(x,y, color = 'green' , label= "green")
c3 = plt.plot(x,y, color = 'red' , label= "red")
c4 = plt.plot(x,y, color = 'magenta' , label= "magenta")
p1 = plt.scatter(x,y, color = 'blue')
p2 = plt.scatter(x,y, color = 'green')
p3 = plt.scatter(x,y, color = 'red')
p4 = plt.scatter(x,y, color = 'magenta')
t1 = plt.scatter(x,y, color = 'blue', facecolors='none')
t2 = plt.scatter(x,y, color = 'green', facecolors='none')
t3 = plt.scatter(x,y, color = 'red', facecolors='none')
t4 = plt.scatter(x,y, color = 'magenta', facecolors='none')
l1 = plt.legend(handlelength = 0, bbox_to_anchor=(1, .5, 0,0), loc ='center right')
llines = l1.get_texts()
llines[0].set_color('blue')
llines[1].set_color('green')
llines[2].set_color('red')
llines[3].set_color('magenta')
shift = max([t.get_window_extent().width for t in l1.get_texts()])
for t in l1.get_texts():
t.set_ha('right')
t.set_position((shift,0))
l2 = plt.legend([(p1, p2, p3, p4), (t1, t2, t3, t4)], ['tomatoes', 'potatoes'],
scatterpoints=1, numpoints=1, loc = 'center right',bbox_to_anchor=(1, .3, 0,0),
handler_map={tuple: HandlerTuple(ndivide=None)})
plt.gca().add_artist(l1)
shift2 = max([t2.get_window_extent().width for t2 in l2.get_texts()])
for t2 in l2.get_texts():
t2.set_ha('right') # ha is alias for horizontalalignment
t2.set_position((shift2,0))
plt.show()
filename_save = "testfile"
plt.savefig(filename_save, dpi = 300, bbox_inches='tight')
Any ideas? Thank you for your help!