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 dashboard API is available in version 2.0.5.+
Run pip install plotly --upgrade to update your Plotly version.

In [1]:
import plotly
plotly.__version__
Out[1]:
'2.0.6'

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 https://plot.ly/dashboard/create/. Dashboards are stored in your Plotly account: https://plot.ly/organize

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()
my_dboard.get_preview()
Out[2]:

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),
    mode='markers',
    marker=dict(
        size='16',
        color = np.random.randn(500),
        colorscale=colorscale,
        showscale=True
    )
)
data = [trace1]
url_1 = py.plot(data, filename='scatter-for-dashboard', auto_open=False)
py.iplot(data, filename='scatter-for-dashboard')
Out[3]:

Create a plot with a secret key:

In [4]:
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_2 = py.plot(data, filename='box-plots-for-dashboard', sharing='secret', auto_open=False)
py.iplot(data, filename='box-plots-for-dashboard')
Out[4]:
In [5]:
url_2
Out[5]:
u'https://plot.ly/~PlotBot/1342?share_key=uVoeGB1i8Xf4fk0b57sT2l'

Add a Box¶

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

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 [6]:
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('/', ':')
    else:
        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)

box_a = {
    'type': 'box',
    'boxType': 'plot',
    'fileId': fileId_1,
    'title': 'scatter-for-dashboard'
}

text_for_box = """ 
## Distributions: 


#### Scatter Plot
1. Ranging 0 - 500
2. Even distribution

#### Box Plot
1. Similar Range
2. Outliers present in trace 1 and trace 3

You can view more markdown tips [here](https://daringfireball.net/projects/markdown/syntax).
"""

box_b = {
    'type': 'box',
    'boxType': 'text',
    'text': text_for_box,
    'title': 'Markdown Options for Text Box'
}

box_c = {
    'type': 'box',
    'boxType': 'plot',
    'fileId': fileId_2,
    'title': 'box-for-dashboard',
    'shareKey': sharekey_from_url(url_2)
}

my_dboard.insert(box_a)

IPython terminal

In [8]:
my_dboard.insert(box_b, 'above', 1)

IPython terminal

In [9]:
my_dboard.insert(box_c, '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 essentially lookup keys that 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 specifies the plot, webpage or text that it contains. 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 dict of the box will be returned:

In [10]:
my_dboard.get_box(1)
Out[10]:
{'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 [11]:
my_dboard.get_box(1)['title'] = 'a new title'
my_dboard.get_box(1)
Out[11]:
{'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 [12]:
my_dboard.get_box(3)['title']
Out[12]:
'box-for-dashboard'
In [13]:
my_dboard.swap(2, 3)
my_dboard.get_box(3)['title']
Out[13]:
'Markdown Options for Text Box'

Remove Box¶

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

In [14]:
my_dboard.insert(box_a, 'below', 2)

IPython terminal

In [15]:
my_dboard.remove(2)

IPython terminal

Add Title¶

Set the title of your dashboard.

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

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

In [17]:
my_dboard['settings']['logoUrl'] = 'https://images.plot.ly/language-icons/api-home/python-logo.png'

Add some links to the header of the dashboard.

In [18]:
my_dboard['settings']['links'] = []
my_dboard['settings']['links'].append({'title': 'Link to Plotly', 'url': 'https://plot.ly/'})
my_dboard['settings']['links'].append({'title': 'Link to Python Website', 'url': 'https://www.python.org/'})

Change Color Settings¶

In [19]:
my_dboard['settings']['foregroundColor'] = '#000000'
my_dboard['settings']['backgroundColor'] = '#adcaea'
my_dboard['settings']['headerForegroundColor'] = '#ffffff'
my_dboard['settings']['headerBackgroundColor'] = '#D232C8'
my_dboard['settings']['boxBackgroundColor'] = '#ffffff'
my_dboard['settings']['boxBorderColor'] = '#000000'
my_dboard['settings']['boxHeaderBackgroundColor'] = '#ffffff'

Update Sizing¶

COMING SOON: A programatic way to change the sizes of the boxes in a dashboard using the Dashboard API. Right now there is no native way to adjust the sizes of the dashboard boxes. A current issue with stacking boxes in a dashhboard layout is that each added box gets incrementally half as big as the one before it after inserting into the dashboard.

In [20]:
stacked_dboard = dashboard.Dashboard()
text_box = {
    'type': 'box',
    'boxType': 'text',
    'text': 'empty space' 
}
for _ in range(5):
    stacked_dboard.insert(text_box, 'below', 1)

If a dashboard looks like the one above with small boxes, it may be difficult to resize in the online creator. To avoid this issue, resize the dashboard:

In [21]:
stacked_dboard['layout']['size'] = 3000

Upload Dashboard¶

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

In [22]:
my_dboard['layout']['first']['first']['first']['text'] = text_for_box
In [23]:
import plotly.plotly as py
py.dashboard_ops.upload(my_dboard, 'My First Dashboard with Python')
Out[23]:
u'https://plot.ly/~PlotBot/1327/my-first-dashboard-with-python/'

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 [24]:
py.dashboard_ops.get_dashboard_names()
Out[24]:
['My First Dashboard with Python']
In [25]:
recent_dboard = py.dashboard_ops.get_dashboard('My First Dashboard with Python')

Reference¶

In [26]:
help(py.dashboard_ops)
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.