streamlit pyplot 子图失真
Posted
技术标签:
【中文标题】streamlit pyplot 子图失真【英文标题】:streamlit pyplot subplot distortion 【发布时间】:2021-12-02 00:11:29 【问题描述】:我正在使用 subplot 绘制图像,它在 Jupyter(或“纯 python”)与 Streamlit 中看起来不同。
例如,如果我有一个只有 1 张图像 的 (2 x 2) 子图,它将在 Streamlit 中拉伸。
我怎样才能关闭这种拉伸?
没有 Streamlit 的绘图:
Streamlit 中的绘图
代码:
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)
【问题讨论】:
【参考方案1】:您可以使用 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')
【讨论】:
非常优雅的解决方法! 这个词,我想说的是'辉煌'!以上是关于streamlit pyplot 子图失真的主要内容,如果未能解决你的问题,请参考以下文章
matplotlib.pyplot.subplots_adjust