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? [email protected]" ) return figure
def return_figure_from_figure_or_data(figure_or_data, validate_figure): from plotly.graph_objs import Figure from plotly.basedatatypes import BaseFigure validated = False if isinstance(figure_or_data, dict): figure = figure_or_data elif isinstance(figure_or_data, list): figure = {"data": figure_or_data} elif isinstance(figure_or_data, BaseFigure): figure = figure_or_data.to_dict() validated = True else: raise exceptions.PlotlyError( "The `figure_or_data` positional " "argument must be " "`dict`-like, `list`-like, or an instance of plotly.graph_objs.Figure" ) if validate_figure and not validated: try: figure = Figure(**figure).to_dict() 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? Visit support.plot.ly" ) return figure
def 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 world_readable (default=True) -- make this figure private/public 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 """ 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? [email protected]" ) for entry in figure['data']: for key, val in list(entry.items()): try: if len(val) > 40000: msg = ("Woah there! Look at all those points! Due to " "browser limitations, Plotly has a hard time " "graphing more than 500k data points for line " "charts, or 40k points for other types of charts. " "Here are some suggestions:\n" "(1) Trying using the image API to return an image " "instead of a graph URL\n" "(2) Use matplotlib\n" "(3) See if you can create your visualization with " "fewer data points\n\n" "If the visualization you're using aggregates " "points (e.g., box plot, histogram, etc.) you can " "disregard this warning.") warnings.warn(msg) except TypeError: pass plot_options = _plot_option_logic(plot_options) res = _send_to_plotly(figure, **plot_options) if res['error'] == '': if plot_options['auto_open']: _open_url(res['url']) return res['url'] else: raise exceptions.PlotlyAccountError(res['error'])
def get(figure_or_data, format='png', width=None, height=None): """ Return a static image of the plot described by `figure`. Valid formats: 'png', 'svg', 'jpeg', 'pdf' """ # TODO: format is a built-in name... we shouldn't really use it if isinstance(figure_or_data, dict): figure = figure_or_data elif isinstance(figure_or_data, list): figure = {'data': figure_or_data} else: raise exceptions.PlotlyEmptyDataError( "`figure_or_data` must be a dict or a list.") if format not in ['png', 'svg', 'jpeg', 'pdf']: raise exceptions.PlotlyError( "Invalid format. This version of your Plotly-Python " "package currently only supports png, svg, jpeg, and pdf. " "Learn more about image exporting, and the currently " "supported file types here: " "https://plot.ly/python/static-image-export/") credentials = get_credentials() validate_credentials(credentials) username, api_key = credentials['username'], credentials['api_key'] headers = { 'Plotly-Version': version.__version__, 'Content-Type': 'application/json', 'Plotly-Client-Platform': 'python' } payload = {'figure': figure, 'format': format} if width is not None: payload['width'] = width if height is not None: payload['height'] = height url = _api_v2.api_url('images/') res = requests.post(url, data=json.dumps(payload, cls=utils.PlotlyJSONEncoder), headers=headers, verify=get_config()['plotly_ssl_verification'], auth=HTTPBasicAuth(username, api_key)) headers = res.headers if res.status_code == 200: if ('content-type' in headers and headers['content-type'] in [ 'image/png', 'image/jpeg', 'application/pdf', 'image/svg+xml' ]): return res.content elif ('content-type' in headers and 'json' in headers['content-type']): return_data = json.loads(res.content) return return_data['image'] else: try: if ('content-type' in headers and 'json' in headers['content-type']): return_data = json.loads(res.content) else: return_data = {'error': res.content} except: raise exceptions.PlotlyError("The response " "from plotly could " "not be translated.") raise exceptions.PlotlyError(return_data['error'])