diff --git a/_posts/python-next/chart-studio/2019-07-03-data-api.html b/_posts/python-next/chart-studio/2019-07-03-data-api.html new file mode 100644 index 000000000000..ff8a3e3a7cb8 --- /dev/null +++ b/_posts/python-next/chart-studio/2019-07-03-data-api.html @@ -0,0 +1,701 @@ +--- +description: How to upload data to Plotly from Python with the Plotly Grid API. +display_as: chart_studio +has_thumbnail: True +language: python/next +layout: user-guide +name: Plots from Grids +order: 5 +page_type: u-guide +permalink: python/next/data-api/ +thumbnail: thumbnail/table.jpg +title: Plotly Data API +v4upgrade: True +--- + +{% raw %} + +
You can instantiate a grid with data by either uploading tabular data to Plotly or by creating a Plotly grid
using the API. To upload the grid we will use plotly.plotly.grid_ops.upload()
. It takes the following arguments:
grid
(Grid Object): the actual grid object that you are uploading.filename
(str): name of the grid in your plotly account,world_readable
(bool): if True
, the grid is public
and can be viewed by anyone in your files. If False
, it is private and can only be viewed by you.auto_open
(bool): if determines if the grid is opened in the browser or not.You can run help(py.grid_ops.upload)
for a more detailed description of these and all the arguments.
import chart_studio
+import chart_studio.plotly as py
+import chart_studio.tools as tls
+import plotly.graph_objects as go
+from chart_studio.grid_objs import Column, Grid
+
+from datetime import datetime as dt
+import numpy as np
+from IPython.display import IFrame
+
+column_1 = Column(['a', 'b', 'c'], 'column 1')
+column_2 = Column([1, 2, 3], 'column 2') # Tabular data can be numbers, strings, or dates
+grid = Grid([column_1, column_2])
+url = py.grid_ops.upload(grid,
+ filename='grid_ex_'+str(dt.now()),
+ world_readable=True,
+ auto_open=False)
+print(url)
+
You can view your newly created grid at the url
:
IFrame(src= url.rstrip('/') + ".embed", width="100%",height="200px", frameBorder="0")
+
You are also able to view the grid in your list of files inside your organize folder.
+ +Along with uploading a grid, you can upload a Dataframe as well as convert it to raw data as a grid:
+ +import chart_studio.plotly as py
+import plotly.figure_factory as ff
+
+import pandas as pd
+
+df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/2014_apple_stock.csv')
+df_head = df.head()
+table = ff.create_table(df_head)
+py.iplot(table, filename='dataframe_ex_preview')
+
Plotly graphs are usually described with data embedded in them. For example, here we place x
and y
data directly into our Histogram2dContour
object:
x = np.random.randn(1000)
+y = np.random.randn(1000) + 1
+
+data = [
+ go.Histogram2dContour(
+ x=x,
+ y=y
+ )
+]
+
+py.iplot(data, filename='Example 2D Histogram Contour')
+
We can also create graphs based off of references to columns of grids. Here, we'll upload several column
s to our Plotly account:
column_1 = Column(np.random.randn(1000), 'column 1')
+column_2 = Column(np.random.randn(1000)+1, 'column 2')
+column_3 = Column(np.random.randn(1000)+2, 'column 3')
+column_4 = Column(np.random.randn(1000)+3, 'column 4')
+
+grid = Grid([column_1, column_2, column_3, column_4])
+url = py.grid_ops.upload(grid, filename='randn_int_offset_'+str(dt.now()))
+print(url)
+
IFrame(src= url.rstrip('/') + ".embed", width="100%",height="200px", frameBorder="0")
+
Instead of placing data into x
and y
, we'll place our Grid columns into xsrc
and ysrc
:
data = [
+ go.Histogram2dContour(
+ xsrc=grid[0],
+ ysrc=grid[1]
+ )
+]
+
+py.iplot(data, filename='2D Contour from Grid Data')
+
So, when you view the data, you'll see your original grid, not just the columns that compose this graph:
+ +In Chart Studio Enterprise, you can upload and assign free-form JSON metadata
to any grid object. This means that you can keep all of your raw data in one place, under one grid.
If you update the original data source, in the workspace or with our API, all of the graphs that are sourced from it will be updated as well. You can make multiple graphs from a single Grid and you can make a graph from multiple grids. You can also add rows and columns to existing grids programatically.
+ +meta = {
+ "Month": "November",
+ "Experiment ID": "d3kbd",
+ "Operator": "James Murphy",
+ "Initial Conditions": {
+ "Voltage": 5.5
+ }
+}
+
+grid_url = py.grid_ops.upload(grid, filename='grid_with_metadata_'+str(dt.now()), meta=meta)
+print(url)
+
help(py.grid_ops)
+
In additional to importing python's requests
and json
packages, this tutorial also uses Plotly's REST API
First define YOUR username and api key and create auth
and headers
to use with requests
import chart_studio
+import chart_studio.plotly as py
+
+import json
+import requests
+from requests.auth import HTTPBasicAuth
+
+username = 'private_plotly' # Replace with YOUR USERNAME
+api_key = 'k0yy0ztssk' # Replace with YOUR API KEY
+
+auth = HTTPBasicAuth(username, api_key)
+headers = {'Plotly-Client-Platform': 'python'}
+
+chart_studio.tools.set_credentials_file(username=username, api_key=api_key)
+
url = py.plot({"data": [{"x": [1, 2, 3],
+ "y": [4, 2, 4]}],
+ "layout": {"title": "Let's Trash This Plot<br>(then restore it)"}},
+ filename='trash example')
+
+url
+
Include the file id in your request.
The file id is your username:plot_id#
fid = username+':658'
+fid
+
The following request moves the plot from the organize folder into the trash.
Note: a successful trash request will return a Response [200]
.
requests.post('https://api.plot.ly/v2/files/'+fid+'/trash', auth=auth, headers=headers)
+
Now if you visit the url, the plot won't be there.
However, at this point, there is the option to restore the plot (i.e. move it out of trash and back to the organize folder) with the following request:
This request CANNOT!!!!!!! be restored.
+Only use permanent_delete
when absolutely sure the plot is no longer needed.
url = py.plot({"data": [{"x": [1, 2, 3],
+ "y": [3, 2, 1]}],
+ "layout": {"title": "Let's Delete This Plot<br><b>FOREVER!!!!</b>"}},
+ filename='PERMANENT delete ex')
+url
+
fid_permanent_delete = username+':661'
+fid_permanent_delete
+
To PERMANENTLY delete a plot, first move the plot to the trash (as seen above):
+ +requests.post('https://api.plot.ly/v2/files/'+fid_permanent_delete+'/trash', auth=auth, headers=headers)
+
Then permanent delete.
+Note: a successful permanent delete request will return a Response [204]
(No Content).
requests.delete('https://api.plot.ly/v2/files/'+fid_permanent_delete+'/permanent_delete', auth=auth, headers=headers)
+
In order to delete all plots and grids permanently, you need to delete all of your plots first, then delete all the associated grids.
+ +def get_pages(username, page_size):
+ url = 'https://api.plot.ly/v2/folders/all?user='+username+'&page_size='+str(page_size)
+ response = requests.get(url, auth=auth, headers=headers)
+ if response.status_code != 200:
+ return
+ page = json.loads(response.content)
+ yield page
+ while True:
+ resource = page['children']['next']
+ if not resource:
+ break
+ response = requests.get(resource, auth=auth, headers=headers)
+ if response.status_code != 200:
+ break
+ page = json.loads(response.content)
+ yield page
+
+def permanently_delete_files(username, page_size=500, filetype_to_delete='plot'):
+ for page in get_pages(username, page_size):
+ for x in range(0, len(page['children']['results'])):
+ fid = page['children']['results'][x]['fid']
+ res = requests.get('https://api.plot.ly/v2/files/' + fid, auth=auth, headers=headers)
+ res.raise_for_status()
+ if res.status_code == 200:
+ json_res = json.loads(res.content)
+ if json_res['filetype'] == filetype_to_delete:
+ # move to trash
+ requests.post('https://api.plot.ly/v2/files/'+fid+'/trash', auth=auth, headers=headers)
+ # permanently delete
+ requests.delete('https://api.plot.ly/v2/files/'+fid+'/permanent_delete', auth=auth, headers=headers)
+
+permanently_delete_files(username, filetype_to_delete='plot')
+permanently_delete_files(username, filetype_to_delete='grid')
+
Plotly graphs can be embedded in any HTML page. This includes IPython notebooks, Wordpress sites, dashboards, blogs, and more.
+For more on embedding Plotly graphs in HTML documents, see our tutorial.
+From Python, you can generate the HTML code to embed Plotly graphs with the plotly.tools.get_embed
function.
import chart_studio.tools as tls
+
+tls.get_embed('https://plot.ly/~chris/1638')
+
import chart_studio.plotly as py
+# Learn about API authentication here: https://plot.ly/python/getting-started
+# Find your api_key here: https://plot.ly/settings/api
+
+fig = py.get_figure("https://plot.ly/~PlotBot/5")
+
+fig['layout']['title'] = "Never forget that title!"
+
+py.iplot(fig, filename="python-change_plot")
+
import chart_studio.plotly as py
+import plotly.graph_objects as go
+# Learn about API authentication here: https://plot.ly/python/getting-started
+# Find your api_key here: https://plot.ly/settings/api
+
+data = py.get_figure("https://plot.ly/~PythonPlotBot/3483").data
+distance = [d['y'][0] for d in data] # check out the data for yourself!
+
+fig = go.Figure()
+fig.add_histogram(y=distance, name="flyby distance", histnorm='probability')
+xaxis = dict(title="Probability for Flyby at this Distance")
+yaxis = dict(title="Distance from Earth (Earth Radii)")
+fig.update_layout(title="data source: https://plot.ly/~AlexHP/68", xaxis=xaxis, yaxis=yaxis)
+
+plot_url = py.plot(fig, filename="python-get-data")
+
import chart_studio.plotly as py
+# Learn about API authentication here: https://plot.ly/python/getting-started
+# Find your api_key here: https://plot.ly/settings/api
+
+fig = py.get_figure("https://plot.ly/~PlotBot/5")
+
+plot_url = py.plot(fig, filename="python-replot1")
+
import chart_studio.plotly as py
+# Learn about API authentication here: https://plot.ly/python/getting-started
+# Find your api_key here: https://plot.ly/settings/api
+
+fig = py.get_figure("PlotBot", 5)
+
+plot_url = py.plot(fig, filename="python-replot2")
+
To install Chart Studio's python package, use the package manager pip inside your terminal.
+If you don't have pip installed on your machine, click here for pip's installation instructions.
+
+
+$ pip install chart_studio
+
or
+$ sudo pip install chart_studio
+
+
+Plotly's Python package is installed alongside the Chart Studio package and it is updated frequently! To upgrade, run:
+
+
+$ pip install plotly --upgrade
Chart Studio provides a web-service for hosting graphs! Create a free account to get started. Graphs are saved inside your online Chart Studio account and you control the privacy. Public hosting is free, for private hosting, check out our paid plans.
+
+
+After installing the Chart Studio package, you're ready to fire up python:
+
+
+$ python
+
+
+and set your credentials:
import chart_studio
+chart_studio.tools.set_credentials_file(username='DemoAccount', api_key='lr1c37zw81')
+
You'll need to replace 'DemoAccount' and 'lr1c37zw81' with your Plotly username and API key.
+Find your API key here.
+
+
+The initialization step places a special .plotly/.credentials file in your home directory. Your ~/.plotly/.credentials file should look something like this:
+
{
+ "username": "DemoAccount",
+ "stream_ids": ["ylosqsyet5", "h2ct8btk1s", "oxz4fm883b"],
+ "api_key": "lr1c37zw81"
+}
+
+Plot can be set to three different type of privacies: public, private or secret.
+By default all plots are set to public. Users with free account have the permission to keep one private plot. If you need to save private plots, upgrade to a pro account. If you're a Personal or Professional user and would like the default setting for your plots to be private, you can edit your Chart Studio configuration:
+ +import chart_studio
+chart_studio.tools.set_config_file(world_readable=False,
+ sharing='private')
+
For more examples on privacy settings please visit Python privacy documentation
+ +Your API key for account on the public cloud will be different than the API key in Chart Studio Enterprise. Visit https://plotly.your-company.com/settings/api/ to find your Chart Studio Enterprise API key. Remember to replace "your-company.com" with the URL of your Chart Studio Enterprise server.
+If your company has a Chart Studio Enterprise server, change the Python API endpoint so that it points to your company's Plotly server instead of Plotly's cloud.
+
+
+In python, enter:
import chart_studio
+chart_studio.tools.set_config_file(plotly_domain='https://plotly.your-company.com',
+ plotly_streaming_domain='https://stream-plotly.your-company.com')
+
Make sure to replace "your-company.com" with the URL of your Chart Studio Enterprise server.
+ +Additionally, you can set your configuration so that you generate private plots by default. For more information on privacy settings see: https://plot.ly/python/privacy/
+
+In python, enter:
import chart_studio
+chart_studio.tools.set_config_file(plotly_domain='https://plotly.your-company.com',
+ plotly_streaming_domain='https://stream-plotly.your-company.com',
+ world_readable=False,
+ sharing='private')
+
Python's virtualenv
allows us create multiple working Python environments which can each use different versions of packages. We can use virtualenv
from the command line to create an environment using plotly.py version 3.3.0 and a separate one using plotly.py version 2.7.0. See the virtualenv documentation for more info.
Install virtualenv globally
+$ sudo pip install virtualenv
Create your virtualenvs
+$ mkdir ~/.virtualenvs
+$ cd ~/.virtualenvs
+$ python -m venv plotly2.7
+$ python -m venv plotly3.3
Activate the virtualenv.
+You will see the name of your virtualenv in parenthesis next to the input promt.
+$ source ~/.virtualenvs/plotly2.7/bin/activate
+(plotly2.7) $
Install plotly locally to virtualenv (note that we don't use sudo).
+(plotly2.7) $ pip install plotly==2.7
Deactivate to exit
+
+(plotly2.7) $ deactivate
+$
Install Jupyter into a virtualenv
+$ source ~/.virtualenvs/plotly3.3/bin/activate
+(plotly3.3) $ pip install notebook
Start the Jupyter kernel from a virtualenv
+(plotly3.3) $ jupyter notebook
When plotting online, the plot and data will be saved to your cloud account. There are two methods for plotting online: py.plot()
and py.iplot()
. Both options create a unique url for the plot and save it in your Plotly account.
py.plot()
to return the unique url and optionally open the url.py.iplot()
when working in a Jupyter Notebook to display the plot in the notebook.Copy and paste one of the following examples to create your first hosted Plotly graph using the Plotly Python library:
+ +import chart_studio.plotly as py
+import plotly.graph_objects as go
+
+trace0 = go.Scatter(
+ x=[1, 2, 3, 4],
+ y=[10, 15, 13, 17]
+)
+trace1 = go.Scatter(
+ x=[1, 2, 3, 4],
+ y=[16, 5, 11, 9]
+)
+data = [trace0, trace1]
+
+py.plot(data, filename = 'basic-line', auto_open=True)
+
Checkout the docstrings for more information:
+ +import chart_studio.plotly as py
+help(py.plot)
+
import chart_studio.plotly as py
+import plotly.graph_objects as go
+
+trace0 = go.Scatter(
+ x=[1, 2, 3, 4],
+ y=[10, 15, 13, 17]
+)
+trace1 = go.Scatter(
+ x=[1, 2, 3, 4],
+ y=[16, 5, 11, 9]
+)
+data = [trace0, trace1]
+
+py.iplot(data, filename = 'basic-line')
+
See more examples in our IPython notebook documentation or check out the py.iplot()
docstring for more information.
import chart_studio.plotly as py
+help(py.iplot)
+
You can also create plotly graphs with matplotlib syntax. Learn more in our matplotlib documentation.
+ +Plotly allows you to create graphs offline and save them locally. There are also two methods for interactive plotting offline: plotly.io.write_html()
and plotly.io.show()
.
plotly.io.write_html()
to create and standalone HTML that is saved locally and opened inside your web browser.plotly.io.show()
when working offline in a Jupyter Notebook to display the plot in the notebook.For information on all of the ways that plotly figures can be displayed, see Displaying plotly figures with plotly for Python.
+ +Copy and paste one of the following examples to create your first offline Plotly graph using the Plotly Python library:
+ +import plotly.graph_objects as go
+import plotly.io as pio
+
+fig = go.Figure(go.Scatter(x=[1, 2, 3, 4], y=[4, 3, 2, 1]))
+fig.update_layout(title_text='hello world')
+pio.write_html(fig, file='hello_world.html', auto_open=True)
+
Learn more by calling help()
:
import plotly
+help(plotly.io.write_html)
+
import plotly.graph_objects as go
+import plotly.io as pio
+
+fig = go.Figure(go.Scatter(x=[1, 2, 3, 4], y=[4, 3, 2, 1]))
+fig.update_layout(title_text='hello world')
+pio.show(fig)
+
You can also call plotly.io.show directly from the go.Figure object.
+ +fig.show()
+
import plotly
+help(plotly.io.show)
+
For more examples on plotting offline with Plotly in python please visit our offline documentation.
+ +To use Plotly with Pandas first $ pip install pandas
and then import pandas in your code like in the example below.
import chart_studio.plotly as py
+import plotly.graph_objects as go
+import pandas as pd
+
+df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/gapminder2007.csv')
+
+fig = go.Figure(go.Scatter(x=df.gdpPercap, y=df.lifeExp, text=df.country, mode='markers', name='2007'))
+fig.update_xaxes(title_text='GDP per Capita', type='log')
+fig.update_yaxes(title_text='Life Expectancy')
+
+py.iplot(fig, filename='pandas-multiple-scatter')
+
Check out more examples and tutorials for using Plotly in python here!
+ +Jupyter has a beautiful notebook that lets you write and execute code, analyze data, embed content, and share reproducible work. Jupyter Notebook (previously referred to as IPython Notebook) allows you to easily share your code, data, plots, and explanation in a sinle notebook. Publishing is flexible: PDF, HTML, ipynb, dashboards, slides, and more. Code cells are based on an input and output format. For example:
+ +print("hello world")
+
There are a few ways to use a Jupyter Notebook:
+pip
. Open a terminal and type: $ pip install jupyter
.setuptools
.Once you've installed the Notebook, you start from your terminal by calling $ jupyter notebook
. This will open a browser on a localhost to the URL of your Notebooks, by default http://127.0.0.1:8888. Windows users need to open up their Command Prompt. You'll see a dashboard with all your Notebooks. You can launch your Notebooks from there. The Notebook has the advantage of looking the same when you're coding and publishing. You just have all the options to move code, run cells, change kernels, and use Markdown when you're running a NB.
- Tab Completion: Jupyter supports tab completion! You can type object_name.<TAB>
to view an object’s attributes. For tips on cell magics, running Notebooks, and exploring objects, check out the Jupyter docs.
+
- Help: provides an introduction and overview of features.
help
+
- Quick Reference: open quick reference by running:
+ +quickref
+
- Keyboard Shortcuts: Shift-Enter
will run a cell, Ctrl-Enter
will run a cell in-place, Alt-Enter
will run a cell and insert another below. See more shortcuts here.
The bulk of this tutorial discusses executing python code in Jupyter notebooks. You can also use Jupyter notebooks to execute R code. Skip down to the [R section] for more information on using IRkernel with Jupyter notebooks and graphing examples.
+When installing packages in Jupyter, you either need to install the package in your actual shell, or run the !
prefix, e.g.:
!pip install packagename
+
+
+You may want to reload submodules if you've edited the code in one. IPython comes with automatic reloading magic. You can reload all changed modules before executing a new line.
+ +%load_ext autoreload
+%autoreload 2
+
+
+
+Some useful packages that we'll use in this tutorial include:
+import pandas as pd
+import numpy as np
+import scipy as sp
+import chart_studio.plotly as py
+
You can use pandas read_csv()
function to import data. In the example below, we import a csv hosted on github and display it in a table using Plotly:
import chart_studio.plotly as py
+import plotly.figure_factory as ff
+import pandas as pd
+
+df = pd.read_csv("https://raw.githubusercontent.com/plotly/datasets/master/school_earnings.csv")
+
+table = ff.create_table(df)
+py.iplot(table, filename='jupyter-table1')
+
Use dataframe.column_title
to index the dataframe:
schools = df.School
+schools[0]
+
Most pandas functions also work on an entire dataframe. For example, calling std()
calculates the standard deviation for each column.
df.std()
+
You can use Plotly's python API to plot inside your Jupyter Notebook by calling plotly.plotly.iplot()
or plotly.offline.iplot()
if working offline. Plotting in the notebook gives you the advantage of keeping your data analysis and plots in one place. Now we can do a bit of interactive plotting. Head to the Plotly getting started page to learn how to set your credentials. Calling the plot with iplot
automaticallly generates an interactive version of the plot inside the Notebook in an iframe. See below:
import chart_studio.plotly as py
+import plotly.graph_objects as go
+
+data = [go.Bar(x=df.School,
+ y=df.Gap)]
+
+py.iplot(data, filename='jupyter-basic_bar')
+
Plotting multiple traces and styling the chart with custom colors and titles is simple with Plotly syntax. Additionally, you can control the privacy with sharing
set to public
, private
, or secret
.
import chart_studio.plotly as py
+import plotly.graph_objects as go
+
+trace_women = go.Bar(x=df.School,
+ y=df.Women,
+ name='Women',
+ marker=dict(color='#ffcdd2'))
+
+trace_men = go.Bar(x=df.School,
+ y=df.Men,
+ name='Men',
+ marker=dict(color='#A2D5F2'))
+
+trace_gap = go.Bar(x=df.School,
+ y=df.Gap,
+ name='Gap',
+ marker=dict(color='#59606D'))
+
+data = [trace_women, trace_men, trace_gap]
+
+layout = go.Layout(title="Average Earnings for Graduates",
+ xaxis=dict(title='School'),
+ yaxis=dict(title='Salary (in thousands)'))
+
+fig = go.Figure(data=data, layout=layout)
+
+py.iplot(fig, sharing='private', filename='jupyter-styled_bar')
+
Now we have interactive charts displayed in our notebook. Hover on the chart to see the values for each bar, click and drag to zoom into a specific section or click on the legend to hide/show a trace.
+ +Plotly is now integrated with Mapbox. In this example we'll plot lattitude and longitude data of nuclear waste sites. To plot on Mapbox maps with Plotly you'll need a Mapbox account and a Mapbox Access Token which you can add to your Plotly settings.
+ +import chart_studio.plotly as py
+import plotly.graph_objects as go
+
+import pandas as pd
+
+# mapbox_access_token = 'ADD YOUR TOKEN HERE'
+
+df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/Nuclear%20Waste%20Sites%20on%20American%20Campuses.csv')
+site_lat = df.lat
+site_lon = df.lon
+locations_name = df.text
+
+data = [
+ go.Scattermapbox(
+ lat=site_lat,
+ lon=site_lon,
+ mode='markers',
+ marker=dict(
+ size=17,
+ color='rgb(255, 0, 0)',
+ opacity=0.7
+ ),
+ text=locations_name,
+ hoverinfo='text'
+ ),
+ go.Scattermapbox(
+ lat=site_lat,
+ lon=site_lon,
+ mode='markers',
+ marker=dict(
+ size=8,
+ color='rgb(242, 177, 172)',
+ opacity=0.7
+ ),
+ hoverinfo='none'
+ )]
+
+
+layout = go.Layout(
+ title='Nuclear Waste Sites on Campus',
+ autosize=True,
+ hovermode='closest',
+ showlegend=False,
+ mapbox=dict(
+ accesstoken=mapbox_access_token,
+ bearing=0,
+ center=dict(
+ lat=38,
+ lon=-94
+ ),
+ pitch=0,
+ zoom=3,
+ style='light'
+ ),
+)
+
+fig = dict(data=data, layout=layout)
+
+py.iplot(fig, filename='jupyter-Nuclear Waste Sites on American Campuses')
+
import chart_studio.plotly as py
+import plotly.graph_objects as go
+
+import numpy as np
+
+s = np.linspace(0, 2 * np.pi, 240)
+t = np.linspace(0, np.pi, 240)
+tGrid, sGrid = np.meshgrid(s, t)
+
+r = 2 + np.sin(7 * sGrid + 5 * tGrid) # r = 2 + sin(7s+5t)
+x = r * np.cos(sGrid) * np.sin(tGrid) # x = r*cos(s)*sin(t)
+y = r * np.sin(sGrid) * np.sin(tGrid) # y = r*sin(s)*sin(t)
+z = r * np.cos(tGrid) # z = r*cos(t)
+
+surface = go.Surface(x=x, y=y, z=z)
+data = [surface]
+
+layout = go.Layout(
+ title='Parametric Plot',
+ scene=dict(
+ xaxis=dict(
+ gridcolor='rgb(255, 255, 255)',
+ zerolinecolor='rgb(255, 255, 255)',
+ showbackground=True,
+ backgroundcolor='rgb(230, 230,230)'
+ ),
+ yaxis=dict(
+ gridcolor='rgb(255, 255, 255)',
+ zerolinecolor='rgb(255, 255, 255)',
+ showbackground=True,
+ backgroundcolor='rgb(230, 230,230)'
+ ),
+ zaxis=dict(
+ gridcolor='rgb(255, 255, 255)',
+ zerolinecolor='rgb(255, 255, 255)',
+ showbackground=True,
+ backgroundcolor='rgb(230, 230,230)'
+ )
+ )
+)
+
+fig = go.Figure(data=data, layout=layout)
+py.iplot(fig, filename='jupyter-parametric_plot')
+
Checkout Plotly's animation documentation to see how to create animated plots inline in Jupyter notebooks like the Gapminder plot displayed below:
+
Add sliders, buttons, and dropdowns to your inline chart:
+ +import chart_studio.plotly as py
+import numpy as np
+
+data = [dict(
+ visible = False,
+ line=dict(color='#00CED1', width=6),
+ name = '𝜈 = '+str(step),
+ x = np.arange(0,10,0.01),
+ y = np.sin(step*np.arange(0,10,0.01))) for step in np.arange(0,5,0.1)]
+data[10]['visible'] = True
+
+steps = []
+for i in range(len(data)):
+ step = dict(
+ method = 'restyle',
+ args = ['visible', [False] * len(data)],
+ )
+ step['args'][1][i] = True # Toggle i'th trace to "visible"
+ steps.append(step)
+
+sliders = [dict(
+ active = 10,
+ currentvalue = {"prefix": "Frequency: "},
+ pad = {"t": 50},
+ steps = steps
+)]
+
+layout = dict(sliders=sliders)
+fig = dict(data=data, layout=layout)
+
+py.iplot(fig, filename='Sine Wave Slider')
+
Additionally, IPython widgets allow you to add sliders, widgets, search boxes, and more to your Notebook. See the widget docs for more information. For others to be able to access your work, they'll need IPython. Or, you can use a cloud-based NB option so others can run your work.
+
+
IRkernel, an R kernel for Jupyter, allows you to write and execute R code in a Jupyter notebook. Checkout the IRkernel documentation for some simple installation instructions. Once IRkernel is installed, open a Jupyter Notebook by calling $ jupyter notebook
and use the New dropdown to select an R notebook.
See a full R example Jupyter Notebook here: https://plot.ly/~chelsea_lyn/14069
+ +We've seen how to embed Plotly tables and charts as iframes in the notebook, with IPython.display
we can embed additional features, such a videos. For example, from YouTube:
from IPython.display import YouTubeVideo
+YouTubeVideo("wupToqz1e2g")
+
We can embed LaTeX inside a Notebook by putting a $$
around our math, then run the cell as a Markdown cell. For example, the cell below is $$c = \sqrt{a^2 + b^2}$$
, but the Notebook renders the expression.
$$c = \sqrt{a^2 + b^2}$$
+ +Or, you can display output from Python, as seen here.
+ +from IPython.display import display, Math, Latex
+
+display(Math(r'F(k) = \int_{-\infty}^{\infty} f(x) e^{2\pi i k} dx'))
+
We can export the Notebook as an HTML, PDF, .py, .ipynb, Markdown, and reST file. You can also turn your NB into a slideshow. You can publish Jupyter Notebooks on Plotly. Simply visit plot.ly and select the + Create
button in the upper right hand corner. Select Notebook and upload your Jupyter notebook (.ipynb) file!
+The notebooks that you upload will be stored in your Plotly organize folder and hosted at a unique link to make sharing quick and easy.
+See some example notebooks:
Users publishing interactive graphs can also use Plotly's dashboarding tool to arrange plots with a drag and drop interface. These dashboards can be published, embedded, and shared.
For more Jupyter tutorials, checkout Plotly's python documentation: all documentation is written in jupyter notebooks that you can download and run yourself or checkout these user submitted examples!
+ + +To use Plotly's Presentations API you will write your presentation code in a string of markdown and then pass that through the Presentations API function pres.Presentation()
. This creates a JSON version of your presentation. To upload the presentation online pass it through py.presentation_ops.upload()
.
In your string, use ---
on a single line to seperate two slides. To put a title in your slide, put a line that starts with any number of #
s. Only your first title will be appear in your slide. A title looks like:
# slide title
Anything that comes after the title will be put as text in your slide. Check out the example below to see this in action.
+ +The function below generates HTML code to display the presentation in an iframe directly in Jupyter.
+ +def url_to_iframe(url, text=True):
+ html = ''
+ # style
+ html += '''<head>
+ <style>
+ div.textbox {
+ margin: 30px;
+ font-weight: bold;
+ }
+ </style>
+ </head>'
+ '''
+ # iframe
+ html += '<iframe src=' + url + '.embed#{} width=750 height=400 frameBorder="0"></iframe>'
+ if text:
+ html += '''<body>
+ <div class="textbox">
+ <p>Click on the presentation above and use left/right arrow keys to flip through the slides.</p>
+ </div>
+ </body>
+ '''
+ return html
+
import chart_studio.plotly as py
+import chart_studio.presentation_objs as pres
+
+filename = 'simple-pres'
+markdown_string = """
+# slide 1
+There is only one slide.
+
+---
+# slide 2
+Again, another slide on this page.
+
+"""
+
+my_pres = pres.Presentation(markdown_string)
+pres_url_0 = py.presentation_ops.upload(my_pres, filename)
+
import IPython
+
+iframe_0 = url_to_iframe(pres_url_0, True)
+IPython.display.HTML(iframe_0)
+
If you want to insert a Plotly chart into your presentation, all you need to do is write a line in your presentation that takes the form:
+Plotly(url)
where url is a Plotly url. For example:
+Plotly(https://plot.ly/~AdamKulidjian/3564)
The Plotly url lines should be written on a separate line after your title line. You can put as many images in your slide as you want, as the API will arrange them on the slide automatically, but it is highly encouraged that you use 4 OR FEWER IMAGES PER SLIDE
. This will produce the cleanest look.
Useful Tip
:
+For Plotly charts it is HIGHLY ADVISED that you use a chart that has layout['autosize']
set to True
. If it is False
the image may be cropped or only partially visible when it appears in the presentation slide.
import chart_studio.plotly as py
+import chart_studio.presentation_objs as pres
+
+filename = 'pres-with-plotly-chart'
+markdown_string = """
+# 3D scatterplots
+3D Scatterplot are just a collection of balls in a 3D cartesian space each of which have assigned properties like color, size, and more.
+
+---
+# simple 3d scatterplot
+
+Plotly(https://plot.ly/~AdamKulidjian/3698)
+---
+# different colorscales
+
+There are various colorscales and colorschemes to try in Plotly. Check out plotly.colors to find a list of valid and available colorscales.
+
+Plotly(https://plot.ly/~AdamKulidjian/3582)
+Plotly(https://plot.ly/~AdamKulidjian/3698)
+"""
+
+my_pres = pres.Presentation(markdown_string)
+pres_url_1 = py.presentation_ops.upload(my_pres, filename)
+
import IPython
+
+iframe_1 = url_to_iframe(pres_url_1, True)
+IPython.display.HTML(iframe_1)
+
To insert an image from the web, insert the a Image(url)
where url is the image url.
import chart_studio.plotly as py
+import chart_studio.presentation_objs as pres
+
+filename = 'pres-with-images'
+markdown_string = """
+# Animals of the Wild
+---
+# The Lion
+
+Panthera leo is one of the big cats in the Felidae family and a member of genus Panthera. It has been listed as Vulnerable on the IUCN Red List since 1996, as populations in African range countries declined by about 43% since the early 1990s. Lion populations are untenable outside designated protected areas. Although the cause of the decline is not fully understood, habitat loss and conflicts with humans are the greatest causes of concern. The West African lion population is listed as Critically Endangered since 2016. The only lion population in Asia survives in and around India's Gir Forest National Park and is listed as Endangered since 1986.
+
+Image(https://i.pinimg.com/736x/da/af/73/daaf73960eb5a21d6bca748195f12052--lion-photography-lion-kings.jpg)
+---
+# The Giraffe
+
+The giraffe is a genus of African even-toed ungulate mammals, the tallest living terrestrial animals and the largest ruminants. The genus currently consists of one species, Giraffa camelopardalis, the type species. Seven other species are extinct, prehistoric species known from fossils. Taxonomic classifications of one to eight extant giraffe species have been described, based upon research into the mitochondrial and nuclear DNA, as well as morphological measurements of Giraffa, but the IUCN currently recognizes only one species with nine subspecies.
+
+Image(https://img.purch.com/w/192/aHR0cDovL3d3dy5saXZlc2NpZW5jZS5jb20vaW1hZ2VzL2kvMDAwLzA2OC8wOTQvaTMwMC9naXJhZmZlLmpwZz8xNDA1MDA4NDQy)
+Image(https://upload.wikimedia.org/wikipedia/commons/9/9f/Giraffe_standing.jpg)
+
+"""
+
+my_pres = pres.Presentation(markdown_string)
+pres_url_2 = py.presentation_ops.upload(my_pres, filename)
+
import IPython
+
+iframe_2 = url_to_iframe(pres_url_2, True)
+IPython.display.HTML(iframe_2)
+
If you want to ensure that your image maintains its original width:height ratio, include the parameter imgStretch=False
in your pres.Presentation()
function call.
import chart_studio.plotly as py
+import chart_studio.presentation_objs as pres
+
+filename = 'pres-with-no-imgstretch'
+markdown_string = """
+# images in native aspect ratio
+
+Image(https://raw.githubusercontent.com/jackparmer/gradient-backgrounds/master/moods1.png)
+Image(https://raw.githubusercontent.com/jackparmer/gradient-backgrounds/master/moods1.png)
+Image(https://raw.githubusercontent.com/jackparmer/gradient-backgrounds/master/moods1.png)
+Image(https://raw.githubusercontent.com/jackparmer/gradient-backgrounds/master/moods1.png)
+Image(https://raw.githubusercontent.com/jackparmer/gradient-backgrounds/master/moods1.png)
+"""
+
+my_pres = pres.Presentation(markdown_string, imgStretch=False)
+pres_url_3 = py.presentation_ops.upload(my_pres, filename)
+
import IPython
+
+iframe_3 = url_to_iframe(pres_url_3, False)
+IPython.display.HTML(iframe_3)
+
You can specify how your want your slides to transition to one another. Just like in the Plotly Presentation Application, there are 4 types of transitions: slide
, zoom
, fade
and spin
.
To apply any combination of these transition to a slide, just insert transitions at the top of the slide as follows:
+transition: slide, zoom
Make sure that this line comes before any heading that you define in the slide, i.e. like this:
+ +transition: slide, zoom
+# slide title
+
+import chart_studio.plotly as py
+import chart_studio.presentation_objs as pres
+
+filename = 'pres-with-transitions'
+markdown_string = """
+transition: slide
+# slide
+---
+transition: zoom
+# zoom
+---
+transition: fade
+# fade
+---
+transition: spin
+# spin
+---
+transition: spin and slide
+# spin, slide
+---
+transition: fade zoom
+# fade, zoom
+---
+transition: slide, zoom, fade, spin, spin, spin, zoom, fade
+# slide, zoom, fade, spin
+
+"""
+
+my_pres = pres.Presentation(markdown_string, style='moods')
+pres_url_6 = py.presentation_ops.upload(my_pres, filename)
+
import IPython
+
+iframe_6 = url_to_iframe(pres_url_6, True)
+IPython.display.HTML(iframe_6)
+
help(py.presentation_ops)
+
By default, plotly.iplot()
and plotly.plot()
create public graphs (which are free to create). With a plotly subscription you can easily make charts private or secret via the sharing argument.
import chart_studio.plotly as py
+import plotly.graph_objects as go
+
+data = [
+ go.Scatter(
+ x=[1, 2, 3],
+ y=[1, 3, 1]
+ )
+]
+
+py.iplot(data, filename='privacy-public', sharing='public')
+
Below is the URL of this public plot. Anyone can view public plots even if they are not logged into Plotly. Go ahead and try it out:
+ +py.plot(data, filename='privacy-public', sharing='public')
+
py.iplot(data, filename='privacy-private', sharing='private')
+
Below is the URL of the private plot above. Only the owner can view the private plot. You won't be able to view this plot, try it out:
+ +py.plot(data, filename='privacy-private', sharing='private')
+
py.iplot(data, filename='privacy-secret', sharing='secret')
+
Below is the URL of this secret plot. Anyone with the secret link can view this chart. However, it will not appear in the Plotly feed, your profile, or search engines. Go ahead and try it out:
+ +py.plot(data, filename='privacy-secret', sharing='secret')
+
To make all future plots private, you can update your configuration file to create private plots by default:
+ +import chart_studio
+chart_studio.tools.set_config_file(world_readable=False, sharing='private')
+
This example uses Plotly's REST API
+ +import json
+import requests
+from requests.auth import HTTPBasicAuth
+
Define variables, including YOUR USERNAME and API KEY
+ +username = 'private_plotly' # Replace with YOUR USERNAME
+api_key = 'k0yy0ztssk' # Replace with YOUR API KEY
+
+auth = HTTPBasicAuth(username, api_key)
+headers = {'Plotly-Client-Platform': 'python'}
+
+page_size = 500
+
Collect filenames of ALL of your plots and
update world_readable
of each plot with a PATCH request
def get_pages(username, page_size):
+ url = 'https://api.plot.ly/v2/folders/all?user='+username+'&filetype=plot&page_size='+str(page_size)
+ response = requests.get(url, auth=auth, headers=headers)
+ if response.status_code != 200:
+ return
+ page = json.loads(response.content.decode('utf-8'))
+ yield page
+ while True:
+ resource = page['children']['next']
+ if not resource:
+ break
+ response = requests.get(resource, auth=auth, headers=headers)
+ if response.status_code != 200:
+ break
+ page = json.loads(response.content.decode('utf-8'))
+ yield page
+
+def make_all_plots_private(username, page_size=500):
+ for page in get_pages(username, page_size):
+ for x in range(0, len(page['children']['results'])):
+ fid = page['children']['results'][x]['fid']
+ requests.patch('https://api.plot.ly/v2/files/'+fid, {"world_readable": False}, auth=auth, headers=headers)
+ print('ALL of your plots are now private - visit: https://plot.ly/organize/home to view your private plots!')
+
+make_all_plots_private(username)
+
help(py.plot)
+
If you are behind a corporate firewall, you may see the error message:
+ +requests.exceptions.ConnectionError: ('Connection aborted.', TimeoutError(10060, ...)
+Plotly uses the requests module to communicate with the Plotly server. You can configure proxies by setting the environment variables HTTP_PROXY and HTTPS_PROXY.
+ +$ export HTTP_PROXY="http://10.10.1.10:3128"
+$ export HTTPS_PROXY="http://10.10.1.10:1080"
+To use HTTP Basic Auth with your proxy, use the http://user:password@host/ syntax:
+ +$ export HTTP_PROXY="http://user:pass@10.10.1.10:3128/"
+Note that proxy URLs must include the scheme.
+You may also see this error if your proxy variable is set but you are no longer behind the corporate proxy. Check if a proxy variable is set with:
+ +$ echo $HTTP_PROXY
+$ echo $HTTPS_PROXY
+Still not working?
+ +Contact support@plot.ly
+Get in touch with your IT department, and ask them about corporate proxies.
+Requests documentation on configuring proxies the requests documentation.
+Plotly for IPython Notebooks is also available for offline use.
+Chart Studio Enterprise is available for behind-the-firewall corporate installations.
+ +