From c4c49e73f74c74d20244cda7a1627e25498428cb Mon Sep 17 00:00:00 2001 From: michaelbabyn Date: Mon, 8 Jul 2019 12:55:44 -0400 Subject: [PATCH] update ipynb files to use front matter from python reorg and re-generate new html files --- .../chart-studio/2019-07-03-data-api.html | 701 +++++++++++ .../chart-studio/2019-07-03-delete-plots.html | 419 +++++++ .../2019-07-03-embedding-charts.html | 67 ++ .../chart-studio/2019-07-03-get-requests.html | 166 +++ ...-03-getting-started-with-chart-studio.html | 1032 +++++++++++++++++ .../2019-07-03-ipython-notebook-tutorial.html | 960 +++++++++++++++ .../2019-07-03-presentations-tool.html | 657 +++++++++++ .../chart-studio/2019-07-03-privacy.html | 500 ++++++++ .../2019-07-03-proxy-configuration.html | 51 + .../python-next/chart-studio/data-api.ipynb | 22 +- _posts/python-next/chart-studio/data-api.md | 14 +- .../chart-studio/delete-plots.ipynb | 22 +- .../python-next/chart-studio/delete-plots.md | 18 +- .../chart-studio/embedding-charts.md | 20 +- .../chart-studio/get-requests.ipynb | 4 +- .../getting-started-with-chart-studio.ipynb | 20 +- .../ipython-notebook-tutorial.ipynb | 50 +- .../chart-studio/presentations-tool.ipynb | 36 +- _posts/python-next/chart-studio/privacy.ipynb | 24 +- _posts/python-next/chart-studio/privacy.md | 17 +- 20 files changed, 4672 insertions(+), 128 deletions(-) create mode 100644 _posts/python-next/chart-studio/2019-07-03-data-api.html create mode 100644 _posts/python-next/chart-studio/2019-07-03-delete-plots.html create mode 100644 _posts/python-next/chart-studio/2019-07-03-embedding-charts.html create mode 100644 _posts/python-next/chart-studio/2019-07-03-get-requests.html create mode 100644 _posts/python-next/chart-studio/2019-07-03-getting-started-with-chart-studio.html create mode 100644 _posts/python-next/chart-studio/2019-07-03-ipython-notebook-tutorial.html create mode 100644 _posts/python-next/chart-studio/2019-07-03-presentations-tool.html create mode 100644 _posts/python-next/chart-studio/2019-07-03-privacy.html create mode 100644 _posts/python-next/chart-studio/2019-07-03-proxy-configuration.html 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 %} + +
+
+
+
+

Creating a Plotly Grid

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.

+ +
+
+
+
+
+
In [1]:
+
+
+
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)
+
+ +
+
+
+ +
+
+ + +
+ +
+ + +
+
https://plot.ly/~PythonPlotBot/3534/
+
+
+
+ +
+
+ +
+
+
+
+
+

View and Share your Grid

You can view your newly created grid at the url:

+ +
+
+
+
+
+
In [2]:
+
+
+
IFrame(src= url.rstrip('/') + ".embed", width="100%",height="200px", frameBorder="0")
+
+ +
+
+
+ +
+
+ + +
+ +
Out[2]:
+ + + +
+ + + +
+ +
+ +
+
+ +
+
+
+
+
+

You are also able to view the grid in your list of files inside your organize folder.

+ +
+
+
+
+
+
+
+

Upload Dataframes to Plotly

Along with uploading a grid, you can upload a Dataframe as well as convert it to raw data as a grid:

+ +
+
+
+
+
+
In [3]:
+
+
+
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')
+
+ +
+
+
+ +
+
+ + +
+ +
Out[3]:
+ + + +
+ + + +
+ +
+ +
+
+ +
+
+
+
+
+

Making Graphs from Grids

Plotly graphs are usually described with data embedded in them. For example, here we place x and y data directly into our Histogram2dContour object:

+ +
+
+
+
+
+
In [4]:
+
+
+
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')
+
+ +
+
+
+ +
+
+ + +
+ +
Out[4]:
+ + + +
+ + + +
+ +
+ +
+
+ +
+
+
+
+
+

We can also create graphs based off of references to columns of grids. Here, we'll upload several columns to our Plotly account:

+ +
+
+
+
+
+
In [5]:
+
+
+
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)
+
+ +
+
+
+ +
+
+ + +
+ +
+ + +
+
https://plot.ly/~PythonPlotBot/3537/
+
+
+
+ +
+
+ +
+
+
+
In [6]:
+
+
+
IFrame(src= url.rstrip('/') + ".embed", width="100%",height="200px", frameBorder="0")
+
+ +
+
+
+ +
+
+ + +
+ +
Out[6]:
+ + + +
+ + + +
+ +
+ +
+
+ +
+
+
+
+
+

Make Graph from Raw Data

Instead of placing data into x and y, we'll place our Grid columns into xsrc and ysrc:

+ +
+
+
+
+
+
In [7]:
+
+
+
data = [
+    go.Histogram2dContour(
+        xsrc=grid[0],
+        ysrc=grid[1]
+    )
+]
+
+py.iplot(data, filename='2D Contour from Grid Data')
+
+ +
+
+
+ +
+
+ + +
+ +
Out[7]:
+ + + +
+ + + +
+ +
+ +
+
+ +
+
+
+
+
+

So, when you view the data, you'll see your original grid, not just the columns that compose this graph:

+ +
+
+
+
+
+
+
+

Attaching Meta Data to Grids

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.

+ +
+
+
+
+
+
In [8]:
+
+
+
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)
+
+ +
+
+
+ +
+
+ + +
+ +
+ + +
+
https://plot.ly/~PythonPlotBot/3537/
+
+
+
+ +
+
+ +
+
+
+
+
+

Reference

