python - 使用 matplotlib.pyplot 添加轴时如何保留分辨率?

标签 python matplotlib resolution

如果运行以下代码

import matplotlib.pyplot as plt
import numpy as np
a=np.random.random((1000,1000))
plt.imshow(a, cmap='Reds', interpolation='nearest')
plt.savefig('fig.png',bbox_inches='tight')

我得到了下面的图片,所有单元格代表每个随机数。

enter image description here

但是,当添加轴时,如下所示的代码:

import matplotlib.pyplot as plt
import numpy as np
a=np.random.random((1000,1000))
plt.imshow(a, cmap='Reds', interpolation='nearest')

plt.xlim(0, 10)
plt.xticks(list(range(0, 10)))
plt.ylim(0, 10)
plt.yticks(list(range(0, 10)))

plt.savefig('fig3.png',bbox_inches='tight')

我得到了分辨率较低的图片:

enter image description here

那么如何在不影响分辨率的情况下添加轴刻度呢?如果与轴标记的字体大小有关,如何自动调整轴标记以保持原始分辨率?

最佳答案

对您的问题的应用:

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*0.01))
formatterX = FuncFormatter(lambda x, pos: '{0:g}'.format(x*0.01))

# 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,100)))

plt.yticks(list(range(0, 1001,100)))

plt.show()

Y with Atoms, X with scalen numbers, both with titles

来源:

一个可能的解决方案是根据某些函数来格式化刻度标签,如下面 matplotlib 页面的示例代码所示。

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

x = np.arange(4)
money = [1.5e5, 2.5e6, 5.5e6, 2.0e7]


def millions(x, pos):
    'The two args are the value and tick position'
    return '$%1.1fM' % (x * 1e-6)


formatter = FuncFormatter(millions)

fig, ax = plt.subplots()
ax.yaxis.set_major_formatter(formatter)
plt.bar(x, money)
plt.xticks(x, ('Bill', 'Fred', 'Mary', 'Sue'))
plt.show()

matplotlib.org Example

<小时/>

this answer 中显示了类似的解决方案, 在哪里 您可以设置一个函数来为您标记轴并将其缩小:

ticks = ticker.FuncFormatter(lambda x, pos: '{0:g}'.format(x*scale))
ax.xaxis.set_major_formatter(ticks)

在这里,您需要执行 /100 而不是 *scale

对您来说更简单的方法可能是:

ticks = plt.xticks()/100
plt.gca().set_xticklabels(ticks.astype(int))

(adapted from https://stackoverflow.com/a/10171851/7505395)

关于python - 使用 matplotlib.pyplot 添加轴时如何保留分辨率?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47850132/

相关文章:

python - Py2exe 错误 : No Commands Supplied

python - Keras 中可以使用什么模型(损失函数等)来进行概率标签的分类训练而不是 one-hot 编码

python - 为什么在 seaborn pairplot 的 kde 子图中没有显示颜色?

python - `plt.style.context` 中的 `matplotlib` 可以用作 Python 3.6 中的 `decorator` 吗?

python - Matplotlib:手动向axes.prop_cycle()中的默认颜色添加更多颜色?

python selenium perfLoggingPrefs过滤

python - 为什么 pickle 吃内存?

algorithm - 粗细算法

android - 如何告诉 Android 不要缩放图像?

audio - ffmpeg : is there a simple way to edit the video resolution, 但保留所有音频和字幕