Skip to content

Commit

Permalink
Merge pull request #192 from plotly/plot_postmessage
Browse files Browse the repository at this point in the history
`plot` method in `GraphWidget`
  • Loading branch information
chriddyp committed Feb 20, 2015
2 parents a283d83 + 8486779 commit 40c2a45
Show file tree
Hide file tree
Showing 4 changed files with 92 additions and 30 deletions.
29 changes: 2 additions & 27 deletions plotly/plotly/plotly.py
Original file line number Diff line number Diff line change
Expand Up @@ -163,33 +163,8 @@ def plot(figure_or_data, validate=True, **plot_options):
False: do not open plot in the browser, but do return the unique url
"""
if isinstance(figure_or_data, dict):
figure = figure_or_data
elif isinstance(figure_or_data, list):
figure = {'data': figure_or_data}
else:
raise exceptions.PlotlyError("The `figure_or_data` positional argument "
"must be either `dict`-like or "
"`list`-like.")
if validate:
try:
tools.validate(figure, obj_type='Figure')
except exceptions.PlotlyError as err:
raise exceptions.PlotlyError("Invalid 'figure_or_data' argument. "
"Plotly will not be able to properly "
"parse the resulting JSON. If you "
"want to send this 'figure_or_data' "
"to Plotly anyway (not recommended), "
"you can set 'validate=False' as a "
"plot option.\nHere's why you're "
"seeing this error:\n\n{0}"
"".format(err))
if not figure['data']:
raise exceptions.PlotlyEmptyDataError(
"Empty data list found. Make sure that you populated the "
"list of data objects you're sending and try again.\n"
"Questions? support@plot.ly"
)
figure = tools.return_figure_from_figure_or_data(figure_or_data, validate)

for entry in figure['data']:
for key, val in list(entry.items()):
try:
Expand Down
32 changes: 32 additions & 0 deletions plotly/tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -1230,3 +1230,35 @@ def __init__(self, url, width, height):

def _repr_html_(self):
return self.embed_code


def return_figure_from_figure_or_data(figure_or_data, validate_figure):
if isinstance(figure_or_data, dict):
figure = figure_or_data
elif isinstance(figure_or_data, list):
figure = {'data': figure_or_data}
else:
raise exceptions.PlotlyError("The `figure_or_data` positional "
"argument must be either "
"`dict`-like or `list`-like.")
if validate_figure:
try:
validate(figure, obj_type='Figure')
except exceptions.PlotlyError as err:
raise exceptions.PlotlyError("Invalid 'figure_or_data' argument. "
"Plotly will not be able to properly "
"parse the resulting JSON. If you "
"want to send this 'figure_or_data' "
"to Plotly anyway (not recommended), "
"you can set 'validate=False' as a "
"plot option.\nHere's why you're "
"seeing this error:\n\n{0}"
"".format(err))
if not figure['data']:
raise exceptions.PlotlyEmptyDataError(
"Empty data list found. Make sure that you populated the "
"list of data objects you're sending and try again.\n"
"Questions? support@plot.ly"
)

return figure
2 changes: 1 addition & 1 deletion plotly/version.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
__version__ = '1.6.6'
__version__ = '1.6.7'
59 changes: 57 additions & 2 deletions plotly/widgets/graph_widget.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
from collections import deque
import json
import os
import uuid

# TODO: protected imports?
from IPython.html import widgets
from IPython.utils.traitlets import Unicode
from IPython.display import Javascript, display

from plotly import utils
from plotly import utils, tools
from plotly.graph_objs import Figure
from pkg_resources import resource_string

# Load JS widget code
Expand Down Expand Up @@ -247,6 +247,61 @@ def message_handler(widget, ranges):
"""
self._handle_registration('zoom', callback, remove)

def plot(self, figure_or_data, validate=True):
"""Plot figure_or_data in the Plotly graph widget.
Args:
figure_or_data (dict, list, or plotly.graph_obj object):
The standard Plotly graph object that describes Plotly
graphs as used in `plotly.plotly.plot`. See examples
of the figure_or_data in https://plot.ly/python/
Returns: None
Example 1 - Graph a scatter plot:
```
from plotly.graph_objs import Scatter
g = GraphWidget()
g.plot([Scatter(x=[1, 2, 3], y=[10, 15, 13])])
```
Example 2 - Graph a scatter plot with a title:
```
from plotly.graph_objs import Scatter, Figure, Data
fig = Figure(
data = Data([
Scatter(x=[1, 2, 3], y=[20, 15, 13])
]),
layout = Layout(title='Experimental Data')
)
g = GraphWidget()
g.plot(fig)
```
Example 3 - Clear a graph widget
```
from plotly.graph_objs import Scatter, Figure
g = GraphWidget()
g.plot([Scatter(x=[1, 2, 3], y=[10, 15, 13])])
# Now clear it
g.plot({}) # alternatively, g.plot(Figure())
```
"""
if figure_or_data == {} or figure_or_data == Figure():
validate = False

figure = tools.return_figure_from_figure_or_data(figure_or_data,
validate)
message = {
'task': 'newPlot',
'data': figure.get('data', []),
'layout': figure.get('layout', {}),
'graphId': self._graphId
}
self._handle_outgoing_message(message)

def restyle(self, data, indices=None):
"""Update the style of existing traces in the Plotly graph.
Expand Down

0 comments on commit 40c2a45

Please sign in to comment.