Placing plotly graphics into a leaflet - python

Im using the Plotly library for an interactive map in python. However, when you use this library it opens it up in chrome when I want to place the figure onto a leaflet to be used in TKinter
from tkinter import *
import csv
import sys
import plotly.graph_objects as go
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
mapbox_access_token = "pk.eyJ1IjoiY21jY3Vza2VyMTMyMiIsImEiOiJja254YjA5emEwb21rMnB0Z3Nib285OGNkIn0.PL7Nx-Q1XgSO5PBSdI2w2Q"
fig = go.Figure(go.Scattermapbox(
lat=['54.1533'],
lon=['-6.0663'],
mode='markers',
marker=go.scattermapbox.Marker(
size=14
),
text=['Mournes'],
))
fig.update_layout(
hovermode='closest',
mapbox=dict(
accesstoken=mapbox_access_token,
bearing=0,
center=go.layout.mapbox.Center(
lat=54,
lon=-6
),
pitch=0,
zoom=9
)
)
fig.show()
f = fig

Related

I have been trying to display histogram on google colab but it is not showing

I have been trying to display histogram on google colab but it is not showing. Below is the code that is not displaying:
//imports
from chart_studio import plotly
from plotly.offline import init_notebook_mode, iplot
init_notebook_mode(connected=True)
import plotly.graph_objs as go
// code starts from here
trace = go.Histogram(
x = data.defects,
opacity = 0.75,
name = "Defects",
marker = dict(color = 'green'))
hist_data = [trace]
hist_layout = go.Layout(barmode='overlay',
title = 'Defects',
xaxis = dict(title = 'True - False'),
yaxis = dict(title = 'Frequency'),
)
fig = go.Figure(data = hist_data, layout = hist_layout)
iplot(fig) //This is not displaying anything
Try adding this before your code:
%matplotlib inline
import matplotlib.pylab as plt

Plotly - how do I highlight the path to a node on hover?

I have a graph that looks like this:
The segment of code that generates the graph looks something like this:
import sys
import os
import numpy
import itertools
from lxml import etree
import lxml.html
import re
import networkx as nx
import matplotlib.pyplot as plt
import pygraphviz
from networkx.drawing.nx_agraph import graphviz_layout
import plotly.graph_objects as go
G = nx.DiGraph()
#nodes and edges added around here
pos=graphviz_layout(G, prog='dot')
edge_trace = go.Scatter(
x=edge_x, y=edge_y,
line=dict(width=0.5, color='#888'),
hoverinfo='none',
mode='lines')
node_trace = go.Scatter(
x=node_x, y=node_y,
mode='markers',
hoverinfo='text',
marker=dict(size=10,line_width=2)
)
node_trace.marker.color = color_list
node_trace.text = node_text
config = dict({'scrollZoom': True})
fig = go.Figure(data=[edge_trace, node_trace],
layout=go.Layout(
title='Comparison Results: ',
titlefont_size=16,
showlegend=False,
hovermode='closest',
margin=dict(b=80,l=10,r=10,t=40),
annotations=[ dict(
text="",
showarrow=False,
xref="paper", yref="paper",
x=0.005, y=-0.002 ) ],
xaxis=dict(showgrid=False, zeroline=False, showticklabels=False),
yaxis=dict(showgrid=False, zeroline=False, showticklabels=False))
)
fig.update_layout(dragmode='pan')
fig.show(config=config)
How do I make it so that when I hover over a node, the path all the way to the root node is highlighted?
Any help is much appreciated. Thanks in advance!

Plotly: How to display graph after clicking a button?

