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.
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.
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.
Plot can be set to three different type of privacies: public, private or secret.
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:
import plotly
plotly.tools.set_config_file(world_readable=False,
sharing='private')
For more examples on privacy settings please visit Python privacy documentation
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.
import plotly
plotly.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://plotly.com/python/privacy/
import plotly
plotly.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')
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
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
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.
py.plot()
to return the unique url and optionally open the url.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:
import plotly.plotly as py
import plotly.graph_objs 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)
'https://plotly.com/~tobin/22'
Checkout the docstrings for more information:
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 arguments: 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
import plotly.plotly as py
import plotly.graph_objs 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')
See more examples in our IPython notebook documentation or check out the py.iplot()
docstring for more information.
import plotly.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 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.
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()
.
plotly.offline.plot()
to create and standalone HTML that is saved locally and opened inside your web browser.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:
import plotly
plotly.__version__
'3.9.0'
Copy and paste one of the following examples to create your first offline Plotly graph using the Plotly Python library:
import plotly
import plotly.graph_objs as go
plotly.offline.plot({
"data": [go.Scatter(x=[1, 2, 3, 4], y=[4, 3, 2, 1])],
"layout": go.Layout(title="hello world")
}, auto_open=True)
'temp-plot.html'
Learn more by calling help()
:
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, config=None, include_mathjax=False) 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://plotly.com/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 Chart Studio Cloud or Chart Studio 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 (True | False | 'cdn' | 'directory' | path - default=True) Specifies how the plotly.js library is included in the output html file or 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 output_type='file' 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 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. If False, no script tag referencing plotly.js is included. This is useful when output_type='div' and the resulting div string will be placed inside an HTML document that already loads plotly.js. This option is not advised when output_type='file' as it will result in a non-functional html file. 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`. config (default=None) -- Plot view options dictionary. Keyword arguments `show_link` and `link_text` set the associated options in this dictionary if it doesn't contain them already. include_mathjax (False | 'cdn' | path - default=False) -- Specifies how the MathJax.js library is included in the output html file or 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. HTML files generated with this option will not be able to display LaTeX typesetting. If 'cdn', a script tag that references a MathJax CDN location will be included in the output. HTML files generated with this option will be able to display LaTeX typesetting as long as they have internet access. 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.
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:
import plotly
import plotly.graph_objs as go
plotly.offline.init_notebook_mode(connected=True)
plotly.offline.iplot({
"data": [go.Scatter(x=[1, 2, 3, 4], y=[4, 3, 2, 1])],
"layout": go.Layout(title="hello world")
})
import plotly
help(plotly.offline.iplot)
Help on function iplot in module plotly.offline.offline: iplot(figure_or_data, show_link=False, link_text='Export to plot.ly', validate=True, image=None, filename='plot_image', image_width=800, image_height=600, config=None, auto_play=True, animation_opts=None) Draw plotly graphs inside an IPython or Jupyter notebook figure_or_data -- a plotly.graph_objs.Figure or plotly.graph_objs.Data or dict or list that describes a Plotly graph. See https://plotly.com/python/ for examples of graph descriptions. Keyword arguments: show_link (default=False) -- 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 using plotly.io.write_image. See https://plotly.com/python/static-image-export/ 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`. config (default=None) -- Plot view options dictionary. Keyword arguments `show_link` and `link_text` set the associated options in this dictionary if it doesn't contain them already. auto_play (default=True) -- Whether to automatically start the animation sequence if the figure contains frames. Has no effect if the figure does not contain frames. animation_opts (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. 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') ``` animation_opts Example: ``` from plotly.offline import iplot figure = {'data': [{'x': [0, 1], 'y': [0, 1]}], 'layout': {'xaxis': {'range': [0, 5], 'autorange': False}, 'yaxis': {'range': [0, 5], 'autorange': False}, 'title': 'Start Title'}, 'frames': [{'data': [{'x': [1, 2], 'y': [1, 2]}]}, {'data': [{'x': [1, 4], 'y': [1, 4]}]}, {'data': [{'x': [3, 4], 'y': [3, 4]}], 'layout': {'title': 'End Title'}}]} iplot(figure,animation_opts="{frame: {duration: 1}}") ```
For more examples on plotting offline with Plotly in python please visit our offline documentation.
To use Plotly with Pandas first $ pip install pandas
and then import pandas in your code like in the example below.
import plotly.plotly as py
import plotly.graph_objs as go
import pandas as pd
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/gapminder2007.csv')
fig = {
'data': [
{
'x': df.gdpPercap,
'y': df.lifeExp,
'text': df.country,
'mode': 'markers',
'name': '2007'},
],
'layout': {
'xaxis': {'title': 'GDP per Capita', 'type': 'log'},
'yaxis': {'title': "Life Expectancy"}
}
}
py.iplot(fig, filename='pandas-multiple-scatter')
Check out more examples and tutorials for using Plotly in python here!
from IPython.display import display, HTML
display(HTML('<link href="//fonts.googleapis.com/css?family=Open+Sans:600,400,300,200|Inconsolata|Ubuntu+Mono:400,700" rel="stylesheet" type="text/css" />'))
display(HTML('<link rel="stylesheet" type="text/css" href="http://help.plot.ly/documentation/all_static/css/ipython-notebook-custom.css">'))
#!pip install git+https://github.com/plotly/publisher.git --upgrade
import publisher
publisher.publish(
'getting-started.ipynb', 'python/getting-started/', 'Getting Started Plotly for Python',
'Installation and Initialization Steps for Using Plotly in Python.',
title = 'Getting Started with Plotly for Python | plotly',
name = 'Getting Started with Plotly for Python', display_as='chart_studio'
language='python', layout='user-guide', has_thumbnail='true', thumbnail='thumbnail/bubble.jpg',
ipynb= '~notebook_demo/123/installation', uses_plotly_offline=True)