+
+
+
+
+
+
In [9]:
+
+
+
help(py.grid_ops)
+
+ +
+
+
+ +
+
+ + +
+ +
+ + +
+
Help on class grid_ops in module chart_studio.plotly.plotly:
+
+class grid_ops(builtins.object)
+ |  Interface to Plotly's Grid API.
+ |  Plotly Grids are Plotly's tabular data object, rendered
+ |  in an online spreadsheet. Plotly graphs can be made from
+ |  references of columns of Plotly grid objects. Free-form
+ |  JSON Metadata can be saved with Plotly grids.
+ |  
+ |  To create a Plotly grid in your Plotly account from Python,
+ |  see `grid_ops.upload`.
+ |  
+ |  To add rows or columns to an existing Plotly grid, see
+ |  `grid_ops.append_rows` and `grid_ops.append_columns`
+ |  respectively.
+ |  
+ |  To delete one of your grid objects, see `grid_ops.delete`.
+ |  
+ |  Class methods defined here:
+ |  
+ |  append_columns(columns, grid=None, grid_url=None) from builtins.type
+ |      Append columns to a Plotly grid.
+ |      
+ |      `columns` is an iterable of plotly.grid_objs.Column objects
+ |      and only one of `grid` and `grid_url` needs to specified.
+ |      
+ |      `grid` is a ploty.grid_objs.Grid object that has already been
+ |      uploaded to plotly with the grid_ops.upload method.
+ |      
+ |      `grid_url` is a unique URL of a `grid` in your plotly account.
+ |      
+ |      Usage example 1: Upload a grid to Plotly, and then append a column
+ |      ```
+ |      from plotly.grid_objs import Grid, Column
+ |      import plotly.plotly as py
+ |      column_1 = Column([1, 2, 3], 'time')
+ |      grid = Grid([column_1])
+ |      py.grid_ops.upload(grid, 'time vs voltage')
+ |      
+ |      # append a column to the grid
+ |      column_2 = Column([4, 2, 5], 'voltage')
+ |      py.grid_ops.append_columns([column_2], grid=grid)
+ |      ```
+ |      
+ |      Usage example 2: Append a column to a grid that already exists on
+ |                       Plotly
+ |      ```
+ |      from plotly.grid_objs import Grid, Column
+ |      import plotly.plotly as py
+ |      
+ |      grid_url = 'https://plot.ly/~chris/3143'
+ |      column_1 = Column([1, 2, 3], 'time')
+ |      py.grid_ops.append_columns([column_1], grid_url=grid_url)
+ |      ```
+ |  
+ |  append_rows(rows, grid=None, grid_url=None) from builtins.type
+ |      Append rows to a Plotly grid.
+ |      
+ |      `rows` is an iterable of rows, where each row is a
+ |      list of numbers, strings, or dates. The number of items
+ |      in each row must be equal to the number of columns
+ |      in the grid. If appending rows to a grid with columns of
+ |      unequal length, Plotly will fill the columns with shorter
+ |      length with empty strings.
+ |      
+ |      Only one of `grid` and `grid_url` needs to specified.
+ |      
+ |      `grid` is a ploty.grid_objs.Grid object that has already been
+ |      uploaded to plotly with the grid_ops.upload method.
+ |      
+ |      `grid_url` is a unique URL of a `grid` in your plotly account.
+ |      
+ |      Usage example 1: Upload a grid to Plotly, and then append rows
+ |      ```
+ |      from plotly.grid_objs import Grid, Column
+ |      import plotly.plotly as py
+ |      column_1 = Column([1, 2, 3], 'time')
+ |      column_2 = Column([5, 2, 7], 'voltage')
+ |      grid = Grid([column_1, column_2])
+ |      py.grid_ops.upload(grid, 'time vs voltage')
+ |      
+ |      # append a row to the grid
+ |      row = [1, 5]
+ |      py.grid_ops.append_rows([row], grid=grid)
+ |      ```
+ |      
+ |      Usage example 2: Append a row to a grid that already exists on Plotly
+ |      ```
+ |      from plotly.grid_objs import Grid
+ |      import plotly.plotly as py
+ |      
+ |      grid_url = 'https://plot.ly/~chris/3143'
+ |      
+ |      row = [1, 5]
+ |      py.grid_ops.append_rows([row], grid=grid_url)
+ |      ```
+ |  
+ |  delete(grid=None, grid_url=None) from builtins.type
+ |      Delete a grid from your Plotly account.
+ |      
+ |      Only one of `grid` or `grid_url` needs to be specified.
+ |      
+ |      `grid` is a plotly.grid_objs.Grid object that has already
+ |             been uploaded to Plotly.
+ |      
+ |      `grid_url` is the URL of the Plotly grid to delete
+ |      
+ |      Usage example 1: Upload a grid to plotly, then delete it
+ |      ```
+ |      from plotly.grid_objs import Grid, Column
+ |      import plotly.plotly as py
+ |      column_1 = Column([1, 2, 3], 'time')
+ |      column_2 = Column([4, 2, 5], 'voltage')
+ |      grid = Grid([column_1, column_2])
+ |      py.grid_ops.upload(grid, 'time vs voltage')
+ |      
+ |      # now delete it, and free up that filename
+ |      py.grid_ops.delete(grid)
+ |      ```
+ |      
+ |      Usage example 2: Delete a plotly grid by url
+ |      ```
+ |      import plotly.plotly as py
+ |      
+ |      grid_url = 'https://plot.ly/~chris/3'
+ |      py.grid_ops.delete(grid_url=grid_url)
+ |      ```
+ |  
+ |  upload(grid, filename=None, world_readable=True, auto_open=True, meta=None) from builtins.type
+ |      Upload a grid to your Plotly account with the specified filename.
+ |      
+ |      Positional arguments:
+ |          - grid: A plotly.grid_objs.Grid object,
+ |                  call `help(plotly.grid_ops.Grid)` for more info.
+ |          - filename: Name of the grid to be saved in your Plotly account.
+ |                      To save a grid in a folder in your Plotly account,
+ |                      separate specify a filename with folders and filename
+ |                      separated by backslashes (`/`).
+ |                      If a grid, plot, or folder already exists with the same
+ |                      filename, a `plotly.exceptions.RequestError` will be
+ |                      thrown with status_code 409.  If filename is None,
+ |                      and randomly generated filename will be used.
+ |      
+ |      Optional keyword arguments:
+ |          - world_readable (default=True): make this grid publically (True)
+ |                                           or privately (False) viewable.
+ |          - auto_open (default=True): Automatically open this grid in
+ |                                      the browser (True)
+ |          - meta (default=None): Optional Metadata to associate with
+ |                                 this grid.
+ |                                 Metadata is any arbitrary
+ |                                 JSON-encodable object, for example:
+ |                                 `{"experiment name": "GaAs"}`
+ |      
+ |      Filenames must be unique. To overwrite a grid with the same filename,
+ |      you'll first have to delete the grid with the blocking name. See
+ |      `plotly.plotly.grid_ops.delete`.
+ |      
+ |      Usage example 1: Upload a plotly grid
+ |      ```
+ |      from plotly.grid_objs import Grid, Column
+ |      import plotly.plotly as py
+ |      column_1 = Column([1, 2, 3], 'time')
+ |      column_2 = Column([4, 2, 5], 'voltage')
+ |      grid = Grid([column_1, column_2])
+ |      py.grid_ops.upload(grid, 'time vs voltage')
+ |      ```
+ |      
+ |      Usage example 2: Make a graph based with data that is sourced
+ |                       from a newly uploaded Plotly grid
+ |      ```
+ |      import plotly.plotly as py
+ |      from plotly.grid_objs import Grid, Column
+ |      from plotly.graph_objs import Scatter
+ |      # Upload a grid
+ |      column_1 = Column([1, 2, 3], 'time')
+ |      column_2 = Column([4, 2, 5], 'voltage')
+ |      grid = Grid([column_1, column_2])
+ |      py.grid_ops.upload(grid, 'time vs voltage')
+ |      
+ |      # Build a Plotly graph object sourced from the
+ |      # grid's columns
+ |      trace = Scatter(xsrc=grid[0], ysrc=grid[1])
+ |      py.plot([trace], filename='graph from grid')
+ |      ```
+ |  
+ |  ----------------------------------------------------------------------
+ |  Static methods defined here:
+ |  
+ |  ensure_uploaded(fid)
+ |  
+ |  ----------------------------------------------------------------------
+ |  Data descriptors defined here:
+ |  
+ |  __dict__
+ |      dictionary for instance variables (if defined)
+ |  
+ |  __weakref__
+ |      list of weak references to the object (if defined)
+
+
+
+
+ +
+
+ +
+ + + + +{% endraw %} \ No newline at end of file diff --git a/_posts/python-next/chart-studio/2019-07-03-delete-plots.html b/_posts/python-next/chart-studio/2019-07-03-delete-plots.html new file mode 100644 index 000000000000..ebe97e7be0b7 --- /dev/null +++ b/_posts/python-next/chart-studio/2019-07-03-delete-plots.html @@ -0,0 +1,419 @@ +--- +description: How to delete plotly graphs in python. +display_as: chart_studio +has_thumbnail: True +ipynb: ~notebook_demo/98 +language: python/next +layout: user-guide +name: Deleting Plots +order: 9 +page_type: u-guide +permalink: python/next/delete-plots/ +thumbnail: thumbnail/delete.jpg +v4upgrade: True +--- + +{% raw %} + +
+
+
+
+

Imports and Credentials

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

+ +
+
+
+
+
+
In [1]:
+
+
+
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)
+
+ +
+
+
+ +
+
+
+
+
+

Trash and Restore

Create a plot and return the url to see the file id which will be used to delete the plot.

+ +
+
+
+
+
+
In [2]:
+
+
+
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
+
+ +
+
+
+ +
+
+ + +
+ +
Out[2]:
+ + + + +
+
'https://plot.ly/~private_plotly/658/'
+
+ +
+ +
+
+ +
+
+
+
+
+

Include the file id in your request.
The file id is your username:plot_id#

