Show Sidebar Hide Sidebar

Dashboard API in Python

How to create and publish a dashboard with the Python API.

New to Plotly?

Plotly's Python library is free and open source! Get started by downloading the client and reading the primer.
You can set up Plotly to work in online or offline mode, or in jupyter notebooks.
We also have a quick-reference cheatsheet (new!) to help you get started!

Version Check

Note: The Dashboards API is available in version 2.0.5.+
Run pip install plotly --upgrade to update your Plotly version

In [1]:
import plotly

Plotly Dashboards

A dashboard is a collection of plots and images organized with a certain layout. There are two ways to create a Plotly dashboard: using the online creator or programmatically with Plotly's python API.

In Plotly, dashboards can contain plots, text and webpage images. To use the online creator, see Dashboards are stored in your Plotly account:

Dashboard Privacy

In the same way that a plot can be public, private or secret, dashboards can also be public, private or secret independent of the plots inside them. So if you're sharing a dashboard with someone and one or more of your plots are set to private, they will not show for the other user. For more information about this refer to the Dashboard Privacy Doc.

Initialize a Dashboard

Now you can programmatically create and modify dashboards in Python. These dashboards can be uploaded to the Plotly server to join your other dashboards. You can also retrieve dashboards from Plotly.

Let's start by creating a new dashboard. To get a preview of the HTML representation of the dashboard organization - i.e. where the items in the dashboard are located with respect to one another - run the .get_preview() method in a notebook cell. Everytime you modify your dashboard you should run this to check what it looks like.

IMPORTANT NOTE: because of the way .get_preview() works only one cell of the Jupyter notebook can display the preview of the dashboard after running this method. A good setup is to designate one cell to look like my_dboard.get_preview() and then run that every time you make a change to update the HTML representation of the dashboard. For the purposes of clarity, each modification of the dashboard in this tutorial is clearly shown.

In [2]:
import plotly.dashboard_objs as dashboard

import IPython.display
from IPython.display import Image

my_dboard = dashboard.Dashboard()

IPython terminal

Choose Plots

In order to use the dashboard, we need to put some plots into it. You can either make these on-the-fly in Jupyter or use a plot you've already created by using its url.

In [3]:
import plotly.graph_objs as go
import plotly.plotly as py

import numpy as np

