Issue
I'm plotting images with subplot and it looks different in Jupyter (or "pure python") vs. Streamlit.
For example, if I have a (2 x 2) subplot with just 1 image, it will be stretched in Streamlit.
How I can turn off such stretching?
Plots without Streamlit:
Plots in Streamlit
Code:
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)
Solution
You may save the image by using plt.savefig(...) and then present the image with st.image, for a higher resolution you can insert the dpi parameter.
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')
Answered By - Slava Bugz
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.