+ +
+
+
+
+
+
In [3]:
+
+
+
fid = username+':658'
+fid
+
+ +
+
+
+ +
+
+ + +
+ +
Out[3]:
+ + + + +
+
'private_plotly:658'
+
+ +
+ +
+
+ +
+
+
+
+
+

The following request moves the plot from the organize folder into the trash.
Note: a successful trash request will return a Response [200].

+ +
+
+
+
+
+
In [4]:
+
+
+
requests.post('https://api.plot.ly/v2/files/'+fid+'/trash', auth=auth, headers=headers)
+
+ +
+
+
+ +
+
+ + +
+ +
Out[4]:
+ + + + +
+
<Response [200]>
+
+ +
+ +
+
+ +
+
+
+
+
+

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:

+ +
+
+
+
+
+
+
+

PERMANENT Delete

This request CANNOT!!!!!!! be restored. +Only use permanent_delete when absolutely sure the plot is no longer needed.

+ +
+
+
+
+
+
In [5]:
+
+
+
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
+
+ +
+
+
+ +
+
+ + +
+ +
Out[5]:
+ + + + +
+
'https://plot.ly/~private_plotly/661/'
+
+ +
+ +
+
+ +
+
+
+
In [6]:
+
+
+
fid_permanent_delete = username+':661'
+fid_permanent_delete
+
+ +
+
+
+ +
+
+ + +
+ +
Out[6]:
+ + + + +
+
'private_plotly:661'
+
+ +
+ +
+
+ +
+
+
+
+
+

To PERMANENTLY delete a plot, first move the plot to the trash (as seen above):

+ +
+
+
+
+
+
In [7]:
+
+
+
requests.post('https://api.plot.ly/v2/files/'+fid_permanent_delete+'/trash', auth=auth, headers=headers)
+
+ +
+
+
+ +
+
+ + +
+ +
Out[7]:
+ + + + +
+
<Response [200]>
+
+ +
+ +
+
+ +
+
+
+
+
+

Then permanent delete.
+Note: a successful permanent delete request will return a Response [204] (No Content).

+ +
+
+
+
+
+
In [8]:
+
+
+
requests.delete('https://api.plot.ly/v2/files/'+fid_permanent_delete+'/permanent_delete', auth=auth, headers=headers)
+
+ +
+
+
+ +
+
+ + +
+ +
Out[8]:
+ + + + +
+
<Response [204]>
+
+ +
+ +
+
+ +
+
+
+
+
+

Delete All Plots and Grids PERMANENTLY!

In order to delete all plots and grids permanently, you need to delete all of your plots first, then delete all the associated grids.

+ +
+
+
+
+
+
In [ ]:
+
+
+
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')
+
+ +
+
+
+ +
+ + + + +{% endraw %} \ No newline at end of file diff --git a/_posts/python-next/chart-studio/2019-07-03-embedding-charts.html b/_posts/python-next/chart-studio/2019-07-03-embedding-charts.html new file mode 100644 index 000000000000..544602ecb4c5 --- /dev/null +++ b/_posts/python-next/chart-studio/2019-07-03-embedding-charts.html @@ -0,0 +1,67 @@ +--- +description: How to embed plotly graphs with an iframe in HTML. +display_as: chart_studio +has_thumbnail: True +language: python/next +layout: user-guide +name: Embedding Graphs in HTML +order: 6 +permalink: python/next/embedding-plotly-graphs-in-HTML/ +thumbnail: thumbnail/embed.jpg +title: Python Embedding Graphs in HTML | Examples | Plotly +v4upgrade: True +--- + +{% raw %} + +
+
+
+
+

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.

+ +
+
+
+
+
+
In [1]:
+
+
+
import chart_studio.tools as tls
+
+tls.get_embed('https://plot.ly/~chris/1638')
+
+ +
+
+
+ +
+
+ + +
+ +
Out[1]:
+ + + + +
+
'<iframe id="igraph" scrolling="no" style="border:none;" seamless="seamless" src="https://plot.ly/~chris/1638.embed" height="525" width="100%"></iframe>'
+
+ +
+ +
+
+ +
+ + + + +{% endraw %} \ No newline at end of file diff --git a/_posts/python-next/chart-studio/2019-07-03-get-requests.html b/_posts/python-next/chart-studio/2019-07-03-get-requests.html new file mode 100644 index 000000000000..f5420341d9bd --- /dev/null +++ b/_posts/python-next/chart-studio/2019-07-03-get-requests.html @@ -0,0 +1,166 @@ +--- +description: How to download plotly users's public graphs and data with python. +display_as: chart_studio +has_thumbnail: True +language: python/next +layout: user-guide +name: Get Requests +order: 8 +permalink: python/next/get-requests/ +thumbnail: thumbnail/spectral.jpg +title: Python Get Requests | Examples | Plotly +v4upgrade: True +--- + +{% raw %} + +
+
+
+
+

Get and Change a Public Figure

+
+
+
+
+
+
In [1]:
+
+
+
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")
+
+ +
+
+
+ +
+
+ + +
+ +
Out[1]:
+ + + +
+ + + +
+ +
+ +
+
+ +
+
+
+
+
+

Get Data and Change Plot

+
+
+
+
+
+
In [2]:
+
+
+
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")
+
+ +
+
+
+ +
+
+
+
+
+

Get and Replot a Public Figure with URL

+
+
+
+
+
+
In [3]:
+
+
+
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")
+
+ +
+
+
+ +
+
+
+
+
+

Get and Replot a Public Figure with ID

+
+
+
+
+
+
In [4]:
+
+
+
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")
+
+ +
+
+
+ +
+ + + + +{% endraw %} \ No newline at end of file diff --git a/_posts/python-next/chart-studio/2019-07-03-getting-started-with-chart-studio.html b/_posts/python-next/chart-studio/2019-07-03-getting-started-with-chart-studio.html new file mode 100644 index 000000000000..bc5941d6e028 --- /dev/null +++ b/_posts/python-next/chart-studio/2019-07-03-getting-started-with-chart-studio.html @@ -0,0 +1,1032 @@ +--- +description: Installation and Initialization Steps for Using Chart Studio in Python. +display_as: chart_studio +has_thumbnail: True +ipynb: ~notebook_demo/123/installation +language: python/next +layout: user-guide +name: Getting Started with Plotly for Python +order: 0.1 +page_type: example_index +permalink: python/next/getting-started-with-chart-studio/ +thumbnail: thumbnail/bubble.jpg +title: Getting Started with Chart Studio for Python | plotly +v4upgrade: True +--- + +{% raw %} + +
+
+
+
+

Installation

+
+
+
+
+
+
+
+

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

+ +
+
+
+
+
+
+
+

Initialization for Online Plotting

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:

+ +
+
+
+
+
+
In [1]:
+
+
+
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"
+}
+ +
+
+
+
+
+
+
+

Online Plot Privacy

Plot can be set to three different type of privacies: public, private or secret.

+
    +
  • public: Anyone can view this graph. It will appear in your profile and can appear in search engines. You do not need to be logged in to Chart Studio to view this chart.
  • +
  • private: Only you can view this plot. It will not appear in the Plotly feed, your profile, or search engines. You must be logged in to Plotly to view this graph. You can privately share this graph with other Chart Studio users in your online Chart Studio account and they will need to be logged in to view this plot.
  • +
  • secret: Anyone with this secret link can view this chart. It will not appear in the Chart Studio feed, your profile, or search engines. If it is embedded inside a webpage or an IPython notebook, anybody who is viewing that page will be able to view the graph. You do not need to be logged in to view this plot.
  • +
+

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:

+ +
+
+
+
+
+
In [2]:
+
+
+
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

+ +
+
+
+
+
+
+
+

Special Instructions for Chart Studio Enterprise Users

+
+
+
+
+
+
+
+

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:

+ +
+
+
+
+
+
In [3]:
+
+
+
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:

+ +
+
+
+
+
+
In [4]:
+
+
+
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')
+
+ +
+
+
+ +
+
+
+
+
+

