I`m working with RMarkdown and Python, I just created a chunk where I add code relate to the folium library, but I can create the report or show up the map
Chunk setup in my RMarkdown Report, I`m al so working with matplotlib in the same RMarkdown report a nd it works fine
```{r setup,include=FALSE}
library(reticulate)
library(ggplot2)
library(lattice)
library(vembedr)
use_python("C:/Users/renzocrossi/AppData/Local/Programs/Python/Python310/python.exe")
knitr::opts_chunk$set(echo=TRUE,message = FALSE,warning = FALSE)
This is the code in the RMarkdown chunk about folium
```{python}
import folium
m = folium.Map(location = [46.20, 6.144], zoom_start=6, tiles="OpenStreetMap")
fg = folium.FeatureGroup(name="My Map")
fg.add_child(folium.Marker(location=[40.12, 10.1], popup="Hi I'am a Marker",
icon=folium.Icon(color='green')))
m.add_child(fg)
m
```
<folium.folium.Map object at 0x000001F6A1098B20>
I ran the code in Python and didn't get an output either. The only way that I think this would work as-is is in a Jupyter notebook. (I think!)
However, with just a bit more, you can definitely get the map on the document. I added import webbrowswer so that I could export the map as HTML, then render it in R Markdown.
```{python mapper, include=FALSE}
import folium
import webbrowser
m = folium.Map(location = [46.20, 6.144], zoom_start=6, tiles="OpenStreetMap")
fg = folium.FeatureGroup(name="My Map")
fg.add_child(folium.Marker(location=[40.12, 10.1], popup="Hi I'am a Marker",
icon = folium.Icon(color='green')))
m.add_child(fg)
m.save("map.html")
webbrowser.open("map.html")
```
Then outside of the Python chunk (not in any chunk), I called the map.
![](map.html)
![](map.html){width=100% height=800px}
I don't know if you have any default figure sizes set, I didn't for this example. However, the calls of this map rendered this:
By the way, the maps are still completely interactive, as they would be in Python or if rendered directly through R.
For example, I decreased magnification and rendered the following:
I'm currently building an application with Streamlit and I'd like to plot a map which fills the entire background. Is there a way to do so in Streamlit? I have following code:
import streamlit as st
import folium
from streamlit_folium import folium_static
m = folium.Map(location=[-22.908333, -43.196389], zoom_start=11, tiles='OpenStreetMap')
folium_static(m)
But the generated map does not fill all the browser available space. I'd like to fill the browser available space like in the example below
Example that I found on the internet:
You can set your Streamlit app to use wide mode with st.set_page_config(layout="wide").
It needs to be the first streamlit call you make (i.e. first thing you do after importing streamlit). This will allow you to make use of the whole screen.
import streamlit as st
import folium
from streamlit_folium import folium_static
st.set_page_config(layout="wide")
m = folium.Map(location=[-22.908333, -43.196389], zoom_start=11, tiles='OpenStreetMap')
folium_static(m)
And I don't know about the streamlit_folium, you may need to increase the plot size
pandas dataframes are displayed nicely within the ipython cell. How does it do it?
The regular ways of getting the console width for Python do not seem to work for ipython cells.
If you just want to see what is the size you can use this script:
from IPython.display import display, HTML
js = """<script>
alert($( ".cell").width())
</script>"""
display(HTML(js))
If you want to use in code you can assign it to a variable and use it in next cell:
from IPython.display import display, HTML
js = """<script>
IPython.notebook.kernel.execute("cell_width="+($( ".cell").width()))
</script>"""
display(HTML(js))
In the next cell:
print(cell_width)
Here's a dummy script that makes three plots and saves them to PDF.
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
df = pd.DataFrame({"A":np.random.normal(100),
"B":np.random.chisquare(5, size = 100),
"C":np.random.gamma(5,size = 100)})
for i in df.columns:
plt.hist(df[i])
plt.savefig(i+".pdf", format = "pdf")
plt.close()
I'm using spyder, which uses IPython. When I run this script, three windows pop at me and then go away. It works, but it's a little annoying.
How can I make the figures get saved to pdf without ever being rendered on my screen?
I'm looking for something like R's
pdf("path/to/plot/name.pdf")
commands
dev.off()
inasmuch as nothing gets rendered on the screen, but the pdf gets saved.
Aha. Partially based on the duplicate suggestion (which wasn't exactly a duplicate), this works:
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
df = pd.DataFrame({"A":np.random.normal(100),
"B":np.random.chisquare(5, size = 100),
"C":np.random.gamma(5,size = 100)})
import matplotlib
old_backend = matplotlib.get_backend()
matplotlib.use("pdf")
for i in df.columns:
plt.hist(df[i])
plt.savefig(i+".pdf", format = "pdf")
plt.close()
matplotlib.use(old_backend)
Basically, set the backend to something like a pdf device, and then set it back to whatever you're accustomed to.
I am referring you to this StackOverflow answer which cites this article as an answer. In the SO answer they also suggest plt.ioff() but are concerned that it could disable other functionality should you want it.
I would like to use an IPython notebook as a way to interactively analyze some genome charts I am making with Biopython's GenomeDiagram module. While there is extensive documentation on how to use matplotlib to get graphs inline in IPython notebook, GenomeDiagram uses the ReportLab toolkit which I don't think is supported for inline graphing in IPython.
I was thinking, however, that a way around this would be to write out the plot/genome diagram to a file and then open the image inline which would have the same result with something like this:
gd_diagram.write("test.png", "PNG")
display(file="test.png")
However, I can't figure out how to do this - or know if it's possible. So does anyone know if images can be opened/displayed in IPython?
Courtesy of this post, you can do the following:
from IPython.display import Image
Image(filename='test.png')
(official docs)
If you are trying to display an Image in this way inside a loop, then you need to wrap the Image constructor in a display method.
from IPython.display import Image, display
listOfImageNames = ['/path/to/images/1.png',
'/path/to/images/2.png']
for imageName in listOfImageNames:
display(Image(filename=imageName))
Note, until now posted solutions only work for png and jpg!
If you want it even easier without importing further libraries or you want to display an animated or not animated GIF File in your Ipython Notebook. Transform the line where you want to display it to markdown and use this nice short hack!
![alt text](test.gif "Title")
This will import and display a .jpg image in Jupyter (tested with Python 2.7 in Anaconda environment)
from IPython.display import display
from PIL import Image
path="/path/to/image.jpg"
display(Image.open(path))
You may need to install PIL
in Anaconda this is done by typing
conda install pillow
If you want to efficiently display big number of images I recommend using IPyPlot package
import ipyplot
ipyplot.plot_images(images_array, max_images=20, img_width=150)
There are some other useful functions in that package where you can display images in interactive tabs (separate tab for each label/class) which is very helpful for all the ML classification tasks.
You could use in html code in markdown section:
example:
<img src="https://www.tensorflow.org/images/colab_logo_32px.png" />
A cleaner Python3 version that use standard numpy, matplotlib and PIL. Merging the answer for opening from URL.
import matplotlib.pyplot as plt
from PIL import Image
import numpy as np
pil_im = Image.open('image.png') #Take jpg + png
## Uncomment to open from URL
#import requests
#r = requests.get('https://www.vegvesen.no/public/webkamera/kamera?id=131206')
#pil_im = Image.open(BytesIO(r.content))
im_array = np.asarray(pil_im)
plt.imshow(im_array)
plt.show()
Courtesy of this page, I found this worked when the suggestions above didn't:
import PIL.Image
from cStringIO import StringIO
import IPython.display
import numpy as np
def showarray(a, fmt='png'):
a = np.uint8(a)
f = StringIO()
PIL.Image.fromarray(a).save(f, fmt)
IPython.display.display(IPython.display.Image(data=f.getvalue()))
from IPython.display import Image
Image(filename =r'C:\user\path')
I've seen some solutions and some wont work because of the raw directory, when adding codes like the one above, just remember to add 'r' before the directory. this should avoid this kind of error: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape
If you are looking to embed your image into ipython notebook from the local host, you can do the following:
First: find the current local path:
# show current directory
import os
cwd = os.getcwd()
cwd
The result for example would be:
'C:\\Users\\lenovo\\Tutorials'
Next, embed your image as follows:
from IPython.display import display
from PIL import Image
path="C:\\Users\\lenovo\\Tutorials\\Data_Science\\DS images\\your_image.jpeg"
display(Image.open(path))
Make sure that you choose the right image type among jpg, jpeg or png.
Another option for plotting inline from an array of images could be:
import IPython
def showimg(a):
IPython.display.display(PIL.Image.fromarray(a))
where a is an array
a.shape
(720, 1280, 3)
You can directly use this instead of importing PIL
from IPython.display import Image, display
display(Image(base_image_path))
Another opt is:
from matplotlib import pyplot as plt
from io import BytesIO
from PIL import Image
import Ipython
f = BytesIO()
plt.savefig(f, format='png')
Ipython.display.display(Ipython.display.Image(data=f.getvalue()))
f.close()
When using GenomeDiagram with Jupyter (iPython), the easiest way to display images is by converting the GenomeDiagram to a PNG image. This can be wrapped using an IPython.display.Image object to make it display in the notebook.
from Bio.Graphics import GenomeDiagram
from Bio.SeqFeature import SeqFeature, FeatureLocation
from IPython.display import display, Image
gd_diagram = GenomeDiagram.Diagram("Test diagram")
gd_track_for_features = gd_diagram.new_track(1, name="Annotated Features")
gd_feature_set = gd_track_for_features.new_set()
gd_feature_set.add_feature(SeqFeature(FeatureLocation(25, 75), strand=+1))
gd_diagram.draw(format="linear", orientation="landscape", pagesize='A4',
fragments=1, start=0, end=100)
Image(gd_diagram.write_to_string("PNG"))
[See Notebook]
This is the solution using opencv-python, but it opens new windows which is busy in waiting
import cv2 # pip install opencv-python
image = cv2.imread("foo.png")
cv2.imshow('test',image)
cv2.waitKey(duration) # in milliseconds; duration=0 means waiting forever
cv2.destroyAllWindows()
if you don't want to display image in another window, using matplotlib or whatever instead cv2.imshow()
import cv2
import matplotlib.pyplot as plt
image = cv2.imread("foo.png")
plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
plt.show()