Show Sidebar Hide Sidebar

Getting Started with Plotly for Python

Installation and Initialization Steps for Using Plotly in Python.

Installation¶

To install Plotly'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 plotly
or
$ sudo pip install plotly

Plotly's Python package is updated frequently! To upgrade, run:

$ pip install plotly --upgrade

Initialization for Online Plotting¶

Plotly provides a web-service for hosting graphs! Create a free account to get started. Graphs are saved inside your online Plotly account and you control the privacy. Public hosting is free, for private hosting, check out our paid plans.

After installing the Plotly package, you're ready to fire up python:

$ python

and set your credentials:

In [10]:
import plotly 
plotly.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 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.

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 Plotly configuration:

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

For more examples on privacy settings please visit Python privacy documentation

Special Instructions for Plotly On-Premise Users¶

Your API key for account on the public cloud will be different than the API key in Plotly On-Premise. Visit https://plotly.your-company.com/settings/api/ to find your Plotly On-Premise API key. Remember to replace "your-company.com" with the URL of your Plotly On-Premise server. If your company has a Plotly On-Premise 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 [9]:
import plotly 
plotly.tools.set_config_file(plotly_domain='https://plotly.your-company.com',
                             plotly_streaming_domain='stream-plotly.your-company.com')

Make sure to replace "your-company.com" with the URL of your Plotly On-Premise 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 plotly 
plotly.tools.set_config_file(plotly_domain='https://plotly.your-company.com',
                             plotly_streaming_domain='stream-plotly.your-company.com', 
                             world_readable=False,
                             sharing='private')

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 [3]:
import plotly.plotly as py
from plotly.graph_objs import *

trace0 = Scatter(
    x=[1, 2, 3, 4],
    y=[10, 15, 13, 17]
)
trace1 = Scatter(
    x=[1, 2, 3, 4],
    y=[16, 5, 11, 9]
)
data = Data([trace0, trace1])

py.plot(data, filename = 'basic-line')
Out[3]:
u'https://plot.ly/~PythonPlotBot/27'

Checkout the docstrings for more information:

In [4]:
import plotly.plotly as py
help(py.plot)
Help on function plot in module plotly.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 agruments:
    filename (string) -- the name that will be associated with this figure
    fileopt ('new' | 'overwrite' | 'extend' | 'append') -- 'new' creates a
        'new': create a new, unique url for this plot
        'overwrite': overwrite the file associated with `filename` with this
        'extend': add additional numbers (data) to existing traces
        'append': add additional traces to existing data lists
    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 [5]:
import plotly.plotly as py
from plotly.graph_objs import *

trace0 = Scatter(
    x=[1, 2, 3, 4],
    y=[10, 15, 13, 17]
)
trace1 = Scatter(
    x=[1, 2, 3, 4],
    y=[16, 5, 11, 9]
)
data = Data([trace0, trace1])

py.iplot(data, filename = 'basic-line')
Out[5]:

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

In [6]:
import plotly.plotly as py
help(py.iplot)
Help on function iplot in module plotly.plotly.plotly:

iplot(figure_or_data, **plot_options)
    Create a unique url for this plot in Plotly and open in IPython.
    
    plot_options keyword agruments:
    filename (string) -- the name that will be associated with this figure
    fileopt ('new' | 'overwrite' | 'extend' | 'append')
        - 'new': create a new, unique url for this plot
        - 'overwrite': overwrite the file associated with `filename` with this
        - 'extend': add additional numbers (data) to existing traces
        - 'append': add additional traces to existing data lists
    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 Offline allows you to create graphs offline and save them locally. There are also two methods for plotting offline: plotly.offline.plot() and plotly.offline.iplot().

  • Use plotly.offline.plot() to create and standalone HTML that is saved locally and opened inside your web browser.
  • Use plotly.offline.iplot() when working offline in a Jupyter Notebook to display the plot in the notebook.

Check your Plotly version, version 1.9.4+ is needed for offline plotting:

In [7]:
import plotly
plotly.__version__
Out[7]:
'2.0.2'

Copy and paste one of the following examples to create your first offline Plotly graph using the Plotly Python library:

In [8]:
import plotly
from plotly.graph_objs import Scatter, Layout

plotly.offline.plot({
    "data": [Scatter(x=[1, 2, 3, 4], y=[4, 3, 2, 1])],
    "layout": Layout(title="hello world")
})
Out[8]:
'file:///Users/Chelsea/Repos/documentation/_posts/python/getting-started/temp-plot.html'

Learn more by calling help():

In [9]:
import plotly
help(plotly.offline.plot)
Help on function plot in module plotly.offline.offline:

plot(figure_or_data, show_link=True, link_text='Export to plot.ly', validate=True, output_type='file', include_plotlyjs=True, filename='temp-plot.html', auto_open=True, image=None, image_filename='plot_image', image_width=800, image_height=600)
    Create a plotly graph locally as an HTML document or string.
    
    Example:
    ```
    from plotly.offline import plot
    import plotly.graph_objs as go
    
    plot([go.Scatter(x=[1, 2, 3], y=[3, 2, 6])], filename='my-graph.html')
    # We can also download an image of the plot by setting the image parameter
    # to the image format we want
    plot([go.Scatter(x=[1, 2, 3], y=[3, 2, 6])], filename='my-graph.html'
         image='jpeg')
    ```
    More examples below.
    
    figure_or_data -- a plotly.graph_objs.Figure or plotly.graph_objs.Data or
                      dict or list that describes a Plotly graph.
                      See https://plot.ly/python/ for examples of
                      graph descriptions.
    
    Keyword arguments:
    show_link (default=True) -- display a link in the bottom-right corner of
        of the chart that will export the chart to Plotly Cloud or
        Plotly Enterprise
    link_text (default='Export to plot.ly') -- the text of export link
    validate (default=True) -- validate that all of the keys in the figure
        are valid? omit if your version of plotly.js has become outdated
        with your version of graph_reference.json or if you need to include
        extra, unnecessary keys in your figure.
    output_type ('file' | 'div' - default 'file') -- if 'file', then
        the graph is saved as a standalone HTML file and `plot`
        returns None.
        If 'div', then `plot` returns a string that just contains the
        HTML <div> that contains the graph and the script to generate the
        graph.
        Use 'file' if you want to save and view a single graph at a time
        in a standalone HTML file.
        Use 'div' if you are embedding these graphs in an HTML file with
        other graphs or HTML markup, like a HTML report or an website.
    include_plotlyjs (default=True) -- If True, include the plotly.js
        source code in the output file or string.
        Set as False if your HTML file already contains a copy of the plotly.js
        library.
    filename (default='temp-plot.html') -- The local filename to save the
        outputted chart to. If the filename already exists, it will be
        overwritten. This argument only applies if `output_type` is 'file'.
    auto_open (default=True) -- If True, open the saved file in a
        web browser after saving.
        This argument only applies if `output_type` is 'file'.
    image (default=None |'png' |'jpeg' |'svg' |'webp') -- This parameter sets
        the format of the image to be downloaded, if we choose to download an
        image. This parameter has a default value of None indicating that no
        image should be downloaded. Please note: for higher resolution images
        and more export options, consider making requests to our image servers.
        Type: `help(py.image)` for more details.
    image_filename (default='plot_image') -- Sets the name of the file your
        image will be saved to. The extension should not be included.
    image_height (default=600) -- Specifies the height of the image in `px`.
    image_width (default=800) -- Specifies the width of the image in `px`.

When using plotly.offline.iplot to plot offline in Jupyter Notebooks, there is an additional initialization step of running: plotly.offline.init_notebook_mode() at the start of each notebook session.
See the example below:

In [10]:
import plotly
from plotly.graph_objs import Scatter, Layout

plotly.offline.init_notebook_mode(connected=True)

plotly.offline.iplot({
    "data": [Scatter(x=[1, 2, 3, 4], y=[4, 3, 2, 1])],
    "layout": Layout(title="hello world")
})
In [11]:
import plotly
help(plotly.offline.iplot)
Help on function iplot in module plotly.offline.offline:

iplot(figure_or_data, show_link=True, link_text='Export to plot.ly', validate=True, image=None, filename='plot_image', image_width=800, image_height=600)
    Draw plotly graphs inside an IPython or Jupyter notebook without
    connecting to an external server.
    To save the chart to Plotly Cloud or Plotly Enterprise, use
    `plotly.plotly.iplot`.
    To embed an image of the chart, use `plotly.image.ishow`.
    
    figure_or_data -- a plotly.graph_objs.Figure or plotly.graph_objs.Data or
                      dict or list that describes a Plotly graph.
                      See https://plot.ly/python/ for examples of
                      graph descriptions.
    
    Keyword arguments:
    show_link (default=True) -- display a link in the bottom-right corner of
                                of the chart that will export the chart to
                                Plotly Cloud or Plotly Enterprise
    link_text (default='Export to plot.ly') -- the text of export link
    validate (default=True) -- validate that all of the keys in the figure
                               are valid? omit if your version of plotly.js
                               has become outdated with your version of
                               graph_reference.json or if you need to include
                               extra, unnecessary keys in your figure.
    image (default=None |'png' |'jpeg' |'svg' |'webp') -- This parameter sets
        the format of the image to be downloaded, if we choose to download an
        image. This parameter has a default value of None indicating that no
        image should be downloaded. Please note: for higher resolution images
        and more export options, consider making requests to our image servers.
        Type: `help(py.image)` for more details.
    filename (default='plot') -- Sets the name of the file your image
        will be saved to. The extension should not be included.
    image_height (default=600) -- Specifies the height of the image in `px`.
    image_width (default=800) -- Specifies the width of the image in `px`.
    
    Example:
    ```
    from plotly.offline import init_notebook_mode, iplot
    init_notebook_mode()
    iplot([{'x': [1, 2, 3], 'y': [5, 2, 7]}])
    # We can also download an image of the plot by setting the image to the
    format you want. e.g. `image='png'`
    iplot([{'x': [1, 2, 3], 'y': [5, 2, 7]}], image='png')
    ```

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

MORE EXAMPLES¶

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

Still need help?
Contact Us

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