Plotly Using virtualenv

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 +
$

+ +
+
+
+
+
+
+
+

Jupyter Setup

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

+ +
+
+
+
+
+
+
+

Start Plotting Online

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.

+
    +
  • Use py.plot() to return the unique url and optionally open the url.
  • +
  • Use 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:

+ +
+
+
+
+
+
In [5]:
+
+
+
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)
+
+ +
+
+
+ +
+
+ + +
+ +
Out[5]:
+ + + + +
+
'https://plot.ly/~PythonPlotBot/27/'
+
+ +
+ +
+
+ +
+
+
+
+
+

Checkout the docstrings for more information:

+ +
+
+
+
+
+
In [6]:
+
+
+
import chart_studio.plotly as py
+help(py.plot)
+
+ +
+
+
+ +
+
+ + +
+ +
+ + +
+
Help on function plot in module chart_studio.plotly.plotly:
+
+plot(figure_or_data, validate=True, **plot_options)
+    Create a unique url for this plot in Plotly and optionally open url.
+    
+    plot_options keyword arguments:
+    filename (string) -- the name that will be associated with this figure
+    auto_open (default=True) -- Toggle browser options
+        True: open this plot in a new browser tab
+        False: do not open plot in the browser, but do return the unique url
+    sharing ('public' | 'private' | 'secret') -- Toggle who can view this
+                                                  graph
+        - 'public': Anyone can view this graph. It will appear in your profile
+                    and can appear in search engines. You do not need to be
+                    logged in to Plotly to view this chart.
+        - 'private': Only you can view this plot. It will not appear in the
+                     Plotly feed, your profile, or search engines. You must be
+                     logged in to Plotly to view this graph. You can privately
+                     share this graph with other Plotly users in your online
+                     Plotly account and they will need to be logged in to
+                     view this plot.
+        - 'secret': Anyone with this secret link can view this chart. It will
+                    not appear in the Plotly feed, your profile, or search
+                    engines. If it is embedded inside a webpage or an IPython
+                    notebook, anybody who is viewing that page will be able to
+                    view the graph. You do not need to be logged in to view
+                    this plot.
+    world_readable (default=True) -- Deprecated: use "sharing".
+                                     Make this figure private/public
+
+
+
+
+ +
+
+ +
+
+
+
In [7]:
+
+
+
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')
+
+ +
+
+
+ +
+
+ + +
+ +
Out[7]:
+ + + +
+ + + +
+ +
+ +
+
+ +
+
+
+
+
+

See more examples in our IPython notebook documentation or check out the py.iplot() docstring for more information.

+ +
+
+
+
+
+
In [8]:
+
+
+
import chart_studio.plotly as py
+help(py.iplot)
+
+ +
+
+
+ +
+
+ + +
+ +
+ + +
+
Help on function iplot in module chart_studio.plotly.plotly:
+
+iplot(figure_or_data, **plot_options)
+    Create a unique url for this plot in Plotly and open in IPython.
+    
+    plot_options keyword arguments:
+    filename (string) -- the name that will be associated with this figure
+    sharing ('public' | 'private' | 'secret') -- Toggle who can view this graph
+        - 'public': Anyone can view this graph. It will appear in your profile
+                    and can appear in search engines. You do not need to be
+                    logged in to Plotly to view this chart.
+        - 'private': Only you can view this plot. It will not appear in the
+                     Plotly feed, your profile, or search engines. You must be
+                     logged in to Plotly to view this graph. You can privately
+                     share this graph with other Plotly users in your online
+                     Plotly account and they will need to be logged in to
+                     view this plot.
+        - 'secret': Anyone with this secret link can view this chart. It will
+                    not appear in the Plotly feed, your profile, or search
+                    engines. If it is embedded inside a webpage or an IPython
+                    notebook, anybody who is viewing that page will be able to
+                    view the graph. You do not need to be logged in to view
+                    this plot.
+    world_readable (default=True) -- Deprecated: use "sharing".
+                                     Make this figure private/public
+
+
+
+
+ +
+
+ +
+
+
+
+
+

You can also create plotly graphs with matplotlib syntax. Learn more in our matplotlib documentation.

+ +
+
+
+
+
+
+
+

Initialization for Offline Plotting

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().

+
    +
  • Use plotly.io.write_html() to create and standalone HTML that is saved locally and opened inside your web browser.
  • +
  • Use 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:

+ +
+
+
+
+
+
In [9]:
+
+
+
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():