colorscale = [[0, '#FAEE1C'], [0.33, '#F3558E'], [0.66, '#9C1DE7'], [1, '#581B98']]
trace1 = go.Scatter(
    y = np.random.randn(500),
        color = np.random.randn(500),
data = [trace1]
url_1 = py.plot(data, filename='scatter-for-dashboard', auto_open=False)
py.iplot(data, filename='scatter-for-dashboard')
In [4]:
import plotly.plotly as py
import plotly.graph_objs as go

colors = ['#FAEE1C', '#F3558E', '#9C1DE7', '#581B98']

trace=go.Pie(labels=labels,values=values,marker={'colors': colors})

url_2 = py.plot([trace], filename='pie-for-dashboard', auto_open=False)
py.iplot([trace], filename='pie-for-dashboard')

Create a plot with a secret key:

In [5]:
import plotly.plotly as py
import plotly.graph_objs as go

import numpy as np

x0 = np.random.randn(50)
x1 = np.random.randn(50) + 2
x2 = np.random.randn(50) + 4
x3 = np.random.randn(50) + 6

colors = ['#FAEE1C', '#F3558E', '#9C1DE7', '#581B98']

trace0 = go.Box(x=x0, marker={'color': colors[0]})
trace1 = go.Box(x=x1, marker={'color': colors[1]})
trace2 = go.Box(x=x2, marker={'color': colors[2]})
trace3 = go.Box(x=x3, marker={'color': colors[3]})
data = [trace0, trace1, trace2, trace3]

url_3 = py.plot([trace], filename='box-plots-for-dashboard', sharing='secret', auto_open=False)
py.iplot(data, filename='box-plots-for-dashboard')
In [6]:

Add a Box

If you want to place a plot, text box or a webpage into dashboard, you need to place it in a box (which is just a dictionary) and insert it into your dashboard.

A box with a plot in it takes the form:

    'type': 'box',
    'boxType': 'plot',
    'fileId': '',
    'shareKey': None,
    'title': ''
  • fileId is of the form username:number (eg. 'PlotBot:1300') which can be found in the url of your plot once it's up on the Plotly server.
  • shareKey: optional - the sharekey if your plot is secret.
  • title: optional - sets the title of your box.

A box with text in it takes the form:

    'type': 'box',
    'boxType': 'text',
    'text': '',
    'title': ''
  • text: the text you want displayed in your box.
  • title: optional - sets the title of your box.

A box with a webpage in it takes the form:

    'type': 'box',
    'boxType': 'webpage',
    'url': '',
    'title': ''

Note: As above, you can run py.plot() to return the url of your plot and then assign it to a variable to use in a dashboard later.

To extract the fileId from a url, use the fileId_from_url below. If your url is secret, use sharekey_from_url to return the sharekey from the url, then place in your box that contains a secret plot.

In [7]:
def fileId_from_url(url):
    """Return fileId from a url."""
    index = url.find('~')
    fileId = url[index + 1:]
    local_id_index = fileId.find('/')

    share_key_index = fileId.find('?share_key')
    if share_key_index == -1:
        return fileId.replace('/', ':')
        return fileId[:share_key_index].replace('/', ':')

def sharekey_from_url(url):
    """Return the sharekey from a url."""
    index = url.find('share_key=')
    return url[index + len('share_key='):]

fileId_1 = fileId_from_url(url_1)
fileId_2 = fileId_from_url(url_2)
fileId_3 = fileId_from_url(url_3)
In [8]:
box_1 = {
    'type': 'box',
    'boxType': 'plot',
    'fileId': fileId_1,
    'title': 'scatter-for-dashboard'

box_2 = {
    'type': 'box',
    'boxType': 'plot',
    'fileId': fileId_2,
    'title': 'pie-for-dashboard'

box_3 = {
    'type': 'box',
    'boxType': 'plot',
    'fileId': fileId_3,
    'title': 'box-for-dashboard',
    'shareKey': sharekey_from_url(url_3)
In [9]:

IPython terminal

In [10]:
my_dboard.insert(box_2, 'above', 1)

IPython terminal

In [11]:
my_dboard.insert(box_3, 'left', 2)

IPython terminal

Get Box

Each time my_dboard.get_preview() is run a layout of the dashboard is returned where each rectangular area is denoted by a number in the center. These numbers or box ids are assigned on-the-fly each time .get_preview() is run and are liable to change.

Remember that a box is just a dictionary that contains multiple of keys to specify the plot, webpage or text that it contains (see Add a Box section above). To lookup the box that each box id is representing, run my_dboard.get_box().

For example, let's say you want to see what plot will show up in the region 1 of the dashboard. Run my_dboard.get_box(1) and the JSON representation of the box will be returned:

In [12]:
{'boxType': 'plot',
 'fileId': u'PlotBot:1296',
 'title': 'scatter-for-dashboard',
 'type': 'box'}

You can now reassign the values in the dictionary to update that box. For example, you can change the title of that plot:

In [13]:
my_dboard.get_box(1)['title'] = 'a new title'
{'boxType': 'plot',
 'fileId': u'PlotBot:1296',
 'title': 'a new title',
 'type': 'box'}

Swap Boxes

If you want to swap the locations of two boxes you've already placed in the dashboard, run my_dboard.get_preview() to look at the layout of the dashboard, then simply pick two unique box ids and you will swap the contents stored at those locations.

In [14]:
In [15]:
my_dboard.swap(2, 3)

Remove Box

You can remove a box from the dashboard by identifying its box id from the my_dboard.get_preview().

In [16]:
my_dboard.insert(box_1, 'below', 2)

IPython terminal

In [17]:

IPython terminal

Add Title

Set the title of your dashboard.

In [18]:
my_dboard['settings']['title'] = 'My First Dashboard with Python'

Add a logo to the top-left corner of the dashboard.

In [19]:
my_dboard['settings']['logoUrl'] = ''

Add some links to the header of the dashboard.

In [20]:
my_dboard['settings']['links'] = []
my_dboard['settings']['links'].append({'title': 'Link to Plotly', 'url': ''})
my_dboard['settings']['links'].append({'title': 'Link to Python Website', 'url': ''})

Change Header Color

Change the color of the header at the top of the dashboard.

In [21]:
my_dboard['settings']['headerBackgroundColor'] = '#D232C8'

Upload Dashboard

To upload your dashboard to your Plotly cloud account use py.dashboard_ops.upload().

In [22]:
import plotly.plotly as py
py.dashboard_ops.upload(my_dboard, 'My First Dashboard with Python')

IPython terminal

Retrieve Dashboard

You can also retrieve any of your dashboards from Plotly. To see what dashboards you have in the Plotly cloud, run py.dashboard_ops.get_dashboard_names() to get a list of the dashboards you have in your files. To grab a specific dashboard, simply input its name into py.dashboard_ops.get_dashboard() to create a Dashboard().

In [23]:
['My First Dashboard with Python']
In [24]:
recent_dboard = py.dashboard_ops.get_dashboard('My First Dashboard with Python')


In [25]:
Help on class dashboard_ops in module plotly.plotly.plotly:

class dashboard_ops
 |  Interface to Plotly's Dashboards API.
 |  Plotly Dashboards are JSON blobs. They are made up by a bunch of
 |  containers which contain either empty boxes or boxes with file urls.
 |  For more info on Dashboard objects themselves, run
 |  `help(plotly.dashboard_objs)`.
 |  Example 1: Upload Simple Dashboard
 |  ```
 |  import plotly.plotly as py
 |  import plotly.dashboard_objs as dashboard
 |  box_1 = {
 |      'type': 'box',
 |      'boxType': 'plot',
 |      'fileId': 'username:123',
 |      'title': 'box 1'
 |  }
 |  box_2 = {
 |      'type': 'box',
 |      'boxType': 'plot',
 |      'fileId': 'username:456',
 |      'title': 'box 2'
 |  }
 |  my_dboard = dashboard.Dashboard()
 |  my_dboard.insert(box_1)
 |  # my_dboard.get_preview()
 |  my_dboard.insert(box_2, 'above', 1)
 |  # my_dboard.get_preview()
 |  py.dashboard_ops.upload(my_dboard)
 |  ```
 |  Example 2: Retreive Dashboard from Plotly
 |  ```
 |  # works if you have at least one dashboard in your files
 |  import plotly.plotly as py
 |  import plotly.dashboard_objs as dashboard
 |  dboard_names = get_dashboard_names()
 |  first_dboard = get_dashboard(dboard_names[0])
 |  first_dboard.get_preview()
 |  ```
 |  Class methods defined here:
 |  get_dashboard(cls, dashboard_name) from __builtin__.classobj
 |      Returns a Dashboard object from a dashboard name.
 |  get_dashboard_names(cls) from __builtin__.classobj
 |      Return list of all active dashboard names from users' account.
 |  upload(cls, dashboard, filename, sharing='public', auto_open=True) from __builtin__.classobj
 |      BETA function for uploading/overwriting dashboards to Plotly.
 |      :param (dict) dashboard: the JSON dashboard to be uploaded. Use
 |          plotly.dashboard_objs.dashboard_objs to create a Dashboard
 |          object.
 |      :param (str) filename: the name of the dashboard to be saved in
 |          your Plotly account. Will overwrite a dashboard 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 dashboard will be viewable by
 |          all other users. If 'private' only you can see your dashboard.
 |          If 'secret', the url will be returned with a sharekey appended
 |          to the url. Anyone with the url may view the dashboard.
 |      :param (bool) auto_open: automatically opens the dashboard in the
 |          browser.

Still need help?
Contact Us

For guaranteed 24 hour response turnarounds, upgrade to a Developer Support Plan.