I am trying to add a plotly figure as a popup in a marker using folium and several options but none of them have worked for me.
Below I'm trying to add a simple plotly example as a figure.
Here is a piece of code:
import plotly.express as px
import plotly
import json
import folium
geomap = folium.Map([19.715576, -99.20099], zoom_start=9, tiles="OpenStreetMap")
df = px.data.gapminder().query("country=='Canada'")
fig = px.line(df, x="year", y="lifeExp", title='Life expectancy in Canada')
fig.update_layout(margin=dict(t=10,l=10,b=10,r=10))[enter image description here](https://i.sstatic.net/Mjnkh.png)
coor1= [19.742110608748604, -99.01751491998121] #marker position
First with Vega:
figjson = json.loads(fig.to_json())
popup = folium.Popup(max_width=650)
folium.Vega(figjson, height=350, width=650).add_to(popup)
folium.Marker(coor1, popup=popup, icon=folium.Icon(color = "blue", prefix = 'fa', icon = 'plane'), tooltip= "airport").add_to(geomap)
Now with iframe:
fightml = fig.to_html(full_html = True, default_width = 200, default_height = 200)
html = fightml
iframe = folium.IFrame(html=html,width=500, height=300)
popup = folium.Popup(iframe, max_width=500)
folium.Marker(coor1, popup=popup, icon=folium.Icon(color = "blue", prefix = 'fa', icon = 'plane'), tooltip= "airport").add_to(geomap)
Both options have similar results to the first image. Another option with even weirder results is with plain html:
html = """
<iframe \"""" + fightml + """\" width="850" height="400" frameborder="0">
"""
popoup= folium.Popup(folium.Html(html, script=True))
folium.Marker(coor1, popup=popup, icon=folium.Icon(color = "blue", prefix = 'fa', icon = 'plane'), tooltip= "airport").add_to(geomap)
Thank you guys
You can use HTML popups in folium, so save the graph you created with plotly in html format. Next, load the saved file and set it as an IFrame for use in folium. Next, set the popup in folium. Finally, set it to a foilum popup. My approach is to save once, but there may be other more efficient ways.
import plotly.express as px
import folium
import branca
df = px.data.gapminder().query("country=='Canada'")
fig = px.line(df, x="year", y="lifeExp", title='Life expectancy in Canada')
fig.update_layout(margin=dict(t=30,l=10,b=10,r=10))
fig.write_html('/content/popup_map.html')
filepath = 'popup_map.html'
with open(filepath , encoding='utf-8') as f:
html = f.read()
coor1= [19.742110608748604, -99.01751491998121]
geomap = folium.Map([19.715576, -99.20099], zoom_start=9, tiles="OpenStreetMap")
iframe = branca.element.IFrame(html=html, width=500, height=300)
popup = folium.Popup(iframe, max_width=500)
folium.Marker([coor1[0],coor1[1]], popup=popup).add_to(geomap)
geomap