+ +
+
+
+
+
+
In [10]:
+
+
+
import plotly
+help(plotly.io.write_html)
+
+ +
+
+
+ +
+
+ + +
+ +
+ + +
+
Help on function write_html in module plotly.io._html:
+
+write_html(fig, file, config=None, auto_play=True, include_plotlyjs=True, include_mathjax=False, post_script=None, full_html=True, animation_opts=None, validate=True, default_width='100%', default_height='100%', auto_open=False)
+    Write a figure to an HTML file representation
+    
+    Parameters
+    ----------
+    fig:
+        Figure object or dict representing a figure
+    file: str or writeable
+        A string representing a local file path or a writeable object
+        (e.g. an open file descriptor)
+    config: dict or None (default None)
+        Plotly.js figure config options
+    auto_play: bool (default=True)
+        Whether to automatically start the animation sequence on page load
+        if the figure contains frames. Has no effect if the figure does not
+        contain frames.
+    include_plotlyjs: bool or string (default True)
+        Specifies how the plotly.js library is included/loaded in the output
+        div string.
+    
+        If True, a script tag containing the plotly.js source code (~3MB)
+        is included in the output.  HTML files generated with this option are
+        fully self-contained and can be used offline.
+    
+        If 'cdn', a script tag that references the plotly.js CDN is included
+        in the output. HTML files generated with this option are about 3MB
+        smaller than those generated with include_plotlyjs=True, but they
+        require an active internet connection in order to load the plotly.js
+        library.
+    
+        If 'directory', a script tag is included that references an external
+        plotly.min.js bundle that is assumed to reside in the same
+        directory as the HTML file. If `file` is a string to a local file path
+        and `full_html` is True then
+    
+        If 'directory', a script tag is included that references an external
+        plotly.min.js bundle that is assumed to reside in the same
+        directory as the HTML file.  If `file` is a string to a local file
+        path and `full_html` is True, then the plotly.min.js bundle is copied
+        into the directory of the resulting HTML file. If a file named
+        plotly.min.js already exists in the output directory then this file
+        is left unmodified and no copy is performed. HTML files generated
+        with this option can be used offline, but they require a copy of
+        the plotly.min.js bundle in the same directory. This option is
+        useful when many figures will be saved as HTML files in the same
+        directory because the plotly.js source code will be included only
+        once per output directory, rather than once per output file.
+    
+        If 'require', Plotly.js is loaded using require.js.  This option
+        assumes that require.js is globally available and that it has been
+        globally configured to know how to find Plotly.js as 'plotly'.
+        This option is not advised when full_html=True as it will result
+        in a non-functional html file.
+    
+        If a string that ends in '.js', a script tag is included that
+        references the specified path. This approach can be used to point
+        the resulting HTML file to an alternative CDN or local bundle.
+    
+        If False, no script tag referencing plotly.js is included. This is
+        useful when the resulting div string will be placed inside an HTML
+        document that already loads plotly.js.  This option is not advised
+        when full_html=True as it will result in a non-functional html file.
+    
+    include_mathjax: bool or string (default False)
+        Specifies how the MathJax.js library is included in the output html
+        div string.  MathJax is required in order to display labels
+        with LaTeX typesetting.
+    
+        If False, no script tag referencing MathJax.js will be included in the
+        output.
+    
+        If 'cdn', a script tag that references a MathJax CDN location will be
+        included in the output.  HTML div strings generated with this option
+        will be able to display LaTeX typesetting as long as internet access
+        is available.
+    
+        If a string that ends in '.js', a script tag is included that
+        references the specified path. This approach can be used to point the
+        resulting HTML div string to an alternative CDN.
+    post_script: str or list or None (default None)
+        JavaScript snippet(s) to be included in the resulting div just after
+        plot creation.  The string(s) may include '{plot_id}' placeholders
+        that will then be replaced by the `id` of the div element that the
+        plotly.js figure is associated with.  One application for this script
+        is to install custom plotly.js event handlers.
+    full_html: bool (default True)
+        If True, produce a string containing a complete HTML document
+        starting with an <html> tag.  If False, produce a string containing
+        a single <div> element.
+    animation_opts: dict or None (default None)
+        dict of custom animation parameters to be passed to the function
+        Plotly.animate in Plotly.js. See
+        https://github.com/plotly/plotly.js/blob/master/src/plots/animation_attributes.js
+        for available options. Has no effect if the figure does not contain
+        frames, or auto_play is False.
+    default_width, default_height: number or str (default '100%')
+        The default figure width/height to use if the provided figure does not
+        specify its own layout.width/layout.height property.  May be
+        specified in pixels as an integer (e.g. 500), or as a css width style
+        string (e.g. '500px', '100%').
+    validate: bool (default True)
+        True if the figure should be validated before being converted to
+        JSON, False otherwise.
+    auto_open: bool (default True
+        If True, open the saved file in a web browser after saving.
+        This argument only applies if `full_html` is True.
+    Returns
+    -------
+    str
+        Representation of figure as an HTML div string
+
+
+
+
+ +
+
+ +
+
+
+
In [11]:
+
+
+
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.

+ +
+
+
+
+
+
In [12]:
+
+
+
fig.show()
+
+ +
+
+
+ +
+
+ + +
+ +
+ + + +
+
+ + +
+ +
+
+ +
+ +
+
+ +
+
+
+
In [13]:
+
+
+
import plotly
+help(plotly.io.show)
+
+ +
+
+
+ +
+
+ + +
+ +
+ + +
+
Help on function show in module plotly.io._renderers:
+
+show(fig, renderer=None, validate=True, **kwargs)
+    Show a figure using either the default renderer(s) or the renderer(s)
+    specified by the renderer argument
+    
+    Parameters
+    ----------
+    fig: dict of Figure
+        The Figure object or figure dict to display
+    
+    renderer: str or None (default None)
+        A string containing the names of one or more registered renderers
+        (separated by '+' characters) or None.  If None, then the default
+        renderers specified in plotly.io.renderers.default are used.
+    
+    validate: bool (default True)
+        True if the figure should be validated before being shown,
+        False otherwise.
+    
+    Returns
+    -------
+    None
+
+
+
+
+ +
+
+ +
+
+
+
+
+

For more examples on plotting offline with Plotly in python please visit our offline documentation.

+ +
+
+
+
+
+
+
+

Using Plotly with Pandas

To use Plotly with Pandas first $ pip install pandas and then import pandas in your code like in the example below.

+ +
+
+
+
+
+
In [14]:
+
+
+
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')
+
+ +
+
+
+ +
+
+ + +
+ +
Out[14]:
+ + + +
+ + + +
+ +
+ +
+
+ +
+
+
+
+
+

MORE EXAMPLES

Check out more examples and tutorials for using Plotly in python here!

+ +
+
+
+ + + + +{% endraw %} \ No newline at end of file diff --git a/_posts/python-next/chart-studio/2019-07-03-ipython-notebook-tutorial.html b/_posts/python-next/chart-studio/2019-07-03-ipython-notebook-tutorial.html new file mode 100644 index 000000000000..81db65adf5fc --- /dev/null +++ b/_posts/python-next/chart-studio/2019-07-03-ipython-notebook-tutorial.html @@ -0,0 +1,960 @@ +--- +description: Jupyter notebook tutorial on how to install, run, and use Jupyter for interactive matplotlib plotting, data analysis, and publishing code +display_as: chart_studio +has_thumbnail: True +ipynb: ~chelsea_lyn/14070 +language: python/next +layout: user-guide +name: Jupyter Notebook Tutorial +order: 11 +page_type: example_index +permalink: python/next/ipython-notebook-tutorial/ +thumbnail: thumbnail/ipythonnb.jpg +title: Jupyter Notebook Tutorial | plotly +v4upgrade: True +--- + +{% raw %} + +
+
+
+
+

Introduction

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:

+ +
+
+
+
+
+
In [1]:
+
+
+
print("hello world")
+
+ +
+
+
+ +
+
+ + +
+ +
+ + +
+
hello world
+
+
+
+ +
+
+ +
+
+
+
+
+

Installation

There are a few ways to use a Jupyter Notebook:

+
    +
  • Install with pip. Open a terminal and type: $ pip install jupyter.
  • +
  • Windows users can install with setuptools.
  • +
  • Anaconda and Enthought allow you to download a desktop version of Jupyter Notebook.
  • +
  • nteract allows users to work in a notebook enviornment via a desktop application.
  • +
  • Microsoft Azure provides hosted access to Jupyter Notebooks.
  • +
  • Domino Data Lab offers web-based Notebooks.
  • +
  • tmpnb launches a temporary online Notebook for individual users.
  • +
+ +
+
+
+
+
+
+
+

Getting Started

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.

+ +
+
+
+
+
+
+
+

Helpful Commands

- 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.

+ +
+
+
+
+
+
In [2]:
+
+
+
help
+
+ +
+
+
+ +
+
+ + +
+ +
Out[2]:
+ + + + +
+
Type help() for interactive help, or help(object) for help about object.
+
+ +
+ +
+
+ +
+
+
+
+
+

- Quick Reference: open quick reference by running:

+ +
+
+
+
+
+
In [3]:
+
+
+
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.

+ +
+
+
+
+
+
+
+

Languages

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.

+

Package Management

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:

+
    +
  • Pandas: import data via a url and create a dataframe to easily handle data for analysis and graphing. See examples of using Pandas here: https://plot.ly/pandas/.
  • +
  • NumPy: a package for scientific computing with tools for algebra, random number generation, integrating with databases, and managing data. See examples of using NumPy here: https://plot.ly/numpy/.
  • +
  • SciPy: a Python-based ecosystem of packages for math, science, and engineering.
  • +
  • Plotly: a graphing library for making interactive, publication-quality graphs. See examples of statistic, scientific, 3D charts, and more here: https://plot.ly/python.
  • +
+ +
+
+
+
+
+
In [4]:
+
+
+
import pandas as pd
+import numpy as np
+import scipy as sp
+import chart_studio.plotly as py
+
+ +
+
+
+ +
+
+
+
+
+

Import Data

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:

+ +
+
+
+
+
+
In [5]:
+
+
+
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')
+
+ +
+
+
+ +
+
+ + +
+ +
Out[5]:
+ + + +
+ + + +
+ +
+ +
+
+ +
+
+
+
+
+

Use dataframe.column_title to index the dataframe:

+ +
+
+
+
+
+
In [6]:
+
+
+
schools = df.School
+schools[0]
+
+ +
+
+
+ +
+
+ + +
+ +
Out[6]:
+ + + + +
+
'MIT'
+
+ +
+ +
+
+ +
+
+
+
+
+

Most pandas functions also work on an entire dataframe. For example, calling std() calculates the standard deviation for each column.

+ +
+
+
+
+
+
In [7]:
+
+
+
df.std()
+
+ +
+
+
+ +
+
+ + +
+ +
Out[7]:
+ + + + +
+
Women    12.813683
+Men      25.705289
+Gap      14.137084
+dtype: float64
+
+ +
+ +
+
+ +
+
+
+
+
+

Plotting Inline

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:

+ +
+
+
+
+
+
In [8]:
+
+
+
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')
+
+ +
+
+
+ +
+
+ + +
+ +
Out[8]:
+ + + +
+ + + +
+ +
+ +
+
+ +
+
+
+
+
+

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.

+ +
+
+
+
+
+
In [9]:
+
+
+
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')
+
+ +
+
+
+ +
+
+ + +
+ +
Out[9]:
+ + + +
+ + + +
+ +
+ +
+
+ +
+
+
+
+
+

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.

+ +
+
+
+
+
+
+
+

Plotting Interactive Maps

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.

+ +
+
+
+
+
+
In [10]:
+
+
+
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')
+
+ +
+
+
+ +
+
+ + +
+ +
Out[10]:
+ + + +
+ + + +
+ +
+ +
+
+ +
+
+
+
+
+

3D Plotting

Using Numpy and Plotly, we can make interactive 3D plots in the Notebook as well.

+ +
+
+
+
+
+
In [11]:
+
+
+
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')
+
+ +
+
+
+ +
+
+ + +
+ +
Out[11]:
+ + + +
+ + + +
+ +
+ +
+
+ +
+
+
+
+
+

Animated Plots

Checkout Plotly's animation documentation to see how to create animated plots inline in Jupyter notebooks like the Gapminder plot displayed below: +https://plot.ly/~PythonPlotBot/231/

+ +
+
+
+
+
+
+
+

Plot Controls & IPython widgets

Add sliders, buttons, and dropdowns to your inline chart:

+ +
+
+
+
+
+
In [12]:
+
+
+
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')
+
+ +
+
+
+ +
+
+ + +
+ +
Out[12]:
+ + + +
+ + + +
+ +
+ +
+
+ +
+
+
+
+
+

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. +
+

+ +
+
+
+
+
+
+
+

Executing R Code

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

+ +
+
+
+
+
+
+
+

Additional Embed Features

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:

+ +
+
+
+
+
+
In [13]:
+
+
+
from IPython.display import YouTubeVideo
+YouTubeVideo("wupToqz1e2g")
+
+ +
+
+
+ +
+
+ + +
+ +
Out[13]:
+ + + +
+ + + +
+ +
+ +
+
+ +
+
+
+
+
+

LaTeX

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.

+ +
+
+
+
+
+
In [14]:
+
+
+
from IPython.display import display, Math, Latex
+
+display(Math(r'F(k) = \int_{-\infty}^{\infty} f(x) e^{2\pi i k} dx'))
+
+ +
+
+
+ +
+
+ + +
+ +
+ + + + +
+$\displaystyle F(k) = \int_{-\infty}^{\infty} f(x) e^{2\pi i k} dx$ +
+ +
+ +
+
+ +
+
+
+
+
+

Exporting & Publishing Notebooks

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:

+ + +
+
+
+
+
+
+
+

Publishing Dashboards

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.

+ +
+
+
+
+
+
+
+

Publishing Dash Apps

For users looking to ship and productionize Python apps, dash is an assemblage of Flask, Socketio, Jinja, Plotly and boiler plate CSS and JS for easily creating data visualization web-apps with your Python data analysis backend. +
+ +

+ +
+
+
+
+
+
+
+

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!

+

IPython Notebook Gallery

+ +
+
+
+ + + + +{% endraw %} \ No newline at end of file diff --git a/_posts/python-next/chart-studio/2019-07-03-presentations-tool.html b/_posts/python-next/chart-studio/2019-07-03-presentations-tool.html new file mode 100644 index 000000000000..b94d8b782fd5 --- /dev/null +++ b/_posts/python-next/chart-studio/2019-07-03-presentations-tool.html @@ -0,0 +1,657 @@ +--- +description: How to create and publish a spectacle-presentation with the Python API. +display_as: chart_studio +has_thumbnail: True +language: python/next +layout: user-guide +name: Presentations Tool +order: 0.6 +page_type: u-guide +permalink: python/next/presentations-tool/ +thumbnail: thumbnail/pres_api.jpg +title: Presentations Tool | plotly +v4upgrade: True +--- + +{% raw %} + +
+
+
+
+

Plotly Presentations

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.

+ +
+
+
+
+
+
+
+

Current Limitations

Boldface, italics and hypertext are not supported features of the Presentation API.

+ +
+
+
+
+
+
+
+

Display in Jupyter

The function below generates HTML code to display the presentation in an iframe directly in Jupyter.

+ +
+
+
+
+
+
In [12]:
+
+
+
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
+
+ +
+
+
+ +
+
+
+
+
+

Simple Example

+
+
+
+
+
+
In [13]:
+
+
+
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)
+
+ +
+
+
+ +
+
+
+ +
+
+
+
In [14]:
+
+
+
import IPython
+
+iframe_0 = url_to_iframe(pres_url_0, True)
+IPython.display.HTML(iframe_0)
+
+ +
+
+
+ +
+
+ + +
+ +
Out[14]:
+ + + +
+ + + ' + +
+

