gpt4 book ai didi

matplotlib - pyplot.subplots : different behavior in python and jupyter notebook

转载 作者:太空宇宙 更新时间:2023-11-03 20:15:20 25 4
gpt4 key购买 nike

在参加kaggle比赛时,我遇到了一些奇怪的问题。基本上,我正在尝试将 am 图像的矢量表示形式转换为 png 文件。它在 iPython 中完美运行,代码如下:

def drawing_to_np_prepare_data(drawing):
drawing = eval(drawing)
fig, ax = plt.subplots()
plt.close(fig)
print('[debug] ax=',ax)
for x,y in drawing:
ax.plot(x, y, marker='.')
ax.axis('off')
fig.canvas.draw()

# Convert images to numpy array
np_drawing = np.array(fig.canvas.renderer._renderer)

print('[debug] fig_size=',fig.get_size_inches())
print('[debug] dpi=',fig.dpi)

print('[debug] shape=',np_drawing.shape)
print('[debug] size=',np_drawing.size)
print('[debug] shape=',np_drawing.shape)

im = cv2.cvtColor(np_drawing.astype(np.uint8), cv2.COLOR_BGR2RGB)

# compress
compressed_array = io.BytesIO()
np.savez_compressed(compressed_array, im)
compressed_array.seek(0)
print('[debug] size=',np_drawing.shape)
return compressed_array

结果显示:

[debug] ax=AxesSubplot(0.125,0.125;0.775x0.755)
[debug] fig_size= [6. 4.]
[debug] dpi= 72.0
[debug] np_drawing.size= 497664
[debug] shape= (288, 432, 4)
[debug] size= 1880

这满足了我的需求:我得到了压缩大小<2Kb的图像

但是,当我从 CLI 在 python 中运行此代码时,我得到了完全不同的结果:

[debug] ax=AxesSubplot(0.125,0.11;0.775x0.77)
[debug] fig_size= [6.4 4.8]
[debug] dpi= 100.0
[debug] np_drawing.size= 1228800
[debug] shape= (480, 640, 4)
[debug] size= 13096

如您所见,图形大小、dpi、轴不同,因此最终的大小也不同。

我可以将参数传递给子图:

plt.subplots(figsize=(6.,4.), dpi=72)

它纠正除轴之外的参数(和尺寸,我猜是因为不同的轴):

[debug] ax=AxesSubplot(0.125,0.11;0.775x0.77)
[debug] fig_size= [6. 4.]
[debug] dpi= 72.0
[debug] np_drawing.size= 497664
[debug] shape= (288, 432, 4)
[debug] size= 8214

注意:我检查了库版本,它们是相同的。

因此,出现了多个问题:

  1. 为什么子图给出不同的轴、形状和分辨率?

  2. 如何修正坐标轴?

  3. 如何在 python 中获得相同的行为?

我想了解发生了什么事。谢谢!

最佳答案

要在脚本中获得与笔记本中完全相同的设置,请打开笔记本,然后运行

%matplotlib inline
%config InlineBackend.rc

它将打印 rcParams 字典。

{'figure.figsize': (6.0, 4.0),
'figure.facecolor': (1, 1, 1, 0),
'figure.edgecolor': (1, 1, 1, 0),
'font.size': 10,
'figure.dpi': 72,
'figure.subplot.bottom': 0.125}

将它们复制到您的 python 文件中

newrc = {'figure.figsize': (6.0, 4.0),
'figure.facecolor': (1, 1, 1, 0),
'figure.edgecolor': (1, 1, 1, 0),
'font.size': 10,
'figure.dpi': 72,
'figure.subplot.bottom': 0.125}

import matplotlib.pyplot as plt
plt.rcParams.update(newrc)

然后绘制你的图。

这是否真正解决了不同渲染器大小的问题无法测试,因为问题不包含 runnable example .

关于matplotlib - pyplot.subplots : different behavior in python and jupyter notebook,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58486988/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com