Fork on GitHub

Plotly Python API

< Back to Main API Page

Interactive, publication-quality plots in your web browser

Quickstart

You can install plotly with pip. In your terminal, enter:
$ pip install plotly
If that didn't work, try it with sudo:
$ sudo pip install plotly
You're good to go. Fire up Python.
>>> import plotly
Make sure that you have the latest version (to upgrade, do $ pip install plotly --upgrade):
>>> print plotly.__version__
0.5.8
Enter your plotly username and API key: Sign-in here, sign-up here, and view your API key here.
py = plotly.plotly("your_plotly_username", "your_plotly_api_key")

Let's make one of our favorite graphs: the Hans Rosling bubble chart

Load up the data. You can just copy 'n paste this block, all we're doing is just downloading and loading this CSV:

https://gist.github.com/chriddyp/8818473/raw/d8c73ff66a190a84eb8c6c19df4d8865673234ca/2007gapminder.csv

import urllib2, StringIO, csv

url = 'https://gist.github.com/chriddyp/8818473/raw/d8c73ff66a190a84eb8c6c19df4d8865673234ca/2007gapminder.csv'
response = urllib2.urlopen(url).read()
output = StringIO.StringIO(response)
cr = csv.reader(output)
def tryFloat(d):
    try:
        return float(d)
    except ValueError:
        return d

data = [[tryFloat(dij) for dij in di] for di in cr]
Let's take a look at the first few rows:
>>> for row in data[0:10]:
...     print row
['Country', 'Population', 'Continent', 'lifeExp', 'gdpPercap']
['Afghanistan', 31889923.0, 'Asia', 43.828, 974.5803384]
['Albania', 3600523.0, 'Europe', 76.423, 5937.029526]
['Algeria', 33333216.0, 'Africa', 72.301, 6223.367465]
['Angola', 12420476.0, 'Africa', 42.731, 4797.231267]
['Argentina', 40301927.0, 'Americas', 75.32, 12779.37964]
['Australia', 20434176.0, 'Oceania', 81.235, 34435.36744]
['Austria', 8199783.0, 'Europe', 79.829, 36126.4927]
['Bahrain', 708573.0, 'Asia', 75.635, 29796.04834]
['Bangladesh', 150448339.0, 'Asia', 64.062, 1391.253792]
Plotly graphs are made by building an array of dictionaries, where each dictionary describes a trace, or a series, in the plot. In this case, each trace will be a different continent. In this example, the dicts will have x, y, text, and marker size data.
import math
graph_data = [] # the data structure that will describe our plotly graph
for continent in ['Asia', 'Europe', 'Africa', 'Americas', 'Oceania']:
    '''
        "x" data is GDP Per Capita
        "y" data is Life Expectancy
        "text" data is the Country Name
        and we scale the "marker" size
         to each country's population
    '''
    graph_data.append(
    {
        'name': continent, # the "name" of this series is the Continent
        'x': [row[4] for row in data if row[2] == continent],
        'y': [row[3] for row in data if row[2] == continent],
        'text': [row[0] for row in data if row[2] == continent],

        'type': 'scatter',
        'mode': 'markers',

        'marker': { # specify the style of the individual scatter points
            'size': [math.sqrt(row[1])/1.e3 for row in data if row[2] == continent],
            'sizemode': 'area',
            'sizeref': 0.05,
            'opacity': 0.55
        }
    })
The rest of the graph, like the axes, title, and legend, is described by a layout dict
layout = {
    'xaxis': {'title': 'GDP Per Capita'},
    'yaxis': {'title': 'Life Expectancy'},
    'title': 'Hans Rosling Bubble Chart<br>2007'
}

Now, let's plot it. Giddyup!

>>> py.plot(graph_data, layout=layout,
         filename='My first plotly graph', fileopt='overwrite',
         world_readable=True, width=1000, height=650)
{
    "url": "https://plot.ly/~IPython.Demo/1085",
    "filename": "My first plotly graph",
    "error": "",
    "warning": "",
    "message": ""
}
The plotly graph will automatically open in your browser. py.plot saves the graph in your plotly account and returns a unique permanent URL where you can view and share your graph. We'll embed the graph here:

Plotly graphs are interactive.

Hover over the points to view the text, click-and-drag to zoom, shift-click-and-drag to pan.

Since your graph is online

You can can share it with that unique url, or embed your interactive graph in a web page.

You can also edit the graph in the plotly web-app

I edited the graph we just made inside the plotly web-app. It's a bit more minimal and the x-axis is logarithmic. All of the options available to customize your graph in the web-app are exposed through the API. Check out my new version here: https://plot.ly/~ChrisP/21. Here's an embedded version:

In plotly, the data and graph are always together, you can view the underlying data in every plotly graph.

The graph that we just made can be viewed here: https://plot.ly/~ChrisP/21 and that graph's data lives here: https://plot.ly/~ChrisP/21.

Usage, Your Data Rights, and Private Graphs