Click on the presentation above and use left/right arrow keys to flip through the slides.

+
+ + +
+ +
+ +
+
+ +
+
+
+
+
+

Insert Plotly Chart

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.

+ +
+
+
+
+
+
In [15]:
+
+
+
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)
+
+ +
+
+
+ +
+
+
+ +
+
+
+
In [16]:
+
+
+
import IPython
+
+iframe_1 = url_to_iframe(pres_url_1, True)
+IPython.display.HTML(iframe_1)
+
+ +
+
+
+ +
+
+ + +
+ +
Out[16]:
+ + + +
+ + + ' + +
+

Click on the presentation above and use left/right arrow keys to flip through the slides.

+
+ + +
+ +
+ +
+
+ +
+
+
+
+
+

Insert Web Images

To insert an image from the web, insert the a Image(url) where url is the image url.

+ +
+
+
+
+
+
In [17]:
+
+
+
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)
+
+ +
+
+
+ +
+
+
+ +
+
+
+
In [18]:
+
+
+
import IPython
+
+iframe_2 = url_to_iframe(pres_url_2, True)
+IPython.display.HTML(iframe_2)
+
+ +
+
+
+ +
+
+ + +
+ +
Out[18]:
+ + + +
+ + + ' + +
+

Click on the presentation above and use left/right arrow keys to flip through the slides.

+
+ + +
+ +
+ +
+
+ +
+
+
+
+
+

Image Stretch

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.

+ +
+
+
+
+
+
In [19]:
+
+
+
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)
+
+ +
+
+
+ +
+
+
+ +
+
+
+
In [20]:
+
+
+
import IPython
+
+iframe_3 = url_to_iframe(pres_url_3, False)
+IPython.display.HTML(iframe_3)
+
+ +
+
+
+ +
+
+ + +
+ +
Out[20]:
+ + + +
+ + + ' + +
+ +
+ +
+
+ +
+
+
+
+
+

Transitions

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
+ +
+
+
+
+
+
In [21]:
+
+
+
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)
+
+ +
+
+
+ +
+
+
+
In [22]:
+
+
+
import IPython
+
+iframe_6 = url_to_iframe(pres_url_6, True)
+IPython.display.HTML(iframe_6)
+
+ +
+
+
+ +
+
+ + +
+ +
Out[22]:
+ + + +
+ + + ' + +
+

Click on the presentation above and use left/right arrow keys to flip through the slides.

+
+ + +
+ +
+ +
+
+ +
+
+
+
+
+

Reference

