I am am trying out colaboratory with plotly notebook mode - I open a new notebook, copy and paste the following simple example from plotly's documentation, but don't see an output. There is a large blank in the output space where the plot whould normally be.
This works fine in my local notebook (which is a newer version of plotly, but per their docs offline mode should work with the google colab version)
Any ideas?
import plotly
from plotly.graph_objs import Scatter, Layout
plotly.offline.init_notebook_mode(connected=True)
plotly.offline.iplot({
"data": [Scatter(x=[1, 2, 3, 4], y=[4, 3, 2, 1])],
"layout": Layout(title="hello world")
})
plotly version 4.x
As of version 4, plotly renderers know about Colab, so the following is sufficient to display a figure in both Colab and Jupyter (and other notebooks like Kaggle, Azure, nteract):
import plotly.graph_objects as go
fig = go.Figure( go.Scatter(x=[1,2,3], y=[1,3,2] ) )
fig.show()
plotly version 3.x
Here's an example showing the use of Plotly in Colab. (Plotly requires custom initialization.)
https://colab.research.google.com/notebook#fileId=14oudHx5e5r7hm1QcbZ24FVHXgVPD0k8f
You need to define this function:
def configure_plotly_browser_state():
import IPython
display(IPython.core.display.HTML('''
<script src="/static/components/requirejs/require.js"></script>
<script>
requirejs.config({
paths: {
base: '/static/base',
plotly: 'https://cdn.plot.ly/plotly-latest.min.js?noext',
},
});
</script>
'''))
And call it in each offline plotting cell:
configure_plotly_browser_state()
simply pass "colab" as the value for the parameter renderer in fig.show(renderer="colab")
example :
import plotly.graph_objects as go
fig = go.Figure(
data=[go.Bar(y=[2, 1, 3])],
layout_title_text="A Figure Displayed with the 'colab' Renderer"
)
fig.show(renderer="colab")
Solution
import plotly.io as pio
pio.renderers.default = "colab"
You need to change the default render. Here is an excerpt from the documentation.
https://plot.ly/python/renderers/#setting-the-default-renderer
The current and available renderers are configured using the
plotly.io.renderers configuration object. Display this object to see
the current default renderer and the list of all available renderers.
>>>import plotly.io as pio
>>>pio.renderers
Renderers configuration
-----------------------
Default renderer: 'notebook_connected'
Available renderers:
['plotly_mimetype', 'jupyterlab', 'nteract', 'vscode',
'notebook', 'notebook_connected', 'kaggle', 'azure', 'colab',
'cocalc', 'databricks', 'json', 'png', 'jpeg', 'jpg', 'svg',
'pdf', 'browser', 'firefox', 'chrome', 'chromium', 'iframe',
'iframe_connected', 'sphinx_gallery']
You need to add a method in order to use Plotly in Colab.
def enable_plotly_in_cell():
import IPython
from plotly.offline import init_notebook_mode
display(IPython.core.display.HTML('''<script src="/static/components/requirejs/require.js"></script>'''))
init_notebook_mode(connected=False)
This method must be executed for every cell which is displaying a Plotly graph.
Sample:
from plotly.offline import iplot
import plotly.graph_objs as go
enable_plotly_in_cell()
data = [
go.Contour(
z=[[10, 10.625, 12.5, 15.625, 20],
[5.625, 6.25, 8.125, 11.25, 15.625],
[2.5, 3.125, 5., 8.125, 12.5],
[0.625, 1.25, 3.125, 6.25, 10.625],
[0, 0.625, 2.5, 5.625, 10]]
)
]
iplot(data)
Reference: https://colab.research.google.com/notebooks/charts.ipynb#scrollTo=WWbPMtDkO4xg
configure_plotly_browser_state() can be executed before running every cell by using IPython's pre_run_cell hook:
import IPython
IPython.get_ipython().events.register('pre_run_cell', configure_plotly_browser_state)
Related
I am working locally(in my pc) just testing and learning PLOTLY 3.7.5.
with anaconda env active.
The code example is given by plotly
Code:
import plotly.plotly as py # Here all begins (Look)
# import chart_studio.plotly as py # inted of the line bellow (optional to try)
import plotly.graph_objs as go
import pandas as pd
from datetime import datetime
if __name__ == '__main__':
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/finance-charts-apple.csv')
trace = go.Ohlc(x=df['Date'],
open=df['AAPL.Open'],
high=df['AAPL.High'],
low=df['AAPL.Low'],
close=df['AAPL.Close'])
data = [trace]
py.iplot(data, filename='simple_ohlc')
note (Look): I got the warning error:
'please install the chart-studio package and use the chart_studio.plotly module instead.'
You need plotly's offline mode to obviate authentication - following https://stackoverflow.com/a/44694854/1021819, rather do:
from plotly.offline import iplot
use below line of code before hitting pilot
cf.go_offline() #will make cufflinks offline
cf.set_config_file(offline=False, world_readable=True)
import pandas as pd
import numpy as np
%matplotlib inline
import plotly.graph_objs as go
from plotly.offline import plot
import chart_studio.plotly as py
import cufflinks as cf
cf.go_offline()
from plotly.offline import download_plotlyjs, init_notebook_mode, plot,iplot
init_notebook_mode(connected='true')
df = pd.DataFrame(np.random.randn(100,4),columns='A B C D'.split())
df.head()
df.iplot(kind='box')
Basics for starting Plotly and Cufflinks section:
import pandas as pd
import numpy as np
%matplotlib inline
from plotly import __version__
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
import cufflinks as cf
init_notebook_mode(connected=True)
cf.go_offline()
Call these two below library automatically problem will be solved
import chart_studio.plotly as py
I created a scatter plot on indian map in jupyter notebook but when i am trying to run the same code in my djnago app. It raises
ModuleNotFoundError: No module named 'mpl_toolkits.basemap'
Here's the code:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
# make up some data for scatter plot
lats = np.random.randint(6, 37, size=50)
lons = np.random.randint(68, 97, size=50)
fig = plt.gcf()
fig.set_size_inches(8, 6.5)
m = Basemap(projection='cyl', \
llcrnrlat=6., urcrnrlat=37., \
llcrnrlon=68., urcrnrlon=97., \
lat_ts=20, \
resolution='c',epsg=3857)
m.bluemarble(scale=1)
m.drawcoastlines(color='white', linewidth=0.2)
m.drawmapboundary(fill_color='#D3D3D3')
x, y = m(lons, lats)
plt.scatter(x, y, 10, marker='o', color='Red')
plt.show()
I am using the same conda interpreter in my django app. whats is the reason for this error ?
I use Anaconda under Win10. With a different OS or installation the solution may be different for you, but I can try to sketch the path.
You have to install Basemap. See here and here. For me conda install -c conda-forge basemap-data-hires did work.
When importing from mpl_toolkits.basemap import Basemap I got an error: KeyError: PROJ_LIB. Following the experiences here you must find a directory share with epsg inside. It is expected to be in the conda or the anaconda directory.
I did a search in my Anaconda3-dirctory and have found this path: "C:\Anaconda3\Library\share"
Then the following code did work for me (and your code gives a nice picture too :-) :
import os
proj_lib = "C:\Anaconda3\Library\share"
os.environ["PROJ_LIB"] = proj_lib
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
plt.figure(figsize=(8, 8))
m = Basemap(projection='ortho', resolution=None, lat_0=50, lon_0=-100)
m.bluemarble(scale=0.5);
I just copy and paste the first batch of code from :
https://dash.plot.ly/getting-started to my Jupyter notebook and this what I am getting:
Running on http://127.0.0.1:8050/
Debugger PIN: 124-434-522
Debugger PIN: 124-434-522
Debugger PIN: 124-434-522
Debugger PIN: 124-434-522
* Serving Flask app "__main__" (lazy loading)
* Environment: production
WARNING: Do not use the development server in a production environment.
Use a production WSGI server instead.
* Debug mode: on
An exception has occurred, use %tb to see the full traceback.
SystemExit: 1
Any help will be more than appreciated.
(Updated comment)
I have aslo tried google colab. Unfortunately it doesn't work on it neither. this is what I am getting:
# -*- coding: utf-8 -*-
import dash
import dash_core_components as dcc
import dash_html_components as html
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
app.layout = html.Div(children=[
html.H1(children='Hello Dash'),
html.Div(children='''
Dash: A web application framework for Python.
'''),
dcc.Graph(
id='example-graph',
figure={
'data': [
{'x': [1, 2, 3], 'y': [4, 1, 2], 'type': 'bar', 'name': 'SF'},
{'x': [1, 2, 3], 'y': [2, 4, 5], 'type': 'bar', 'name': u'Montréal'},
],
'layout': {
'title': 'Dash Data Visualization'
}
}
)
])
if __name__ == '__main__':
app.run_server(debug=True)
ModuleNotFoundError Traceback (most recent call last)
in ()
----> 1 import dash
2 import dash_core_components as dcc
3 import dash_html_components as html
4
5 external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
ModuleNotFoundError: No module named 'dash'
(Second update)
I am running the same script in Atom. Unfortunately it doesn't seen to be working:
I don't understand what I am doing wrong.
This is the tutorial you are looking for https://plot.ly/python/ipython-notebook-tutorial/. As Alexander explained Dash is a web server. If you are just learning python and want to plot stuff with Jupyter, running a webserver is not what you need. Instead you have to install a plot library like plotly or my favorite matplotlib. To install it, you would run ! pip install plotly from inside Jupyter. The tutorial will walk you through it.
Your last picture shows that dash is working perfectly fine
Go to the URL that is indicated in the terminal
You can not use debug=True with Jupyter Notebook. Change to False or else run the code from a code editor/IDE.
I need to plot my data using plotly, But this code doesn't give me any result, I display my data, but without any figure:
import plotly.graph_objs as go
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
data_t = []
for mac, dico_data in dict_info.items():
data_t.append(go.Scatter( x= dico_data['asn'], y= dico_data["time"], name=mac ))
print (data_t)
data = data_t
iplot(data_t)
Try using:
init_notebook_mode(connected=True)
Or try using the inline mode in notebooks:
py.init_notebook_mode()
And if you are using it out of a notebook, try the following example:
import plotly
import plotly.graph_objs as go
plotly.offline.plot({
"data": [go.Scatter(x=[1, 2, 3, 4], y=[4, 3, 2, 1])],
"layout": go.Layout(title="hello world")
}, auto_open=True)
Read more in the plotly documentation: https://plot.ly/python/offline/
Issue:
Due to inbuilt restriction in browser, you need to install
plotly-extension
Solution:
Install it if missing with:
jupyter labextension install #jupyterlab/plotly-extension
Reference:
https://jupyterlab.readthedocs.io/en/stable/user/extensions.html
I am using the below the script in python:
from plotly.offline import init_notebook_mode, iplot
import plotly.plotly as py
from plotly.graph_objs import *
from plotly.plotly.plotly import image
X=[1,2,3]
Y=[1,2,3]
fig = {'data': [{'x': X, 'y': Y, 'type': 'bar'}]}
#iplot([{"x": X, "y": Y}])
image.ishow(fig, 'png', scale=3)
I started ipython-notebook in ubuntu-PC also,but I am not able to visualize the image created or the chart plotted.
The Output is coming like this when I uncommented iplot statement:
and it returns raise exceptions.PlotlyError(return_data['error'])
KeyError: 'error .
How to plot the using plot and how to see that?
My first thought is you haven't told plotly to work in notebook mode with:
init_notebook_mode()
You imported it but never ran it.
From: https://plot.ly/python/offline/