When you make a graph on plotly, you retain the rights to your content (see our terms here). You also control whether your graphs are public or private. Public plotting is free; for a lot of private use, you can get a Premium or Organizational plan (see https://plot.ly/plans). By default, anyone can view the graphs at the unique URL. To make the graphs private, so that only you can see them when your logged in, set world_readable to False. Here is a public graph:
import math
t = [i*2*math.pi/100 for i in range(100)]
x = [16.*math.sin(ti)**3 for ti in t]
y = [13.*math.cos(ti)-5*math.cos(2*ti)-2*math.cos(3*ti)-math.cos(4*ti) for ti in t]
trace0 = {'x': x, 'y': y, 'line': {'color': 'red', 'width': 6}}
axes = {'ticks': '', 'showline': False, 'zeroline': False}
layout = {'xaxis': axes, 'yaxis': axes}
py.iplot([trace0], layout = layout, filename="public hearts", world_readable=True, width=1000, height=650)
And the same graph, but with a private setting:
py.iplot([trace0], layout = layout, filename="private hearts", world_readable=False)

Preventing the graph from opening in your browser

If your plotting from your Python command line, using the method py.plot, your graphs will automatically open for you in your browser. To turn this off, run:
py.ioff() # interactive mode off
and back on again:
py.ion() # interactive mode on

Plotting with NumPy, Datetime, and LaTeX

import numpy as np

boxes = [{'y': np.random.randn(50), 'type': 'box', 'boxpoints': 'all', 'jitter': 0.5, 'pointpos': -1.8} for i in range(10)]

layout = {'title': 'NumPy Boxes',
          'showlegend': False,
          'yaxis': {'zeroline': False, 'ticks': '', 'showline': False},
          'xaxis': {'ticks': '', 'showgrid': False, 'showline': False}}

py.iplot(boxes, layout = layout, filename='numpy boxes', fileopt='overwrite', width=1000, height=650)
import datetime
import random

N = 500
now = datetime.datetime.now()
x = [ datetime.timedelta(hours=i) + now for i in range(N) ]
y = [ math.sin(i*5*math.pi/N)*math.exp(-2.*i/N)+random.random()/3. for i in range(N) ]

layout = {'title': 'Datetime Decay',
        'annotations': [{
            'text':'The date-formatted x-axis will increase it\'s time-resolution when you zoom.'+\
                    '<br>Click-and-drag your mouse on the plot to see how it responds!',
            'xref': 'paper', 'yref': 'paper', 'showarrow': False, 'x':0, 'y': 0}]}

py.iplot([{'x':x, 'y':y, 'mode':'markers'}], layout=layout, filename='Datetime Decay', fileopt='overwrite', width=1000, height=650)
import numpy as np
import math
x = np.linspace(-7, 7, 100)
y0 = x
y1 = y0 - x**3/math.factorial(3)
y2 = y1 + x**5/math.factorial(5)
y3 = y2 - x**7/math.factorial(7)
y4 = y3 + x**9/math.factorial(9)
y5 = np.sin(x)

linestyle = {'line': {'color': '#7FDBFF', 'dash': 'dot'}}

data = [{'x': x, 'y': y0},
        {'x': x, 'y': y1},
        {'x': x, 'y': y2},
        {'x': x, 'y': y3},
        {'x': x, 'y': y4},
        {'x': x, 'y': y5, 'line': {'color': '#0074D9'}}]

layout = {'yaxis': {'range': [-4.5, 4.5], 'zeroline':False, 'ticks':'','showline':False},
          'xaxis': {'showgrid':False,'showline':False, 'zeroline':False, 'ticks':''},
          'showlegend': False,
          'title': '$\\sin(x)=\sum\limits_{k=0}^{\infty}\dfrac{(-1)^k x^{1+2k}}{(1+2k)!}$'}

py.iplot(data, layout=layout, style=linestyle, traces=[0,1,2,3,4], filename='LaTeX', fileopt='overwrite', width=1000, height=650)

Flexible Axes and Subplots

Plotly abstracts subplots and insets as axes, so it's easy to let subplots share axes and interactivity. For example, this graph has two yaxes and two axes. Each column of plots share the same x-axis, and each row of plots share the same y-axis. Try zooming in any section of the plot (click-and-drag to zoom)!
import numpy as np

x0 = np.concatenate([np.random.randn(100), np.random.randn(100)+6])
y0 = np.random.rayleigh(size=200)

histogram2d = { "x": x0, "y": y0, "type": "histogram2d"}

histogramy1 = {"y": y0, "type": "histogramy", "xaxis": "x2", "yaxis": "y", "bardir": "h",
                "marker":{"color":"rgb(31, 119, 180)"}}
histogramy2 = {"x":x0, "type": "histogramx", "xaxis": "x", "yaxis": "y2",
                "marker":{"color":"rgb(31, 119, 180)"}}

layout = {
    "xaxis":{ "domain":[0,0.8], "showgrid":False, "showline":False, "zeroline":False },
    "yaxis":{ "domain":[0,0.8], "showgrid":False, "showline":False, "zeroline":False },
    "xaxis2":{ "domain":[0.82,1.0], "showgrid":False, "showline":False, "zeroline":False },
    "yaxis2":{ "domain":[0.82,1.0], "showgrid":False, "showline":False, "zeroline":False },
     "showlegend":False,
}
py.iplot([histogram2d, histogramy1, histogramy2],layout=layout, filename='histogram subplots', fileopt='overwrite', width=1000, height=650)

Installation

Option 1: PIP

From inside your Terminal, run

$ pip install plotly
[...]
Successfully installed plotly

Option 2: Easy Install

From inside your Terminal, run

$ easy_install plotly
[...]
Successfully installed plotly

Option 3: Tarball

Download and uncompress the latest Python API ,
In the downloaded folder, run the setup script inside your terminal:

$ python setup.py install
# you made need to 'sudo'
$ sudo python setup.py install

Initialization

To get started, import plotly and initialize a plotly object with your username and api key.

import plotly
py = plotly.plotly('username_or_email', 'api_key')

You will interact with your plotly graphs through 3 methods:

py.plot py.style py.layout

Authentication

New User - Sign Up

You can sign up on with Plotly's online GUI or through the API:

import plotly
username='anna.lyst'
email='anna.lyst@plot.ly'
response = plotly.signup(username, email)
api_key = response['api_key']
tmp_pw = response['tmp_pw']

Existing User - Generate API Key

Existing users display or reset their API key here. You will be prompted to log-in if you aren't already.

Display Key
Reset Key

Your key will display here.

Documentation Examples

Search for an example, or explore the links below!

Chart Types

Line and Scatter

Area Plots

Bar Charts

Error Bars

Box Plots

Histograms

Bubble Charts

Heatmaps

Text Charts

Mixed Types

Time Series

Multiple Axes, Insets and Subplots

Multiple Axes

Subplots

Insets

Layout

File Settings

Basic Line Plot

import plotly
py = plotly.plotly('PythonAPI', 'ubpiol2cve')

x0 = [1,2,3,4]; y0 = [10,15,13,17]
x1 = [2,3,4,5]; y1 = [16,5,11,9]
py.plot(x0, y0, x1, y1)
Basic Line Plot

Line with Scatter

import plotly
py = plotly.plotly('PythonAPI', 'ubpiol2cve')

trace0 = {'x': [1,2,3,4],
  'y': [10,15,13,17],
  'type': 'scatter',
  'mode': 'markers'}

trace1 = {'x': [2,3,4,5],
  'y': [16,5,11,9],
  'type': 'scatter',
  'mode': 'lines'}

trace2 = {'x': [1,2,3,4],
  'y': [12,9,15,12],
  'type': 'scatter',
  'mode': 'lines+markers'}

py.plot([trace0, trace1, trace2])
Line with Scatter

Styling Line and Scatter

import plotly
py = plotly.plotly('PythonAPI', 'ubpiol2cve')

x1 = [1,2,3]; y1 = [4,5,6]
x2 = [1,2,3]; y2 = [2,10,12]

# plotly's data dictionaries
trace1 = {'x': x1,
    'y': y1,
    "name":"Experiment",
    "type":"scatter",
    "line":{
        "color":"rgb(3,78,123)",
        "width":6,
        "dash":"dot"
    },
    "marker":{
        "opacity":1.0,
        "symbol":"square",
        "size":12,
        "color":"rgb(54,144,192)",
        "line":{
            "width":3,
            "color":"darkblue"
        }
    }
}

trace2 = {"x":x2,
    "y":y2,
    "name":"Control",
    "type":"scatter",
    "line":{
        "color":"purple",
        "width":4,
        "dash":"dashdot"
    },
    "marker":{
        "opacity":0.9,
        "symbol":"cross",
        "size":16,
        "color":"fuchsia",
        "line":{
            "color":"",
            "width":0
        },
    }
}

py.plot([trace1, trace2])
Styling Line and Scatter

Basic Area Plot

import plotly
py = plotly.plotly('PythonAPI', 'ubpiol2cve')

trace0 = {'x': [1,2,3,4],
  'y': [0, 2, 3, 5],
  'fill': 'tozeroy'} options

trace1 = {'x': [1,2,3,4],
  'y': [3,5,1,7],
  'fill': 'tonexty'}

py.plot([trace0, trace1])
Basic Area Plot

Basic Bar Chart

import plotly
py = plotly.plotly('PythonAPI', 'ubpiol2cve')

x0 = ['giraffes', 'orangutans', 'monkeys']; note
y0 = [20, 14, 23];
data = {'x': x0, 'y': y0,
	'type': 'bar'} options
py.plot([data])
Basic Bar Chart

Grouped Bar Chart

import plotly
py = plotly.plotly('PythonAPI', 'ubpiol2cve')

categories = ['giraffes', 'orangutans', 'monkeys'];
SF = {'name': 'SF Zoo',
	'x': categories,
	'y': [20, 14, 23],
	'type': 'bar'}
LA = {'name': 'LA Zoo',
	'x': categories,
	'y': [12,18,29],
	'type': 'bar'}
layout = {
	'barmode': 'group',options
	'xaxis': {'type': 'category'},
	'categories': categories}
py.plot([LA, SF], layout=layout)
Grouped Bar Chart

Stacked Bar Chart

import plotly
py = plotly.plotly('PythonAPI', 'ubpiol2cve')

[...]	# ... SF and LA data from above
layout = {'barmode': 'stack',   options
	'xaxis': {'type': 'category'},
	'categories': categories}
py.plot([SF, LA], layout=layout)
Stacked Bar Chart

Styling Bar Charts

import plotly
py = plotly.plotly('PythonAPI', 'ubpiol2cve')

categories=['giraffes', 'orangutans', 'monkeys']
SF = {'name': 'SF Zoo',
  'x': categories,
  'y': [20, 14, 23],
  'type': 'bar',
  'marker':{note
    'color': 'orange', options
    'line': {'color': 'grey',  note
      'width': 3}}
  }

LA = {'name': 'LA Zoo',
  'x': categories,
  'y': [12,18,29],
  'type': 'bar',
  'marker': {'color': 'rgb(111, 168, 220)',
    'line': {'color': 'grey',
      'width': 3}}
  }

layout = {
  'title': 'Animal Population',
  'barmode': 'group',options
  'yaxis': {'name': '# of animals (thousands)'},
  'xaxis': {'type': 'category'},
  'categories': categories,
  'bargap': 0.25,note
  'bargroupgap': 0.3,note
  'bardir': 'v'}options

py.plot([LA, SF], layout=layout)
Styling Bar Charts

Basic Error Bars

import plotly
py = plotly.plotly('PythonAPI', 'ubpiol2cve')

data = {'x': [0,1,2],
  'y': [6,10,2],
  'error_y': {'type': 'data',options
	'array': [1, 2, 3],
	'visible': True}}
py.plot([data])
Basic Error Bars

Percentage, Constant or Square Root

import plotly
py = plotly.plotly('PythonAPI', 'ubpiol2cve')

data = {'x': [0,1,2],
  'y': [6,8,4],
  'error_y': {'type': 'percent',options
    'value': 50, note
    'visible': True}}
py.plot([data])
Percentage, Constant or Square Root

Bar Chart with Error Bars

import plotly
py = plotly.plotly('PythonAPI', 'ubpiol2cve')

categories = ['Trial 1', 'Trial 2', 'Trial 3']
control = {'x': categories,
  'y': [3, 6, 4],
  'type': 'bar',
  'marker':{'color': 'rgb(74, 134, 232)'},
  'error_y': {'type': 'data',
    'array': [1, 0.5, 1.5],
    'visible': True,
	'color': 'rgb(67, 67, 67)'}}
exp = {'x': categories,
  'y': [4, 7, 3],
  'type': 'bar',
  'marker':{'color':'rgb(111, 168, 220)'},
  'error_y': {'type': 'data',options
    'array': [0.5, 1, 2], note
	'visible': True,
	'color': 'rgb(67, 67, 67)'}}
layout = {'barmode': 'group'}

py.plot([control, exp], layout=layout)
Bar Chart with Error Bars

Basic Box Plot

import plotly
py = plotly.plotly('PythonAPI', 'ubpiol2cve')

box1 = {'y': [0, 1, 2, 4],
  	'type': 'box'}
box2 = {'y': [1,2,4,5,8],
	'type': 'box'}
py.plot([box1, box2])

Basic Box Plot

Box Plot with Jitter

import plotly
py = plotly.plotly('PythonAPI', 'ubpiol2cve')

from numpy import *
box = {'y': random.randn(50),
  	'type': 'box',
  	'boxpoints': 'all', options
  	'jitter': 0.3,   note
  	'pointpos': -1.8}  note
py.plot([box])

Box Plot with Jitter

Basic Histogram

import plotly
py = plotly.plotly('PythonAPI', 'ubpiol2cve')

from numpy import *
x = random.randn(500) # normally distributed vector
data = {'x': x,
	'type': 'histogramx'}
py.plot([data])

Basic Histogram

Stacked Histogram

import plotly
py = plotly.plotly('PythonAPI', 'ubpiol2cve')

from numpy import *
x0 = random.randn(500)
x1 = random.randn(500)+1
data0 = {'x': x0,
	'type': 'histogramx'}
data1 = {'x': x1,
	'type': 'histogramx'}
layout = {'barmode': 'stack'} options
py.plot([data0, data1], layout=layout)

Stacked Histogram

Overlaid Histogram

import plotly
py = plotly.plotly('PythonAPI', 'ubpiol2cve')

[...] # data0, data1 from the above example
layout = {'barmode': 'overlay'}  options
py.plot([data0, data1], layout=layout)

Overlaid Histogram

Styling Histograms

import plotly
py = plotly.plotly('PythonAPI', 'ubpiol2cve')

from numpy import *
x0 = random.randn(500)
x1 = random.randn(500)+1
data0 = {'x': x0,
  'type': 'histogramx',
  'name': 'control',
  'marker':{note
    'color': 'fuchsia',options
    'opacity': 0.75,
    'line': {'color': 'grey',note
      'width': 0}},
  'autobinx': False,
  'xbins':{
    'start': -3.2,
    'end': 2.8,
    'size': 0.2},
  'histnorm': 'count'options
}
data1 = {'x': x1,
  'name': 'experiment',
  'type': 'histogramx',
  'marker':{
    'color': 'rgb(255, 217, 102)',
    'opacity': 0.75},
  'autobinx': False,
  'xbins':{
    'start': -1.8,
    'end': 4.2,
    'size': 0.2}}

layout = {'barmode': 'overlay',options
  'bargap': 0.25,note
  'bargroupgap': 0.3,note
  'bardir': 'v',options
  'title': 'Sampled Results',
  'xaxis': {'title': 'Value'},
  'yaxis': {'title': 'Count'}}
py.plot([data0, data1], layout=layout)

Styling Histograms

2D Histogram

import plotly
py = plotly.plotly('PythonAPI', 'ubpiol2cve')

from numpy import *
x = random.randn(500)
y = random.randn(500)+1
data = {'x': x, 'y': y,
	'type': 'histogram2d'}
py.plot([data])

2D Histogram

2D Histogram Options

import plotly
py = plotly.plotly('PythonAPI', 'ubpiol2cve')

from numpy import *
x = random.randn(500)
y = random.randn(500)+1
data = {'x': x,
	'y': y,
	'type': 'histogram2d',
	'autobinx': False,
	'xbins': {
		'start': -3,
		'end': 3,
		'size': 0.1
	},
	'autobiny': False,
	'ybins': {
		'start': -2.5,
		'end': 4,
		'size': 0.1
	},
	'scl': [[0,"rgb(12,51,131)"],\
		[0.25,"rgb(10,136,186)"],\
		[0.5,"rgb(242,211,56)"],\
		[0.75,"rgb(242,143,56)"],\
		[1,"rgb(217,30,30)"]],
	'histnorm': 'probability'
}

layout =  {
	'xaxis':{'range':[-2,2]	},
	'yaxis':{'range':[-1,3] },
	'width':520,'height':380,
	'autosize':False
	}

py.plot([data],layout=layout)

2D Histogram Options

Basic Heatmap

import plotly
py = plotly.plotly('PythonAPI', 'ubpiol2cve')

z = [[1., 20., 30 ],\
     [20., 1., 60 ],\
     [30., 60., 1.]]
data = {'z': z,
	'type': 'heatmap'}
py.plot([data])

Basic Heatmap

Labelled Heatmap

import plotly
py = plotly.plotly('PythonAPI', 'ubpiol2cve')

x = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
y = ['Morning', 'Afternoon', 'Evening']
z = [[1., 20., 30, 50, 1],\
     [20., 1., 60, 80, 30 ],\
     [30., 60., 1., -10, 20]]
data = {'x': x,
	'y': y,
	'z': z,
	'type': 'heatmap'}
py.plot([data])

Labelled Heatmap

Bar Chart with Line Plot

import plotly
py = plotly.plotly('PythonAPI', 'ubpiol2cve')

from numpy import *
x0 = linspace(0, 5, 15)
y0 = sin(x0) + random.rand(15)
data0 = {'x': x0,'y': y0,
	'type': 'scatter'}

x1 = [0, 1, 2, 3, 4, 5]
y1 = [1, 0.5, 0.7, -1.2, 0.3, 0.4]
data1 = {'x': x1,'y': y1,
	'type': 'bar'}

py.plot([data0, data1])

Bar Chart with Line Plot

2D Histogram with Scatter Overlay

import plotly
py = plotly.plotly('PythonAPI', 'ubpiol2cve')

from numpy import *

x0 = random.randn(100)/5. + 0.5
y0 = random.randn(100)/5. + 0.5

x1 = random.rayleigh(size=80)/7. + 0.1
y1 = random.rayleigh(size=80)/8. + 1.1

y = concatenate([y0,y1])
x = concatenate([x0,x1])

data0 = {'x': x0, 'y': y0,
  'marker':{'symbol':'circle'},
  'type': 'scatter', 'mode': 'markers'}
data1 = {'x': x1, 'y': y1,
  'marker':{'symbol':'cross'},
  'type': 'scatter', 'mode': 'markers'}

data_hist = {'x': x, 'y': y,
  'type':'histogram2d'}

py.plot([data0,data1,data_hist])

2D Histogram with Scatter Overlay

Legend Visibility

import plotly
py = plotly.plotly('PythonAPI', 'ubpiol2cve')

x = [0,1,2,3,4,5,6,7,8]
y = [0,3,6,4,5,2,3,5,4]
x2 = [0,1,2,3,4,5,6,7,8]
y2 = [0,4,7,8,3,6,3,3,4]

layout = {
  'showlegend': False #Default value when there are more than two traces is 'True'
}

py.plot(x,y,x2,y2,layout=layout)
Legend Visibility

Legend Position Inside

import plotly
py = plotly.plotly('PythonAPI', 'ubpiol2cve')

x = [0,1,2,3,4,5,6,7,8]
y = [0,3,6,4,5,2,3,5,4]
x2 = [0,1,2,3,4,5,6,7,8]
y2 = [0,4,7,8,3,6,3,3,4]

# Position the legend inside the graph by assigning x and y values of <= 1.
# e.g :
# {"x" : 0, "y" : 0} -- Bottom Left
# {"x" : 1, "y" : 0} -- Bottom Right
# {"x" : 1, "y" : 1} -- Top Right
# {"x" : 0, "y" : 1} -- Top Left
# {"x" : .5, "y" : 0} -- Bottom Center
# {"x" : .5, "y" : 1} -- Top Center

legendstyle = {"x" : 1, "y" : 1}

# place legend into layout
layout = {
  'showlegend':True,
  'legend': legendstyle
}

py.plot(x,y,x2,y2,layout=layout)
Legend Position Inside

Legend Position Outside

import plotly
py = plotly.plotly('PythonAPI', 'ubpiol2cve')

x = [0,1,2,3,4,5,6,7,8]
y = [0,3,6,4,5,2,3,5,4]
x2 = [0,1,2,3,4,5,6,7,8]
y2 = [0,4,7,8,3,6,3,3,4]

# Position the legend outside of the graph by assigning one of the x and y values to either 100 or -100.
# e.g :
# {"x" : 100, "y" : 0} -- Outside Right Bottom
# {"x" : 100, "y" : 1} -- Outside Right Top
# {"x" : 100, "y" : .5} -- Outside Right Middle
# {"x" : 0, "y" : -100} -- Under Left
# {"x" : 0.5, "y" : -100} -- Under Center
# {"x" : 1, "y" : -100} -- Under Right


legendstyle = {"x" : 100, "y" : 1}

# place legend into layout
layout = {
  'showlegend':True,
  'legend': legendstyle
}

py.plot(x,y,x2,y2,layout=layout)
Legend Position Outside

Styling the Legend

import plotly
py = plotly.plotly('PythonAPI', 'ubpiol2cve')

x = [0,1,2,3,4,5,6,7,8]
y = [0,3,6,4,5,2,3,5,4]
x2 = [0,1,2,3,4,5,6,7,8]
y2 = [0,4,7,8,3,6,3,3,4]


legendstyle = {
  "x" : 0,
  "y" : 1,
  "bgcolor" : "#E2E2E2",options
  "bordercolor" : "#FFFFFF",options
  "borderwidth" : 2,
  "traceorder" : "normal",options
  "font" : {
    "color" : "#000",options
    "family" : "sans-serif",options
    "size" : 12
    }
}

# place legend into layout
layout = {
  'showlegend':True,note
  'legend': legendstyle
}

py.plot(x,y,x2,y2,layout=layout)
Styling the Legend

Legend Labels

import plotly
py = plotly.plotly('PythonAPI', 'ubpiol2cve')

trace0  = {
    'x': [0,1,2,3],
    'y': [0,2,4,6],
    'name': 'Blue Trace'
    }

trace1 = {
    'x': [0,1,2,3],
    'y': [8,4,2,0],
    'name': 'Orange Trace'
    }

py.plot(trace0,trace1)
Legend Labels

Basic Text Chart

import plotly
py = plotly.plotly('PythonAPI', 'ubpiol2cve')

data = [{
    "x": [0,1,2], "y": [1,1,1],
    "name": "Lines, Markers and Text",
    "text": ["Text A", "Text B", "Text C"], note
    "type": "scatter",
    "mode": "lines+markers+text", options
    "textposition": "top"options
  },
  {
    "x": [0,1,2], "y": [2,2,2],
    "name": "Markers and Text",
    "text": ["Text D", "Text E", "Text F"],
    "type": "scatter",
    "mode": "markers+text",
    "textposition": "bottom"
  },
  {
    "x": [0,1,2], "y": [3,3,3],
    "name": "Lines and Text",
    "text": ["Text G", "Text H", "Text I"],
    "type": "scatter",
    "mode": "lines+text",
    "textposition" : "bottom"
  }]

#hide legend
layout = {
'showlegend':False,
}

py.plot(data, layout=layout)
Basic Text Chart

Styling Text Charts

import plotly
py = plotly.plotly('PythonAPI', 'ubpiol2cve')

data = [{
      "x": [0,1,2], "y": [1,1,1],
      "name": "Lines, Markers and Text",
      "text": ["Text A", "Text B", "Text C"],
      "type": "scatter",
      "mode": "lines+markers+text",
      "textposition": "top right",
      "textfont" : {
        "color": "#1f77b4",options
        "family": "sans serif",options
        "size": 18
      }
    },
    {
      "x": [0,1,2], "y": [2,2,2],
      "name": "Lines and Text",
      "text": ["Text G", "Text H", "Text I"],
      "type": "scatter",
      "mode": "lines+markers+text",
      "textposition" : "bottom",
      "textfont" : {
        "color": "#ff7f0e",options
        "family": "sans serif",options
        "size": 18
      }
    }]

#hide legend
layout = {
  'showlegend':False,
}

py.plot(data, layout=layout)
Styling Text Charts

Axes Booleans

import plotly
py = plotly.plotly('PythonAPI', 'ubpiol2cve')

x = [0,1,2,3,4,5,6,7,8]
y = [8,7,6,5,4,3,2,1,0]
x2 = [0,1,2,3,4,5,6,7,8]
y2 = [0,1,2,3,4,5,6,7,8]

axesstyle = {
      "autotick" : True,
      "showgrid" : False,
      "showline" : False,note
      "showticklabels" : False,
      "zeroline" : False,
      "ticks" : "" options
}

layout = {
    "xaxis" : axesstyle,
    "yaxis" : axesstyle,
    "showlegend" : False
}

py.plot(x,y,x2,y2,layout=layout)
Axes Booleans

Linear and Log Axes

import plotly
py = plotly.plotly('PythonAPI', 'ubpiol2cve')

x = [0,1,2,3,4,5,6,7,8]
y = [8,7,6,5,4,3,2,1,0]
x2 = [0,1,2,3,4,5,6,7,8]
y2 = [0,1,2,3,4,5,6,7,8]


axesstyle = {
    "type" : "log",options
}

layout = {
    "xaxis" : axesstyle,
    "yaxis" : axesstyle,
}


py.plot(x,y,x2,y2,layout=layout)
Linear and Log Axes

Manual Range

import plotly
py = plotly.plotly('PythonAPI', 'ubpiol2cve')

x = [0,1,2,3,4,5,6,7,8]
y = [8,7,6,5,4,3,2,1,0]
x2 = [0,1,2,3,4,5,6,7,8]
y2 = [0,1,2,3,4,5,6,7,8]


axesstyle = {
    "range" : [2,5]options
}

layout = {
    "xaxis" : axesstyle,
    "yaxis" : axesstyle,
}


py.plot(x,y,x2,y2,layout=layout)
Manual Range

Range Mode

import plotly
py = plotly.plotly('PythonAPI', 'ubpiol2cve')

x = [2,4,6]
y = [-3,0,3]


layout = {
    "showlegend" : False,
    "xaxis" : {
        "rangemode" : "tozero"options
    },
    "yaxis" : {
        "rangemode" : "nonnegative"options
    }
}


py.plot(x,y,layout=layout)
Range Mode

Axes Lines

import plotly
py = plotly.plotly('PythonAPI', 'ubpiol2cve')

x = [0,1,2,3,4,5,6,7,8]
y = [8,7,6,5,4,3,2,1,0]
x2 = [0,1,2,3,4,5,6,7,8]
y2 = [0,1,2,3,4,5,6,7,8]


axesstyle = {
    "showline" : True,note
    "mirror" : "ticks",optionsnote
    "linecolor" : "#636363",options
    "linewidth" : 6,

    "showgrid" : True,note
    "gridcolor" : "#bdbdbd",options
    "gridwidth" : 2,

    "zeroline" : True, note
    "zerolinecolor" : "#969696",options
    "zerolinewidth" : 4
}

layout = {
  "xaxis" : axesstyle,
  "yaxis" : axesstyle,
}


py.plot(x,y,x2,y2,layout=layout)
Axes Lines

Axes Ticks

import plotly
py = plotly.plotly('PythonAPI', 'ubpiol2cve')

x = [0,1,2,3,4,5,6,7,8]
y = [8,7,6,5,4,3,2,1,0]
x2 = [0,1,2,3,4,5,6,7,8]
y2 = [0,1,2,3,4,5,6,7,8]

axesstyle = {
      "autotick" : False,
      "tick0" : 0,note
      "dtick" : .25,note
      "ticks" : "outside",options
      "tickcolor" : "#000",options
      "ticklen" : 8,note
      "tickwidth" : 4
}

layout = {
  "xaxis" : axesstyle,
  "yaxis" : axesstyle,
}

py.plot(x,y,x2,y2,layout=layout)
Axes Ticks

Axes Labels

import plotly
py = plotly.plotly('PythonAPI', 'ubpiol2cve')

x = [0,1,2,3,4,5,6,7,8]
y = [8,7,6,5,4,3,2,1,0]
x2 = [0,1,2,3,4,5,6,7,8]
y2 = [0,1,2,3,4,5,6,7,8]

axesstyle = {
      "title" : "AXIS TITLE",

      "titlefont" : {
        "color" : "lightgrey",options
        "family" : "Arial, sans-serif",options
        "size" : 18
      },
      "showticklabels" : True,
      "tickfont" : {
        "color" : "black",options
        "family" : "Old Standard TT, serif",options
        "size" : 14
      },
      "tickangle" : 45,options
      "showexponent" : "All",options
      "exponentformat" : "e",options
}

layout = {
  "xaxis" : axesstyle,
  "yaxis" : axesstyle,
}

py.plot(x,y,x2,y2,layout=layout)
Axes Labels

Reversed Axes

import plotly
py = plotly.plotly('PythonAPI', 'ubpiol2cve')

x = [1,2]
y = [1,2]

layout = {
    "xaxis": {
      "autorange": "reversed"
    }
}

py.plot(x,y,layout=layout)
Reversed Axes

Date Axes

import plotly
py = plotly.plotly('PythonAPI', 'ubpiol2cve')

import datetime
# Plotly understands dates and times in format "YYYY-MM-DD HH:MM:SS" (e.g. "2009-10-04 22:23:00") as well as python datetime objects

x1 = ['2013-10-04 22:23:00', '2013-11-04 22:23:00', '2013-12-04 22:23:00']
x2 = [datetime.datetime(2013,10,04,22,23,00), datetime.datetime(2013,11,04,22,23,00), datetime.datetime(2013,12,04,22,23,00)]
y1 = [1,3,6]
y2 = [6,3,1]
py.plot(x1,y1,x2,y2)
Date Axes

Simple Double Axes

import plotly
py = plotly.plotly('PythonAPI', 'ubpiol2cve')

data = [
   {
    "x":[1,2,3],
    "y":[40,50,60],
      "name":"yaxis data"
   },
   {
      "x":[2,3,4],
      "y":[4,5,6],
      "yaxis":"y2", # this will reference the yaxis2 object in the layout object
      "name": "yaxis2 data"
   }
];
layout = {
   "yaxis":{
      "title": "yaxis title", # optional
   },
   "yaxis2":{
      "title": "yaxis2 title", # optional
      "titlefont":{
         "color":"rgb(148, 103, 189)"
      },
      "tickfont":{
         "color":"rgb(148, 103, 189)"
      },
      "overlaying":"y",
      "side":"right",
   },
   "title": "Double Y Axis Example",
}
py.plot(data, layout=layout)

Simple Double Axes

Simple Multiple Axes

import plotly
py = plotly.plotly('PythonAPI', 'ubpiol2cve')

# color variable array
c = ['#1f77b4', # muted blue
                '#ff7f0e', # safety orange
                '#2ca02c', # cooked asparagus green
                '#d62728', # brick red
                '#9467bd', # muted purple
                '#8c564b', # chestnut brown
                '#e377c2', # raspberry yogurt pink
                '#7f7f7f', # middle gray
                '#bcbd22', # curry yellow-green
                '#17becf']; #blue-teal

data = [
    {
    "x":[1,2,3],
    "y":[4,5,6],
    "name":"yaxis1 data"
   },
   {
      "x":[2,3,4],
      "y":[40,50,60],
      "name":"yaxis2 data",
      "yaxis":"y2" # this references the "yaxis2" object in layout
   },
   {
      "x":[3,4,5],
      "y":[400,500,600],
      "name":"yaxis3 data",
      "yaxis":"y3"
    },
    {
    "x":[4,5,6],
    "y":[40000,50000,60000],
    "name":"yaxis4 data",
    "yaxis":"y4"
   },
    {
    "x":[5,6,7],
    "y":[400000,500000,600000],
    "name":"yaxis5 data",
    "yaxis":"y5"
   },
    {
    "x":[6,7,8],
    "y":[4000000,5000000,6000000],
    "name":"yaxis6 data",
    "yaxis":"y6"
   },
]
layout = {
    "width":800,
    "xaxis":{
        "domain":[0.3,0.7]
    },
   "yaxis":{
      "title": "yaxis title",
      "titlefont":{
         "color":c[0]
      },
      "tickfont":{
         "color":c[0]
      },
   },
   "yaxis2":{
      "overlaying":"y",
      "side":"left",
      "anchor":"free",
      "position":0.15,

      "title": "yaxis2 title",
      "titlefont":{
         "color":c[1]
      },
      "tickfont":{
         "color":c[1]
      },
   },
   "yaxis3":{
      "overlaying":"y",
      "side":"left",
      "anchor":"free",
      "position":0,

      "title": "yaxis3 title",
      "titlefont":{
         "color":c[2]
      },
      "tickfont":{
         "color":c[2]
      },
   },

   "yaxis4":{
      "overlaying":"y",
      "side":"right",
      "anchor":"x",

      "title": "yaxis4 title",
      "titlefont":{
         "color":c[3]
      },
      "tickfont":{
         "color":c[3]
      },
   },

   "yaxis5":{
      "overlaying":"y",
      "side":"right",
      "anchor":"free",
      "position":0.85,

      "title": "yaxis5 title",
      "titlefont":{
         "color":c[4]
      },
      "tickfont":{
         "color":c[4]
      },
   },

   "yaxis6":{
      "overlaying":"y",
      "side":"right",
      "anchor":"free",
      "position":1.0,

      "title": "yaxis6 title",
      "titlefont":{
         "color":c[5]
      },
      "tickfont":{
         "color":c[5]
      },
    },
    "title": "multiple y-axes example"
}
py.plot(data, layout=layout)
Simple Multiple Axes

Simple Subplot

import plotly
py = plotly.plotly('PythonAPI', 'ubpiol2cve')

data = [
    {
    "x":[1,2,3],
    "y":[4,5,6],
   },
   {
      "x":[20,30,40],
      "y":[50,60,70],
      "xaxis":"x2",
      "yaxis":"y2"
   }
]

layout = {
    "xaxis":{
        "domain":[0,0.45] # i.e. let the first x-axis span the first 45% of the plot width
    },
    "xaxis2":{
        "domain":[0.55,1] # i.e. let the second x-axis span the latter 45% of the plot width
    },
    "yaxis2":{
        "anchor":"x2" # i.e. bind the second y-axis to the start of the second x-axis
    }
}
py.plot(data, layout=layout)
Simple Subplot

Custom Sized Subplot

import plotly
py = plotly.plotly('PythonAPI', 'ubpiol2cve')

data = [
    {
    "x":[1,2,3],
    "y":[4,5,6],
   },
   {
      "x":[20,30,40],
      "y":[50,60,70],
      "xaxis":"x2",
      "yaxis":"y2"
   }
]

layout = {
    "xaxis":{
        "domain":[0,0.7] # i.e. let the first x-axis span the first 70% of the plot width
    },
    "xaxis2":{
        "domain":[0.8,1] # i.e. let the second x-axis span the latter 20% of the plot width
    },
    "yaxis2":{
        "anchor":"x2" # i.e. bind the second y-axis to the start of the second x-axis
    }
}
py.plot(data, layout=layout)
Custom Sized Subplot

Multiple Subplots

import plotly
py = plotly.plotly('PythonAPI', 'ubpiol2cve')

data = [
    {
    "x":[1,2,3],
    "y":[4,5,6],
   },
   {
      "x":[20,30,40],
      "y":[50,60,70],
      "xaxis":"x2",
      "yaxis":"y2"
   },
   {
      "x":[300,400,500],
      "y":[600,700,800],
      "xaxis":"x3",
      "yaxis":"y3"
   },
   {
      "x":[4000,5000,6000],
      "y":[7000,8000,9000],
      "xaxis":"x4",
      "yaxis":"y4"
   }
]

layout = {
    "xaxis":{
        "domain":[0,0.45] # let the first x-axis span the first 45% of the plot width
    },
    "yaxis":{
        "domain":[0,0.45] # # and let the first y-axis span the first 45% of the plot height
    },
    "xaxis2":{
        "domain":[0.55,1] # and let the second x-axis span the latter 45% of the plot width
    },
    "yaxis2":{
        "domain":[0,0.45], # and let the second y-axis span the first 45% of the plot height
        "anchor":"x2" # bind the horizontal position of the second y-axis to the start of the second x-axis
    },
    "xaxis3":{
        "domain":[0,0.45],
        "anchor":"y3" # bind the vertical position of this axis to the start of yaxis3
    },
    "yaxis3":{
        "domain":[0.55,1],
    },
    "xaxis4":{
        "domain":[0.55,1],
        "anchor":"y4", # bind the vertical position of this axis to the start of yaxis4
    },
    "yaxis4":{
        "domain":[0.55,1],
        "anchor":"x4" # bind the horizontal position of this axis to the start of xaxis4
    }
}
py.plot(data, layout=layout)
Multiple Subplots

Subplots with Shared Axes

import plotly
py = plotly.plotly('PythonAPI', 'ubpiol2cve')

data = [
    {
    "x":[1,2,3],
    "y":[2,3,4],
   },
   {
      "x":[20,30,40],
      "y":[5,5,5],
      "xaxis":"x2",
      "yaxis":"y"
   },
   {
      "x":[2,3,4],
      "y":[600,700,800],
      "xaxis":"x",
      "yaxis":"y3"
   },
   {
      "x":[4000,5000,6000],
      "y":[7000,8000,9000],
      "xaxis":"x4",
      "yaxis":"y4"
   }
]

layout = {
    "xaxis":{
        "domain":[0,0.45] # let the first x-axis span the first 45% of the plot width
    },
    "yaxis":{
        "domain":[0,0.45] # and let the first y-axis span the first 45% of the plot height
    },
    "xaxis2":{
        "domain":[0.55,1] # and let the second x-axis span the latter 45% of the plot width
    },
    "yaxis3":{
        "domain":[0.55,1],
    },
    "xaxis4":{
        "domain":[0.55,1],
        "anchor":"y4", # bind the vertical position of this axis to the start of yaxis4
    },
    "yaxis4":{
        "domain":[0.55,1],
        "anchor":"x4" # bind the horizontal position of this axis to the start of xaxis4
    }
}
py.plot(data, layout=layout)
Subplots with Shared Axes

Stacked Subplots

import plotly
py = plotly.plotly('PythonAPI', 'ubpiol2cve')

data = [{'x': [0,1,2], 'y': [10,11,12]},
        {'x': [2,3,4], 'y': [100,110,120], 'yaxis': 'y2', 'xaxis': 'x2'},
        {'x': [3,4,5], 'y': [1000,1100,1200], 'yaxis': 'y3', 'xaxis': 'x3'}]
layout={
    'yaxis': {'domain': [0,0.8/3.]},
    'yaxis2': {'domain':[0.8/3+0.1,2*0.8/3+0.1]},
    'yaxis3': {'domain':[2*0.8/3+0.2,1]},
    'xaxis2': {'anchor':'y2'},
    'xaxis3': {'anchor':'y3'},
    'legend': {'traceorder': 'reversed'}
}

py.plot(data,layout=layout)
Stacked Subplots

Stacked Subplots with Coupled X-Axis

import plotly
py = plotly.plotly('PythonAPI', 'ubpiol2cve')

data = [{'x': [0,1,2], 'y': [10,11,12]},
        {'x': [2,3,4], 'y': [100,110,120], 'yaxis': 'y2'},
        {'x': [3,4,5], 'y': [1000,1100,1200], 'yaxis': 'y3'}]
layout={
    'yaxis': {'domain': [0,1./3.]},
    'yaxis2': {'domain':[1./3,2./3.]},
    'yaxis3': {'domain':[2./3.,1]},
    'legend': {'traceorder': 'reversed'}
}

py.plot(data,layout=layout)
Stacked Subplots with Coupled X-Axis

Simple Inset

import plotly
py = plotly.plotly('PythonAPI', 'ubpiol2cve')

data = [
    {
    "x":[1,2,3],
    "y":[4,3,2],
   },
   {
      "x":[20,30,40],
      "y":[30,40,50],
      "xaxis":"x2",
      "yaxis":"y2"
   }
]
layout = {
    "xaxis2": {
        "domain": [0.6, 0.95],
        "anchor": "y2"
    },
    "yaxis2":{
        "domain": [0.6, 0.95],
        "anchor": "x2"
    }
}
py.plot(data, layout=layout)
Simple Inset

Plot and Margin Size

import plotly
py = plotly.plotly('PythonAPI', 'ubpiol2cve')

x = [0,1,2,3,4,5,6,7,8]
y = [0,1,2,3,4,5,6,7,8]

layout = {
          'autosize': False,
          'height': 500,
          'width': 500,
          'margin': {
                    't':100,
                    'b':100,
                    'r':50,
                    'l':50,
                    'pad':4},  # space between border and gridlines
          "plot_bgcolor": "#c7c7c7",
          "paper_bgcolor": "#7f7f7f"
}

py.plot(x,y,layout=layout)
Plot and Margin Size

Global Font

import plotly
py = plotly.plotly('PythonAPI', 'ubpiol2cve')

x = [0,1,2,3,4,5,6,7,8]
y = [0,1,2,3,4,5,6,7,8]
x2 = [0,1,2,3,4,5,6,7,8]
y2 = [1,0,3,2,5,4,7,6,8]

layout = {"title": "Global Font",
          "font": {"color": "#7f7f7f",
                   "family": "Courier New, monospace",
                   "size": 18}
}



py.plot(x,y,x2,y2,layout=layout)
Global Font

Titles, Axes Names and Trace Names

import plotly
py = plotly.plotly('PythonAPI', 'ubpiol2cve')

x = [0,1,2,3,4,5,6,7,8]
y = [0,1,2,3,4,5,6,7,8]
x2 = [0,1,2,3,4,5,6,7,8]
y2 = [1,0,3,2,5,4,7,6,8]

data = [{'x': x,
         'y': y,
         'name':'Name of Trace 1'
         },
        {'x': x2,
         'y': y2,
         'name':'Name of Trace 2'
         }
        ]

layout = {

"title": "Plot Title",
          "xaxis": {
              "title":"x Axis",
              "titlefont": {
                  "color":"#7f7f7f",
                  "family":"Courier New, monospace",
                  "size":18
              }
          },
          "yaxis": {
              "title":"y Axis",
              "titlefont": {
                  "color":"#7f7f7f",
                  "family":"Courier New, monospace",
                  "size":18
              }
          }
}

py.plot(data,layout=layout)
Titles, Axes Names and Trace Names

Simple Annotation

import plotly
py = plotly.plotly('PythonAPI', 'ubpiol2cve')

x = [0,1,2,3,4,5,6,7,8]
y = [0,1,3,2,4,3,4,6,5]
x2 = [0,1,2,3,4,5,6,7,8]
y2 = [0,4,5,1,2,2,3,4,2]


layout = {
    "showlegend": False,
    "annotations": [{
        "text": "Annotation Text",
        "xref": "x",
        "yref": "y",
        "x": 2,
        "y": 5,
        "ax": 0,
        "ay": -40,
        "showarrow": True,
        "arrowhead": 7
    }]
}

py.plot(x,y,x2,y2,layout=layout)
Simple Annotation

Multiple Annotations

import plotly
py = plotly.plotly('PythonAPI', 'ubpiol2cve')

x = [0,1,2,3,4,5,6,7,8]
y = [0,1,3,2,4,3,4,6,5]
x2 = [0,1,2,3,4,5,6,7,8]
y2 = [0,4,5,1,2,2,3,4,2]


layout = {
    "showlegend": False,
    "annotations": [{
        "text": "Annotation Text",
        "xref": "x",
        "yref": "y",
        "x": 2,
        "y": 5,
        "ax": 0,
        "ay": -40,
        "showarrow": True,
        "arrowhead": 7
    },
    {
        "text": "Annotation Text 2",
        "xref": "x",
        "yref": "y",
        "x": 4,
        "y": 4,
        "ax": 0,
        "ay": -40,
        "showarrow": True,
        "arrowhead": 7
    }]
}

py.plot(x,y,x2,y2,layout=layout)
Multiple Annotations

Styling Annotations

import plotly
py = plotly.plotly('PythonAPI', 'ubpiol2cve')

x = [0,1,2,3,4,5,6,7,8]
y = [0,1,3,2,4,3,4,6,5]
x2 = [0,1,2,3,4,5,6,7,8]
y2 = [0,4,5,1,2,2,3,4,2]


layout = {
    "showlegend": False,
    "annotations": [{
        "text": "max=5",
        "xref": "x",
        "yref": "y",
        "x": 2,
        "y": 5,
        "ax": 20,
        "ay": -30,
        "arrowhead": 2,
        "arrowsize": 1,
        "arrowwidth": 2,
        "arrowcolor": "#636363",
        "bgcolor": "#ff7f0e",
        "bordercolor": "#c7c7c7",
        "borderpad": 4,
        "borderwidth": 2,
        "font": {
            "color": "#ffffff",
            "family": "Courier New, monospace",
            "size": 16
        },
        "opacity": 0.8,
        "showarrow": True,
        "align": "center"
    }]
}

py.plot(x,y,x2,y2,layout=layout)
Styling Annotations

Simple Bubblechart

import plotly
py = plotly.plotly('PythonAPI', 'ubpiol2cve')

data = [
    {'x': [1,2,3,4],
     'y': [10,11,12,13],
     'marker':{
        'size': [12, 22, 32, 42], # diameter
        'color': ['hsl(0,100,40)', 'hsl(33,100,40)', 'hsl(66,100,40)', 'hsl(99,100,40)'],
        'opacity':[.60, .70, .80, .90],
     },
     'mode': 'markers'
     },
     {'x': [1,2,3,4],
     'y': [11,12,13,14],
     'marker':{
        'color': 'rgb(31, 119, 180)',
        'size': 18,
        'symbol': ['circle', 'square', 'diamond', 'cross']
     },
     'mode': 'markers'
     },
     {'x': [1,2,3,4],
     'y': [12,13,14,15],
     'marker':{
        'size': 18,
        'line':{
            'color': ['rgb(120,120,120)', 'rgb(120,120,120)', 'red', 'rgb(120,120,120)'],
            'width': [2, 2, 6, 2]
        }
     },
     'mode': 'markers'
     }
]

py.plot(data, layout={'showlegend':False})
Simple Bubblechart

Private Graph

import plotly
py = plotly.plotly('PythonAPI', 'ubpiol2cve')

x = [0,2,4]
y = [0,4,2]

py.plot(x,y, world_readable=False) #defaults to True

# These settings apply to IPython notebooks, too.
# Private files will be viewable only to the creator
# and the private sharees in the notebooks.
# You must be signed in to Plotly and have cookies
# enabled to access.
Private Graph

Public Graph

import plotly
py = plotly.plotly('PythonAPI', 'ubpiol2cve')

x = [0,2,4]
y = [0,4,2]

py.plot(x,y, world_readable=True)
Public Graph

File Naming

import plotly
py = plotly.plotly('PythonAPI', 'ubpiol2cve')

x = [0,2,4]
y = [0,4,2]

py.plot(x,y, filename='myplotlygraph')
#or
py.plot(x,y, filename='myfolder/myplotlygraph')
File Naming

Data Visibility

import plotly
py = plotly.plotly('PythonAPI', 'ubpiol2cve')

trace0  = {
    'x': [0,1,2,3],
    'y': [0,2,4,6],
    'visible': True
    }

trace1 = {
    'x': [0,1,2,3],
    'y': [8,4,2,0],
    'visible': False
    }

py.plot(trace0,trace1)
Data Visibility

New Graph

import plotly
py = plotly.plotly('PythonAPI', 'ubpiol2cve')

py.plot([1,2], [3,4], filename='new plot', fileopt='new')

API RESPONSE:

{u'error': u'',
u'filename': u'new plot',
u'message': u'',
u'url': u'https://plot.ly/~IPython.Demo/497',
u'warning': u''}
import plotly
py = plotly.plotly('PythonAPI', 'ubpiol2cve')

py.plot([1,2], [3,4], filename='new plot', fileopt='new')
Check out the filename and url in the responses. We specified the same filename in both calls, but since we used the fileopt 'new', our second call appended '(1)' to the filename and created a new unique url for that graph. The first graph was not overwritten.

API RESPONSE:

{u'error': u'',
u'filename': u'new plot (1)',
u'message': u'',
u'url': u'https://plot.ly/~IPython.Demo/498',
u'warning': u''}

Overwrite

The overwrite option will save the plot with the specified filename no matter what. If a plot already exists under the same name, it will overwrite it and create a revision. If the plot with that filename doesn't exist, it will create it!
import plotly
py = plotly.plotly('PythonAPI', 'ubpiol2cve')

py.plot([1,2], [3,4], filename='same plot', fileopt='overwrite')

API RESPONSE:

{u'error': u'',
u'filename': u'same plot',
u'message': u'',
u'url': u'https://plot.ly/~IPython.Demo/494',
u'warning': u''}
import plotly
py = plotly.plotly('PythonAPI', 'ubpiol2cve')

py.plot([10,20], [30,40], filename='same plot', fileopt='overwrite')

API RESPONSE:

{u'error': u'',
u'filename': u'same plot',
u'message': u'',
u'url': u'https://plot.ly/~IPython.Demo/494',
u'warning': u''}

Append

The "append" fileopt will append the data that you supplied as new traces. If the filename doesn't exist, it will create a new file with that data.
import plotly
py = plotly.plotly('PythonAPI', 'ubpiol2cve')

py.plot([1, 2], [1, 2], filename='append plot', fileopt='append')
Here we're starting with one trace.
import plotly
py = plotly.plotly('PythonAPI', 'ubpiol2cve')

py.plot([1, 2], [3, 4], filename='append plot', fileopt='append')
Here we are appending a new trace with points (1,3) and (2,4).
import plotly
py = plotly.plotly('PythonAPI', 'ubpiol2cve')

py.plot([1, 2], [4, 5], [1, 2], [5, 6], filename='append plot', fileopt='append')
Here we are appending two new traces at points (1,4), (2,5) and (1,5), (2,6).

Extend

The "extend" fileopt will extend existing traces with your new data.
import plotly
py = plotly.plotly('PythonAPI', 'ubpiol2cve')

py.plot([1,2], [1, 2], [1, 2], [2, 3], [1, 2], [3, 4], filename='extend plot', fileopt='extend')
If there is no data in the plot, 'extend' will create new traces.
import plotly
py = plotly.plotly('PythonAPI', 'ubpiol2cve')

py.plot([3,4], [2, 1], [3, 4], [3, 2], [3, 4], [4, 3], filename='extend plot', fileopt='extend')
If there is data in the plot, the existing traces will be extended with the data in the order that it is supplied.
import plotly
py = plotly.plotly('PythonAPI', 'ubpiol2cve')

py.plot([4,5], [2, 3], filename='extend plot', fileopt='extend', traces=[1])
You can also choose which trace to extend with the "traces" argument. Here we extend the second trace. (traces=[1])
import plotly
py = plotly.plotly('PythonAPI', 'ubpiol2cve')

py.plot([5,6], [3,3], [4, 5], [1, 1], filename='extend plot', fileopt='extend', traces=[2, 0])
The traces option accepts an array as an argument. Here we extend the 3rd trace in the plot with the first data set that we supply, and the 1st trace in the plot with the second data set.

Setting Style

A simple example:
py.style([{'type':'bar'}, {'type':'scatter','marker':{'symbol':'square', 'color':'marker'}}])
This sets the first data trace to a bar chart and the second data trace to a scatter plot with purple square scatter points.

The general syntax is
py.style(style1[,style2,...], **kwargs)
stylei is a Plotly formatted dictionary that customizes the style of the i'th trace. It is identical to the datai dictionaries used in py.plot except that it doesn't contain the keys x or y.

**kwargs represents optional arguments. Accepted arguments are:
filename: filename of the plot inside your plotly account. If not specified, then the style is applied to the last plot that was made in your API session.
traces: a list that specifies which traces to style. If not specified, then traces are styled in the order of the data dicts or, if supplied, applied to the trace specified by the datai['name'] value.

Setting Layout

A simple example:
py.layout({'title':'Hello World'})
This sets your plot's title to Hello World.
The general syntax is
py.layout(layout, **kwargs)
layout is a Plotly formatted layout dictionary that customizes the style of the layout, the axes, and the legend.

**kwargs represents optional arguments. Accepted arguments are:
filename: filename of the plot inside your plotly account. If not specified, then the style is applied to the last plot that was made in your API session.

File Sharing

import plotly
py = plotly.plotly('PythonAPI', 'ubpiol2cve')

x = [0,2,4]
y = [0,4,2]

py.plot(x,y, filename='lab_results/experiment1')

When you share a folder in the Plotly tool, files created within that folder using the API are automatically shared.

In this case user demos has shared the folder lab_results with batman and robin.

When demos saves a file (experiment1 inside lab_results, batman

IFrames

Formal Syntax

A simple example:
py.plot([0,1],[10,11])
or in an alternate syntax
py.plot([{'x':[0,1],'y':[10,11]}])
The general plotting syntax is
py.plot(x1, y1[,x2,y2,...], **kwargs)
or
py.plot([data1[,data2,...]], **kwargs)
xi, yi are lists or numpy arrays with numbers or characters as elements.

datai is a Plotly formatted data dictionary that is at least {'x': xi, 'y': xi} but can contain more styling and chart-type data. For example,
data1={'x':[0,1],'y':[10,11],'name':'Exp Results', 'type':'scatter', 'marker':{'symbol':'square','color':'purple'}}
specifies a scatter trace with purple square data markers that is named Exp Results.

**kwargs represents optional arguments. Accepted arguments are:
filename: filename of the plot inside your plotly account
fileopt: file-options: 'new', 'overwrite', or 'append'
layout: a Plotly formatted layout dict describing layout options.
style: a Plotly formatted style dict describing the style of all the data traces.
world_readable: a boolean. If True, then the graph will be public. If False, then only you can see it. Default is True.