+
+
+
+
+
+
In [23]:
+
+
+
help(py.presentation_ops)
+
+ +
+
+
+ +
+
+ + +
+ +
+ + +
+
Help on class presentation_ops in module chart_studio.plotly.plotly:
+
+class presentation_ops(builtins.object)
+ |  Interface to Plotly's Spectacle-Presentations API.
+ |  
+ |  Class methods defined here:
+ |  
+ |  upload(presentation, filename, sharing='public', auto_open=True) from builtins.type
+ |      Function for uploading presentations to Plotly.
+ |      
+ |      :param (dict) presentation: the JSON presentation to be uploaded. Use
+ |          plotly.presentation_objs.Presentation to create presentations
+ |          from a Markdown-like string.
+ |      :param (str) filename: the name of the presentation to be saved in
+ |          your Plotly account. Will overwrite a presentation of the same
+ |          name if it already exists in your files.
+ |      :param (str) sharing: can be set to either 'public', 'private'
+ |          or 'secret'. If 'public', your presentation will be viewable by
+ |          all other users. If 'private' only you can see your presentation.
+ |          If it is set to 'secret', the url will be returned with a string
+ |          of random characters appended to the url which is called a
+ |          sharekey. The point of a sharekey is that it makes the url very
+ |          hard to guess, but anyone with the url can view the presentation.
+ |      :param (bool) auto_open: automatically opens the presentation in the
+ |          browser.
+ |      
+ |      See the documentation online for examples.
+ |  
+ |  ----------------------------------------------------------------------
+ |  Data descriptors defined here:
+ |  
+ |  __dict__
+ |      dictionary for instance variables (if defined)
+ |  
+ |  __weakref__
+ |      list of weak references to the object (if defined)
+
+
+
+
+ +
+
+ +
+ + + + +{% endraw %} \ No newline at end of file diff --git a/_posts/python-next/chart-studio/2019-07-03-privacy.html b/_posts/python-next/chart-studio/2019-07-03-privacy.html new file mode 100644 index 000000000000..f6f23fb47c99 --- /dev/null +++ b/_posts/python-next/chart-studio/2019-07-03-privacy.html @@ -0,0 +1,500 @@ +--- +description: How to set the privacy settings of plotly graphs in python. Three examples of different privacy options: public, private and secret. +display_as: chart_studio +has_thumbnail: True +ipynb: ~notebook_demo/97 +language: python/next +layout: user-guide +name: Privacy +order: 2 +permalink: python/next/privacy/ +thumbnail: thumbnail/privacy.jpg +title: Privacy | plotly +v4upgrade: True +--- + +{% raw %} + +
+
+
+
+

Default Privacy

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.

+ +
+
+
+
+
+
+
+

Public Graphs

+
+
+
+
+
+
In [1]:
+
+
+
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')
+
+ +
+
+
+ +
+
+ + +
+ +
Out[1]:
+ + + +
+ + + +
+ +
+ +
+
+ +
+
+
+
+
+

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:

+ +
+
+
+
+
+
In [2]:
+
+
+
py.plot(data, filename='privacy-public', sharing='public')
+
+ +
+
+
+ +
+
+ + +
+ +
Out[2]:
+ + + + +
+
'https://plot.ly/~PythonPlotBot/2677/'
+
+ +
+ +
+
+ +
+
+
+
+
+

Private Graphs

+
+
+
+
+
+
In [3]:
+
+
+
py.iplot(data, filename='privacy-private', sharing='private')
+
+ +
+
+
+ +
+
+ + +
+ +
Out[3]:
+ + + +
+ + + +
+ +
+ +
+
+ +
+
+
+
+
+

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:

+ +
+
+
+
+
+
In [4]:
+
+
+
py.plot(data, filename='privacy-private', sharing='private')
+
+ +
+
+
+ +
+
+ + +
+ +
Out[4]:
+ + + + +
+
'https://plot.ly/~PythonPlotBot/2679/'
+
+ +
+ +
+
+ +
+
+
+
+
+

Secret Graphs

+
+
+
+
+
+
In [5]:
+
+
+
py.iplot(data, filename='privacy-secret', sharing='secret')
+
+ +
+
+
+ +
+
+ + +
+ +
Out[5]:
+ + + +
+ + + +
+ +
+ +
+
+ +
+
+
+
+
+

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:

+ +
+
+
+
+
+
In [6]:
+
+
+
py.plot(data, filename='privacy-secret', sharing='secret')
+
+ +
+
+
+ +
+
+ + +
+ +
Out[6]:
+ + + + +
+
'https://plot.ly/~PythonPlotBot/475?share_key=UaGz0FTFLklnEd7XTKaqy8'
+
+ +
+ +
+
+ +
+
+
+
+
+

Make All Future Plots Private

To make all future plots private, you can update your configuration file to create private plots by default:

+ +
+
+
+
+
+
In [7]:
+
+
+
import chart_studio
+chart_studio.tools.set_config_file(world_readable=False, sharing='private')
+
+ +
+
+
+ +
+
+
+
+
+

Make All Existing Plots Private

This example uses Plotly's REST API

+ +
+
+
+
+
+
In [8]:
+
+
+
import json
+import requests
+from requests.auth import HTTPBasicAuth
+
+ +
+
+
+ +
+
+
+
+
+

Define variables, including YOUR USERNAME and API KEY

+ +
+
+
+
+
+
In [9]:
+
+
+
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

+ +
+
+
+
+
+
In [ ]:
+
+
+
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)
+
+ +
+
+
+ +
+
+
+
+
+

Reference

+
+
+
+
+
+
In [10]:
+
+
+
help(py.plot)
+
+ +
+
+
+ +
+
+ + +
+ +
+ + +
+
Help on function plot in module chart_studio.plotly.plotly:
+
+plot(figure_or_data, validate=True, **plot_options)
+    Create a unique url for this plot in Plotly and optionally open url.
+    
+    plot_options keyword arguments:
+    filename (string) -- the name that will be associated with this figure
+    auto_open (default=True) -- Toggle browser options
+        True: open this plot in a new browser tab
+        False: do not open plot in the browser, but do return the unique url
+    sharing ('public' | 'private' | 'secret') -- Toggle who can view this
+                                                  graph
+        - 'public': Anyone can view this graph. It will appear in your profile
+                    and can appear in search engines. You do not need to be
+                    logged in to Plotly to view this chart.
+        - 'private': Only you can view this plot. It will not appear in the
+                     Plotly feed, your profile, or search engines. You must be
+                     logged in to Plotly to view this graph. You can privately
+                     share this graph with other Plotly users in your online
+                     Plotly account and they will need to be logged in to
+                     view this plot.
+        - 'secret': Anyone with this secret link can view this chart. It will
+                    not appear in the Plotly feed, your profile, or search
+                    engines. If it is embedded inside a webpage or an IPython
+                    notebook, anybody who is viewing that page will be able to
+                    view the graph. You do not need to be logged in to view
+                    this plot.
+    world_readable (default=True) -- Deprecated: use "sharing".
+                                     Make this figure private/public
+
+
+
+
+ +
+
+ +
+ + + + +{% endraw %} \ No newline at end of file diff --git a/_posts/python-next/chart-studio/2019-07-03-proxy-configuration.html b/_posts/python-next/chart-studio/2019-07-03-proxy-configuration.html new file mode 100644 index 000000000000..c22ef98ca25c --- /dev/null +++ b/_posts/python-next/chart-studio/2019-07-03-proxy-configuration.html @@ -0,0 +1,51 @@ +--- +description: How to configure Plotly's Python API to work with corporate proxies +display_as: chart_studio +has_thumbnail: True +language: python/next +layout: user-guide +name: Requests Behind Corporate Proxies +order: 10 +permalink: python/next/proxy-configuration/ +thumbnail: thumbnail/net.jpg +title: requests.exceptions.ConnectionError - Getting Around Corporate Proxies +v4upgrade: True +--- + +{% raw %} + +
+
+
+
+

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?

+

Log an issue

+

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.

