【问题标题】:streamlit pyplot subplot distortionstreamlit pyplot 子图失真
【发布时间】: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)

【问题讨论】:

    标签: python matplotlib streamlit


    【解决方案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')
    

    【讨论】:

    • 非常优雅的解决方法!
    • 这个词,我想说的是'辉煌'!
    猜你喜欢
    • 1970-01-01
    • 2011-02-27
    • 1970-01-01
    • 2011-10-21
    • 1970-01-01
    • 2012-09-09
    • 2021-12-12
    • 2020-05-29
    • 2023-04-04
    相关资源
    最近更新 更多