如何使用plt.savefig正确显示足够的刻度标记? [英] How to properly display sufficient tick markers using plt.savefig?

查看:552
本文介绍了如何使用plt.savefig正确显示足够的刻度标记?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

运行下面的代码后,所有轴刻度线都相互重叠.此时,当plt.show()弹出缩放时,每个标记仍可以具有良好的分辨率.但是,由plt.savefig('fig.png')保存的图形将失去其分辨率.还能优化吗?

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

推荐答案

我认为您可以通过设置图形的大小来解决它,例如

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

正如@PatrickArtner在评论中指出的那样,您还可以通过

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)

代替

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

这篇关于如何使用plt.savefig正确显示足够的刻度标记?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