+ +
+
+
+ + + + +{% endraw %} \ No newline at end of file diff --git a/_posts/python-next/chart-studio/data-api.ipynb b/_posts/python-next/chart-studio/data-api.ipynb index b7af49e62675..d197858306aa 100644 --- a/_posts/python-next/chart-studio/data-api.ipynb +++ b/_posts/python-next/chart-studio/data-api.ipynb @@ -23,7 +23,7 @@ "name": "stdout", "output_type": "stream", "text": [ - "https://plot.ly/~PythonPlotBot/3521/\n" + "https://plot.ly/~PythonPlotBot/3534/\n" ] } ], @@ -68,14 +68,14 @@ " \n", " " ], "text/plain": [ - "" + "" ] }, "execution_count": 2, @@ -121,7 +121,7 @@ " " ], "text/plain": [ - "" + "" ] }, "execution_count": 3, @@ -168,7 +168,7 @@ " " ], "text/plain": [ - "" + "" ] }, "execution_count": 4, @@ -206,7 +206,7 @@ "name": "stdout", "output_type": "stream", "text": [ - "https://plot.ly/~PythonPlotBot/3524/\n" + "https://plot.ly/~PythonPlotBot/3537/\n" ] } ], @@ -233,14 +233,14 @@ " \n", " " ], "text/plain": [ - "" + "" ] }, "execution_count": 6, @@ -279,7 +279,7 @@ " " ], "text/plain": [ - "" + "" ] }, "execution_count": 7, @@ -324,7 +324,7 @@ "name": "stdout", "output_type": "stream", "text": [ - "https://plot.ly/~PythonPlotBot/3524/\n" + "https://plot.ly/~PythonPlotBot/3537/\n" ] } ], @@ -602,7 +602,7 @@ }, "plotly": { "description": "How to upload data to Plotly from Python with the Plotly Grid API.", - "display_as": "file_settings", + "display_as": "chart_studio", "has_thumbnail": true, "language": "python", "layout": "user-guide", diff --git a/_posts/python-next/chart-studio/data-api.md b/_posts/python-next/chart-studio/data-api.md index 2acc09df8325..d4173b41185c 100644 --- a/_posts/python-next/chart-studio/data-api.md +++ b/_posts/python-next/chart-studio/data-api.md @@ -22,19 +22,17 @@ jupyter: pygments_lexer: ipython3 version: 3.6.5 plotly: - permalink: python/data-api/ description: How to upload data to Plotly from Python with the Plotly Grid API. - name: Upload Data to Plotly from Python + display_as: chart_studio has_thumbnail: true - thumbnail: thumbnail/table.jpg + language: python layout: user-guide name: Plots from Grids - language: python - title: Plotly Data API - display_as: chart_studio - has_thumbnail: true - page_type: u-guide order: 5 + page_type: u-guide + permalink: python/data-api/ + thumbnail: thumbnail/table.jpg + title: Plotly Data API v4upgrade: true --- diff --git a/_posts/python-next/chart-studio/delete-plots.ipynb b/_posts/python-next/chart-studio/delete-plots.ipynb index 54d743c49bf8..c6c4524922bf 100644 --- a/_posts/python-next/chart-studio/delete-plots.ipynb +++ b/_posts/python-next/chart-studio/delete-plots.ipynb @@ -80,7 +80,7 @@ { "data": { "text/plain": [ - "'private_plotly:604'" + "'private_plotly:658'" ] }, "execution_count": 3, @@ -89,7 +89,7 @@ } ], "source": [ - "fid = username+':604'\n", + "fid = username+':658'\n", "fid" ] }, @@ -165,22 +165,22 @@ }, { "cell_type": "code", - "execution_count": 11, + "execution_count": 6, "metadata": {}, "outputs": [ { "data": { "text/plain": [ - "'private_plotly:651'" + "'private_plotly:661'" ] }, - "execution_count": 11, + "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ - "fid_permanent_delete = username+':651'\n", + "fid_permanent_delete = username+':661'\n", "fid_permanent_delete" ] }, @@ -193,7 +193,7 @@ }, { "cell_type": "code", - "execution_count": 12, + "execution_count": 7, "metadata": {}, "outputs": [ { @@ -202,7 +202,7 @@ "" ] }, - "execution_count": 12, + "execution_count": 7, "metadata": {}, "output_type": "execute_result" } @@ -221,7 +221,7 @@ }, { "cell_type": "code", - "execution_count": 13, + "execution_count": 8, "metadata": {}, "outputs": [ { @@ -230,7 +230,7 @@ "" ] }, - "execution_count": 13, + "execution_count": 8, "metadata": {}, "output_type": "execute_result" } @@ -325,7 +325,7 @@ }, "plotly": { "description": "How to delete plotly graphs in python.", - "display_as": "file_settings", + "display_as": "chart_studio", "has_thumbnail": true, "ipynb": "~notebook_demo/98", "language": "python", diff --git a/_posts/python-next/chart-studio/delete-plots.md b/_posts/python-next/chart-studio/delete-plots.md index bd8e11a27512..fe3a854ec2ba 100644 --- a/_posts/python-next/chart-studio/delete-plots.md +++ b/_posts/python-next/chart-studio/delete-plots.md @@ -22,19 +22,17 @@ jupyter: pygments_lexer: ipython3 version: 3.6.5 plotly: - permalink: python/delete-plots/ description: How to delete plotly graphs in python. - name: Deleting Plots with the Python API - has_thumbnail: true - thumbnail: thumbnail/delete.jpg - layout: user-guide - name: Deleting Plots - language: python display_as: chart_studio has_thumbnail: true ipynb: ~notebook_demo/98 - page_type: u-guide + language: python + layout: user-guide + name: Deleting Plots order: 9 + page_type: u-guide + permalink: python/delete-plots/ + thumbnail: thumbnail/delete.jpg v4upgrade: true --- @@ -75,7 +73,7 @@ url Include the file id in your request.
The file id is your `username:plot_id#` ```python -fid = username+':604' +fid = username+':658' fid ``` @@ -105,7 +103,7 @@ url ``` ```python -fid_permanent_delete = username+':651' +fid_permanent_delete = username+':661' fid_permanent_delete ``` diff --git a/_posts/python-next/chart-studio/embedding-charts.md b/_posts/python-next/chart-studio/embedding-charts.md index b785d7dab91e..b7f6600e3de6 100644 --- a/_posts/python-next/chart-studio/embedding-charts.md +++ b/_posts/python-next/chart-studio/embedding-charts.md @@ -22,17 +22,17 @@ jupyter: pygments_lexer: ipython3 version: 3.6.5 plotly: - v4upgrade: true - title: Python Embedding Graphs in HTML | Examples | Plotly - name: Embedding Graphs in HTML - permalink: python/embedding-plotly-graphs-in-HTML/ description: How to embed plotly graphs with an iframe in HTML. - layout: user-guide - language: python - has_thumbnail: true - thumbnail: thumbnail/embed.jpg display_as: chart_studio + has_thumbnail: true + language: python + layout: user-guide + name: Embedding Graphs in HTML order: 6 + permalink: python/embedding-plotly-graphs-in-HTML/ + thumbnail: thumbnail/embed.jpg + title: Python Embedding Graphs in HTML | Examples | Plotly + v4upgrade: true --- Plotly graphs can be embedded in any HTML page. This includes [IPython notebooks](https://plot.ly/ipython-notebooks/), [Wordpress sites](https://wordpress.org/plugins/wp-plotly), dashboards, blogs, and more. @@ -47,3 +47,7 @@ import chart_studio.tools as tls tls.get_embed('https://plot.ly/~chris/1638') ``` + +```python + +``` diff --git a/_posts/python-next/chart-studio/get-requests.ipynb b/_posts/python-next/chart-studio/get-requests.ipynb index 1bd0528679f1..c731608399e8 100644 --- a/_posts/python-next/chart-studio/get-requests.ipynb +++ b/_posts/python-next/chart-studio/get-requests.ipynb @@ -19,14 +19,14 @@ " \n", " " ], "text/plain": [ - "" + "" ] }, "execution_count": 1, diff --git a/_posts/python-next/chart-studio/getting-started-with-chart-studio.ipynb b/_posts/python-next/chart-studio/getting-started-with-chart-studio.ipynb index 5af12dc8a5e4..47d81ed93b5d 100644 --- a/_posts/python-next/chart-studio/getting-started-with-chart-studio.ipynb +++ b/_posts/python-next/chart-studio/getting-started-with-chart-studio.ipynb @@ -324,7 +324,7 @@ " " ], "text/plain": [ - "" + "" ] }, "execution_count": 7, @@ -1341,20 +1341,20 @@ "
\n", " \n", " \n", - "
\n", + "
\n", "