Getting Started with Chart Studio in Python

Installation and Initialization Steps for Using Chart Studio in Python.


New to Plotly?

Plotly is a free and open-source graphing library for Python. We recommend you read our Getting Started guide for the latest installation or upgrade instructions, then move on to our Plotly Fundamentals tutorials or dive straight in to some Basic Charts tutorials.

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='lr1c37zw')

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_api_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://plotly.com/python/privacy/

In python, enter:

In [4]:
import chart_studio
chart_studio.tools.set_config_file(
plotly_domain='https://plotly.your-company.com',
plotly_api_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://plotly.com/~PythonPlotBot/27/'

Checkout the docstrings for more information:

In [6]:
import chart_studio.plotly as py
(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

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]:
impoimport 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  tag.  If False, produce a string containing
    a single 
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!

In [ ]: