gpt4 book ai didi

python - streamlit pyplot 子图失真

转载 作者:行者123 更新时间:2023-12-05 03:36:44 27 4
gpt4 key购买 nike

我正在用子图绘制图像,它在 Jupyter(或“纯 python”)和 Streamlit 中看起来不同。

例如,如果我有一个只有1 张图像(2 x 2) 子图,它将在 Streamlit 中被拉伸(stretch)

如何关闭这种拉伸(stretch)?

没有 Streamlit 的绘图:

enter image description here

Streamlit 中的绘图

streamlit plot

代码:

import streamlit as st
import numpy as np
import matplotlib.pyplot as plt

imgs = [np.random.random((50,50)) for _ in range(4)]

fig1 = plt.figure(figsize = (3,3))
plt.subplot(2, 2, 1);
plt.imshow(imgs[0]);
plt.axis('off');
plt.subplot(2, 2, 2);
plt.imshow(imgs[1]);
plt.axis('off');
plt.subplot(2, 2, 3);
plt.imshow(imgs[2]);
plt.axis('off');
plt.subplot(2, 2, 4);
plt.imshow(imgs[3]);
plt.axis('off');
plt.subplots_adjust(wspace=.025, hspace=.025)
st.pyplot(fig1)

fig2 = plt.figure(figsize = (3,3))
plt.subplot(2, 2, 1);
plt.imshow(imgs[0]);
plt.axis('off');
st.pyplot(fig2)

最佳答案

您可以使用 plt.savefig(...) 保存图像,然后使用 st.image 呈现图像,为了获得更高的分辨率,您可以插入 dpi 参数。

import streamlit as st
import numpy as np
import matplotlib.pyplot as plt
import os

imgs = [np.random.random((50,50)) for _ in range(4)]

fig1 = plt.figure(figsize = (3,3))
plt.subplot(2, 2, 1);
plt.imshow(imgs[0]);
plt.axis('off');
plt.subplot(2, 2, 2);
plt.imshow(imgs[1]);
plt.axis('off');
plt.subplot(2, 2, 3);
plt.imshow(imgs[2]);
plt.axis('off');
plt.subplot(2, 2, 4);
plt.imshow(imgs[3]);
plt.axis('off');
plt.subplots_adjust(wspace=.025, hspace=.025)


# save image, display it, and delete after usage.
plt.savefig('x',dpi=400)
st.image('x.png')
os.remove('x.png')

fig2 = plt.figure(figsize = (3,3))
plt.subplot(2, 2, 1);
plt.imshow(imgs[0]);
plt.axis('off');

# save second image, display it, and delete after usage.
plt.savefig('test',dpi=400)
st.image('test.png')
os.remove('test.png')

enter image description here

关于python - streamlit pyplot 子图失真,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69556761/

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