增加DPI时如何修复plt.show()和plt.savefig错误?

时间:2019-06-27 23:43:34

标签: python matplotlib dpi

我编写了一个代码,该代码需要对图例进行一些手动格式化才能获得所需的内容。基于a question I posted yesterday和更多的谷歌搜索信息,我得到了图例,以使其在使用plt.show()进行显示时准确地显示我想要的样子。不幸的是,现在当我使用plt.savefig(dpi = 300)保存图像时,图例就被搞砸了。当我从plt.show窗口中将其保存为200dpi时,但是我希望至少将其保存为300 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:

我看到like this one帖子说plt.show和plt.savefig之间存在分辨率差异,但是我不知道如何为我解决实际问题。我尝试设置图形大小,但是一旦在savefig中更改dpi,它就会再次拧紧。我还尝试将bbox_inches ='tight'添加到savefig中,这没有什么区别。

这是测试它的代码:

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

有什么想法吗?谢谢您的帮助!

0 个答案:

没有答案