I want to use plotly to display a graph only after a button is clicked but am not sure how to make this work. My figure is stored in the following code bit
fig1 = go.Figure(data=plot_data, layout=plot_layout)
I then define my app layout with the following code bit:
app.layout = html.Div([
#button
html.Div(className='submit', children=[
html.Button('Forecast', id='submit', n_clicks=0)
]),
#loading
dcc.Loading(
id="loading-1",
type="default",
children=html.Div(id="loading-output-1")
),
#graph
dcc.Graph(id= 'mpg-scatter',figure=fig),
#hoverdata
html.Div([
dcc.Markdown(id='hoverdata-text')
],style={'width':'50%','display':'inline-block'})
])
#app.callback(Output('hoverdata-text','children'),
[Input('mpg-scatter','hoverData')])
def callback_stats(hoverData):
return str(hoverData)
if __name__ == '__main__':
app.run_server()
But the problem is i only want the button displayed at first. Then when someone clicks on the forecast button the loading feature appears and a second later the graph displays. I defined a dcc.loading component but am not sure how to define the callback for this feature.
SUGGESTION 3 - dcc.Store() and dcc.Loading
This suggestion uses a dcc.Store() component, a html.Button() and a dcc.Loading component to produce what I now understand to be the desired setup:
Launch an app that only shows a button.
Click a button to show a loading icon, and then
display a figure.
Click again to show the next figure in a sequence of three figures.
Start again when the figure sequence is exhausted.
Upon launch, the app will look like this:
Now you can click Figures once to get Figure 1 below, but only after enjoying one of the following loading icons: ['graph', 'cube', 'circle', 'dot', or 'default'] of which 'dot' will trigger ptsd, and 'cube' happens to be my favorite:
Loading...
Figure 1
Now you cann keep on clicking for Figure 2 and Figure 3. I've set the loading time for Figure 1 no less than 5 seconds, and then 2 seconds for Figure 2 and Figure 3. But you can easily change that.
When you've clicked more than three times, we start from the beginning again:
I hope I've finally figured out a solution for what you were actually looking for. The setup in the code snippet below builds on the setup described here, but has been adjusted to hopefully suit your needs. Let me know how this works out for you!
import pandas as pd
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, State
import plotly.graph_objects as go
from jupyter_dash import JupyterDash
import dash_table
from dash.exceptions import PreventUpdate
import dash_bootstrap_components as dbc
import time
time.sleep(5) # Delay for 5 seconds.
global_df = pd.DataFrame({'value1':[1,2,3,4],
'value2':[10,11,12,14]})
# app = JupyterDash(__name__)
app = JupyterDash(external_stylesheets=[dbc.themes.SLATE])
df = pd.DataFrame({'Value 1': [1,2,3],
'Value 2':[10,11,12],
'Value 3':[14,12,9]})
df.set_index('Value 1', inplace = True)
app.layout = html.Div([
# The memory store reverts to the default on every page refresh
dcc.Store(id='memory'),
# The local store will take the initial data
# only the first time the page is loaded
# and keep it until it is cleared.
# Same as the local store but will lose the data
# when the browser/tab closes.
html.Table([
html.Thead([
html.Tr(html.Th('Click to launch figure:')),
html.Tr([
html.Th(html.Button('Figures', id='memory-button')),
]),
]),
]),
dcc.Loading(id = "loading-icon",
#'graph', 'cube', 'circle', 'dot', or 'default'
type = 'cube',
children=[html.Div(dcc.Graph(id='click_graph'))])
])
# Create two callbacks for every store.
# add a click to the appropriate store.
#app.callback(Output('memory', 'data'),
[Input('memory-button', 'n_clicks')],
[State('memory', 'data')])
def on_click(n_clicks, data):
if n_clicks is None:
# prevent the None callbacks is important with the store component.
# you don't want to update the store for nothing.
raise PreventUpdate
# Give a default data dict with 0 clicks if there's no data.
data = data or {'clicks': 0}
data['clicks'] = data['clicks'] + 1
if data['clicks'] > 3: data['clicks'] = 0
return data
# output the stored clicks in the table cell.
#app.callback(Output('click_graph', 'figure'),
# Since we use the data prop in an output,
# we cannot get the initial data on load with the data prop.
# To counter this, you can use the modified_timestamp
# as Input and the data as State.
# This limitation is due to the initial None callbacks
# https://github.com/plotly/dash-renderer/pull/81
[Input('memory', 'modified_timestamp')],
[State('memory', 'data')])
def on_data(ts, data):
if ts is None:
#raise PreventUpdate
fig = go.Figure()
fig.update_layout(plot_bgcolor='rgba(0,0,0,0)', paper_bgcolor='rgba(0,0,0,0)',
yaxis = dict(showgrid=False, zeroline=False, tickfont = dict(color = 'rgba(0,0,0,0)')),
xaxis = dict(showgrid=False, zeroline=False, tickfont = dict(color = 'rgba(0,0,0,0)')))
return(fig)
data = data or {}
0
# plotly
y = 'Value 2'
y2 = 'Value 3'
fig = go.Figure()
fig.update_layout(plot_bgcolor='rgba(0,0,0,0)', paper_bgcolor='rgba(0,0,0,0)',
yaxis = dict(showgrid=False, zeroline=False, tickfont = dict(color = 'rgba(0,0,0,0)')),
xaxis = dict(showgrid=False, zeroline=False, tickfont = dict(color = 'rgba(0,0,0,0)')))
if data.get('clicks', 0) == 1:
fig = go.Figure(go.Scatter(name=y, x=df.index, y=df[y], mode = 'lines'))
fig.add_traces(go.Scatter(name=y, x=df.index, y=df[y2], mode = 'lines'))
fig.update_layout(template='plotly_dark',
title = 'Plot number ' + str(data.get('clicks', 0)))
# delay only after first click
time.sleep(2)
if data.get('clicks', 0) == 2:
fig = go.Figure((go.Scatter(name=y, x=df.index, y=df[y], mode = 'lines')))
fig.add_traces(go.Scatter(name=y, x=df.index, y=df[y2], mode = 'lines'))
fig.update_layout(template='seaborn',
title = 'Plot number ' + str(data.get('clicks', 0)))
if data.get('clicks', 0) == 3:
fig = go.Figure((go.Scatter(name=y, x=df.index, y=df[y], mode = 'lines')))
fig.add_traces(go.Scatter(name=y, x=df.index, y=df[y2], mode = 'lines'))
fig.update_layout(template='plotly_white',
title = 'Plot number ' + str(data.get('clicks', 0)))
# Aesthetics
fig.update_layout(margin= {'t':30, 'b':0, 'r': 50, 'l': 50, 'pad': 0},
hovermode = 'x',
legend=dict(x=1,y=0.85),
uirevision='constant')
# delay for every figure
time.sleep(2)
return fig
app.run_server(mode='external', port = 8070, dev_tools_ui=True,
dev_tools_hot_reload =True, threaded=True)
SUGGESTION 2
After a little communation we now know that you'd like to:
only display a button first (question)
when the button is clicked once fig 1 is displayed at the bottom , on 2nd click fig 2 is displayed, and on 3rd click fig 3 is displayed (comment)
I've made a new setup that should meet all criteria above. At first, only the control options are being showed. And then you can select which figure to display: Fig1, Fig2 or Fig3. To me it would seem like a non-optimal user iterface if you have to cycle through your figures in order to select which one you would like to display. So I'v opted for radio buttons such as this:
Now you can freely select your figure to display, or go back to showing nothing again, like this:
Display on startup, or when None is selected:
Figure 1 is selected
You still haven't provided a data sample, so I'm still using my synthetic data from Suggestion 1, and rather letting the different layouts indicate which figure is shown. I hope that suits your needs since it seemed that you would like to have different layouts for the different figures.
Complete code 2
from jupyter_dash import JupyterDash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, State, ClientsideFunction
import dash_bootstrap_components as dbc
import dash_bootstrap_components as dbc
import dash_core_components as dcc
import dash_html_components as html
import pandas as pd
import plotly.graph_objs as go
from dash.dependencies import Input, Output
import numpy as np
from plotly.subplots import make_subplots
import plotly.express as px
pd.options.plotting.backend = "plotly"
from datetime import datetime
palette = px.colors.qualitative.Plotly
# sample data
df = pd.DataFrame({'Prices': [1,10,7,5, np.nan, np.nan, np.nan],
'Predicted_prices':[np.nan, np.nan, np.nan, 5, 8,6,9]})
# app setup
app = JupyterDash(external_stylesheets=[dbc.themes.SLATE])
# controls
controls = dbc.Card(
[dbc.FormGroup(
[
dbc.Label("Options"),
dcc.RadioItems(id="display_figure",
options=[ {'label': 'None', 'value': 'Nope'},
{'label': 'Figure 1', 'value': 'Figure1'},
{'label': 'Figure 2', 'value': 'Figure2'},
{'label': 'Figure 3', 'value': 'Figure3'}
],
value='Nope',
labelStyle={'display': 'inline-block', 'width': '10em', 'line-height':'0.5em'}
)
],
),
dbc.FormGroup(
[dbc.Label(""),]
),
],
body=True,
style = {'font-size': 'large'})
app.layout = dbc.Container(
[
html.H1("Button for predictions"),
html.Hr(),
dbc.Row([
dbc.Col([controls],xs = 4),
dbc.Col([
dbc.Row([
dbc.Col(dcc.Graph(id="predictions")),
])
]),
]),
html.Br(),
dbc.Row([
]),
],
fluid=True,
)
#app.callback(
Output("predictions", "figure"),
[Input("display_figure", "value"),
],
)
def make_graph(display_figure):
# main trace
y = 'Prices'
y2 = 'Predicted_prices'
# print(display_figure)
if 'Nope' in display_figure:
fig = go.Figure()
fig.update_layout(plot_bgcolor='rgba(0,0,0,0)', paper_bgcolor='rgba(0,0,0,0)',
yaxis = dict(showgrid=False, zeroline=False, tickfont = dict(color = 'rgba(0,0,0,0)')),
xaxis = dict(showgrid=False, zeroline=False, tickfont = dict(color = 'rgba(0,0,0,0)')))
return fig
if 'Figure1' in display_figure:
fig = go.Figure(go.Scatter(name=y, x=df.index, y=df[y], mode = 'lines'))
fig.add_traces(go.Scatter(name=y, x=df.index, y=df[y2], mode = 'lines'))
fig.update_layout(template='plotly_dark')
# prediction trace
if 'Figure2' in display_figure:
fig = go.Figure((go.Scatter(name=y, x=df.index, y=df[y], mode = 'lines')))
fig.add_traces(go.Scatter(name=y, x=df.index, y=df[y2], mode = 'lines'))
fig.update_layout(template='seaborn')
if 'Figure3' in display_figure:
fig = go.Figure((go.Scatter(name=y, x=df.index, y=df[y], mode = 'lines')))
fig.add_traces(go.Scatter(name=y, x=df.index, y=df[y2], mode = 'lines'))
fig.update_layout(template='plotly_white')
# Aesthetics
fig.update_layout(margin= {'t':30, 'b':0, 'r': 0, 'l': 0, 'pad': 0})
fig.update_layout(hovermode = 'x')
fig.update_layout(showlegend=True, legend=dict(x=1,y=0.85))
fig.update_layout(uirevision='constant')
fig.update_layout(title = "Prices and predictions")
return(fig)
app.run_server(mode='external', port = 8005)
SUGGESTION 1
This suggestion will focus directly on:
I want to use plotly to display a graph only after a button is clicked
Which means that I don't assume that dcc.Loading() has to be a part of the answer.
I find that dcc.Checklist() is an extremely versatile and user-friendly component. And when set up correctly, it will appear as a button that has to be clicked (or an option that has to be marked) in order to trigger certain functionalities or visualizations.
Here's a basic setup:
dcc.Checklist(
id="display_columns",
options=[{"label": col + ' ', "value": col} for col in df.columns],
value=[df.columns[0]],
labelStyle={'display': 'inline-block', 'width': '12em', 'line-height':'0.5em'}
And here's how it will look like:
Along with, among other things, the following few lines, the dcc.Checklist() component will let you turn the Prediction trace on and off as you please.
# main trace
y = 'Prices'
fig = make_subplots(specs=[[{"secondary_y": True}]])
if 'Prices' in display_columns:
fig.add_trace(go.Scatter(name=y, x=df.index, y=df[y], mode = 'lines'), secondary_y=False)
# prediction trace
if 'Predicted_prices' in display_columns:
fig.add_trace(go.Scatter(name = 'predictions', x=df.index, y=df['Predicted_prices'], mode = 'lines'), secondary_y=False
Adding to that, this setup will easily let you handle multiple predictions for multiple traces if you would like to extend this example further. Give it a try, and let me know how it works out for you. And if something is not clear, then we can dive into the details when you find the time.
Here's how the app will look like with and without Predictions activated:
OFF
ON
Complete code:
from jupyter_dash import JupyterDash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, State, ClientsideFunction
import dash_bootstrap_components as dbc
import dash_bootstrap_components as dbc
import dash_core_components as dcc
import dash_html_components as html
import pandas as pd
import plotly.graph_objs as go
from dash.dependencies import Input, Output
import numpy as np
from plotly.subplots import make_subplots
import plotly.express as px
pd.options.plotting.backend = "plotly"
from datetime import datetime
palette = px.colors.qualitative.Plotly
# sample data
df = pd.DataFrame({'Prices': [1,10,7,5, np.nan, np.nan, np.nan],
'Predicted_prices':[np.nan, np.nan, np.nan, 5, 8,6,9]})
# app setup
app = JupyterDash(external_stylesheets=[dbc.themes.SLATE])
# input controls
controls = dbc.Card(
[dbc.FormGroup(
[
dbc.Label("Options"),
dcc.Checklist(
id="display_columns",
options=[{"label": col + ' ', "value": col} for col in df.columns],
value=[df.columns[0]],
labelStyle={'display': 'inline-block', 'width': '12em', 'line-height':'0.5em'}
#clearable=False,
#multi = True
),
],
),
dbc.FormGroup(
[dbc.Label(""),]
),
],
body=True,
style = {'font-size': 'large'})
app.layout = dbc.Container(
[
html.H1("Button for predictions"),
html.Hr(),
dbc.Row([
dbc.Col([controls],xs = 4),
dbc.Col([
dbc.Row([
dbc.Col(dcc.Graph(id="predictions")),
])
]),
]),
html.Br(),
dbc.Row([
]),
],
fluid=True,
)
#app.callback(
Output("predictions", "figure"),
[Input("display_columns", "value"),
],
)
def make_graph(display_columns):
# main trace
y = 'Prices'
fig = make_subplots(specs=[[{"secondary_y": True}]])
if 'Prices' in display_columns:
fig.add_trace(go.Scatter(name=y, x=df.index, y=df[y], mode = 'lines'), secondary_y=False)
# prediction trace
if 'Predicted_prices' in display_columns:
fig.add_trace(go.Scatter(name = 'predictions', x=df.index, y=df['Predicted_prices'], mode = 'lines'), secondary_y=False)
# Aesthetics
fig.update_layout(margin= {'t':30, 'b':0, 'r': 0, 'l': 0, 'pad': 0})
fig.update_layout(hovermode = 'x')
fig.update_layout(showlegend=True, legend=dict(x=1,y=0.85))
fig.update_layout(uirevision='constant')
fig.update_layout(template='plotly_dark',
plot_bgcolor='#272B30',
paper_bgcolor='#272B30')
fig.update_layout(title = "Prices and predictions")
return(fig)
app.run_server(mode='external', port = 8005)

How to add a horizontal scrollbar to the X axis?

I want to add a (horizontal) scrollbar to the X axis, because the number of points is large. How can I do it?
trace0 = go.Scatter(
x = x1_values,
y = y1_values,
name = "V1"
)
data = [trace0]
layout = dict(title = title,
xaxis = dict(tickmode='linear', tickfont=dict(size=10)),
yaxis = dict(title = "Title")
)
fig = dict(data=data, layout=layout)
iplot(fig)
Using plotly you can add a rangeslider using fig['layout']['xaxis']['rangeslider'] with functionality that exceeds that of a scrollbar:
Plot:
Code:
Here's an example using some random data in an off-line Jupyter Notebook.
# imports
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
from IPython.core.display import display, HTML
import plotly.figure_factory as ff
import plotly.graph_objs as go
import pandas as pd
import numpy as np
# setup
display(HTML("<style>.container { width:35% !important; } .widget-select > select {background-color: gainsboro;}</style>"))
init_notebook_mode(connected=True)
np.random.seed(1)
# random time series sample
df = pd.Series(np.random.randn(1000),index=pd.date_range('1/1/2000', periods=1000)).cumsum().to_frame()+100
df.columns = ['Series1']
# trace / line
trace1 = go.Scatter(
x=df.index,
y=df['Series1'],
name = "AAPL High",
line = dict(color = 'blue'),
opacity = 0.4)
# plot layout
layout = dict(
title='Slider / Scrollbar',
xaxis=dict(
rangeselector=dict(
buttons=list([
dict(count=1,
label='1m',
step='month',
stepmode='backward'),
dict(count=6,
label='6m',
step='month',
stepmode='backward'),
dict(step='all')
])
),
rangeslider=dict(
visible = True
),
type='date'
)
)
# plot figure
data = [trace1]
fig = dict(data=data, layout=layout)
iplot(fig)
For more details take a look here.

Plotly: How to display charts in Spyder?

Since November 2015, plotly is Open-Source and available for python. https://plot.ly/javascript/open-source-announcement/
When trying to do some plots offline, these work in iPython Notebook (version 4.0.4)
But if I try to run them in Spyder (version 2.3.8), i just get the following output:
<IPython.core.display.HTML object>
<IPython.core.display.HTML object>
There's something wrong in my code or the iPython Terminal of Spyder still doesn't support this?
Here goes the example code (taken from https://www.reddit.com/r/IPython/comments/3tibc8/tip_on_how_to_run_plotly_examples_in_offline_mode/)
from plotly.offline import download_plotlyjs, init_notebook_mode, iplot
from plotly.graph_objs import *
init_notebook_mode()
trace0 = Scatter(
x=[1, 2, 3, 4],
y=[10, 11, 12, 13],
mode='markers',
marker=dict(
size=[40, 60, 80, 100],
)
)
data = [trace0]
layout = Layout(
showlegend=False,
height=600,
width=600,
)
fig = dict( data=data, layout=layout )
iplot(fig)
If you'd like to develop your plotly figures in Spyder, perhaps because of Spyders superb variable explorer, you can easily display a non-interactive image by just running fig.show(). Note that this is for newer versions of plotly where you don't have to worry about iplot and plotly.offline.
And if you'd like display your figure in the browser as a fully interactive version, just run:
import plotly.io as pio
pio.renderers.default='browser'
Now your figure will be displayed in your default browser.
To switch back to producing your figure in Spyder, just run:
import plotly.io as pio
pio.renderers.default='svg'
You can check other options too using pio.renderers?:
Renderers configuration
-----------------------
Default renderer: 'svg'
Available rendere <...> wser', 'firefox', 'chrome', 'chromium', 'iframe',
'iframe_connected', 'sphinx_gallery']
You'll find even more details here under Setting the default renderer
Here's a detailed example
Code:
import plotly.graph_objects as go
import plotly.io as pio
#pio.renderers.default = 'svg'
pio.renderers.default = 'browser'
x = ['Product A', 'Product B', 'Product C']
y = [20, 14, 23]
fig = go.Figure(data=[go.Bar(
x=x, y=y,
text=y,
textposition='auto',
)])
fig.show()
Plot:
System info:
Python 3.7.6
Spyder 3.3.1
Plotly 3.2.0
importing plot instead iplot (and changing the last line from iplot(fig) to plot(fig) resolved the problem, at least in python 3:
from plotly.offline import download_plotlyjs, init_notebook_mode, plot
from plotly.graph_objs import *
init_notebook_mode()
trace0 = Scatter(
x=[1, 2, 3, 4],
y=[10, 11, 12, 13],
mode='markers',
marker=dict(
size=[40, 60, 80, 100],
)
)
data = [trace0]
layout = Layout(
showlegend=False,
height=600,
width=600,
)
fig = dict( data=data, layout=layout )
plot(fig)
But instead you could do the following, which is slightly easier:
import plotly
import plotly.graph_objs
plotly.offline.plot({
"data": [
plotly.graph_objs.Scatter( x=[1, 2, 3, 4],
y=[10, 11, 12, 13], mode='markers',
marker=dict(
size=[40, 60, 80, 100]))],
"layout": plotly.graph_objs.Layout(showlegend=False,
height=600,
width=600,
)
})

Categories