How to properly display sufficient tick markers using plt.savefig?

徘徊边缘 提交于 2019-12-11 10:16:56

问题


After running the code below, the axis tick markers all overlap with each other. At this time, each marker could still have good resolution when zooming popped up by plt.show(). However, the figure saved by plt.savefig('fig.png') would lost its resolution. Can this also be optimised?

from matplotlib.ticker import FuncFormatter
from matplotlib.pyplot import show
import matplotlib.pyplot as plt
import numpy as np

a=np.random.random((1000,1000))

# create scaled formatters / for Y with Atom prefix
formatterY = FuncFormatter(lambda y, pos: 'Atom {0:g}'.format(y))
formatterX = FuncFormatter(lambda x, pos: '{0:g}'.format(x))

# apply formatters 
fig, ax = plt.subplots()
ax.yaxis.set_major_formatter(formatterY)
ax.xaxis.set_major_formatter(formatterX)

plt.imshow(a, cmap='Reds', interpolation='nearest')

# create labels
plt.xlabel('nanometer')
plt.ylabel('measure')
plt.xticks(list(range(0, 1001,10)))
plt.yticks(list(range(0, 1001,10)))

plt.savefig('fig.png',bbox_inches='tight')
plt.show()

回答1:


I think you can solve it by setting the size of the figure, e.g.

fig, ax = plt.subplots()
fig.set_size_inches(15., 15.)

As pointed out by @PatrickArtner in the comments, you can then also avoid the overlap of x-ticks by

plt.xticks(list(range(0, 1001, 10)), rotation=90)

instead of

plt.xticks(list(range(0, 1001,10)))

The rest of the code is completely unchanged; the output then looks reasonable (but is too large to upload here).



来源:https://stackoverflow.com/questions/47871512/how-to-properly-display-sufficient-tick-markers-using-plt-savefig

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!