我们从Python开源项目中,提取了以下47个代码示例,用于说明如何使用plotly.plotly.plot()。
def plot_frame(dataframe, uname=None, api_key=None, mode='lines', line={}): try: import plotly.plotly as ply import plotly.tools as ptls from plotly.graph_objs import Scatter, Layout, Data, Figure except ImportError: raise InvalidOperationException("Please install the Python plotly bindings") if uname and api_key: ply.sign_in(uname, api_key) c1 = dataframe.ch1 c2 = dataframe.ch2 x = list(range(len(c1))) t1 = Scatter(x=x, y=c1, mode=mode, line=line) t2 = Scatter(x=x, y=c2, mode=mode, line=line) layout = Layout(title="Moku:Lab Frame Grab") data = Data([t1, t2]) fig = Figure(data=data, layout=layout) return ply.plot(fig)
def probabilitygraph(data, vec1, high, k=5, weightf=gaussian, ss=5.0): t1 = np.arange(0.0, high, 0.1) probs = np.array([probguess(data, vec1, v, v+0.1, k, weightf) for v in t1]) smoothed = [] for i in xrange(len(probs)): sv = 0.0 for j in xrange(len(probs)): dist = abs(i-j)*0.1 weight = gaussian(dist, sigma=ss) sv += weight*probs[j] smoothed.append(sv) smoothed = np.array(smoothed) data = go.Scatter(x=t1, y=smoothed) fig = go.Figure(data=[data]) py.plot(fig, filename='wineguess_smoothed')
def _make_colorscale(colors, scale=None): """ Makes a colorscale from a list of colors and scale Takes a list of colors and scales and constructs a colorscale based on the colors in sequential order. If 'scale' is left empty, a linear- interpolated colorscale will be generated. If 'scale' is a specificed list, it must be the same legnth as colors and must contain all floats For documentation regarding to the form of the output, see https://plot.ly/python/reference/#mesh3d-colorscale """ colorscale = [] if not scale: for j, color in enumerate(colors): colorscale.append([j * 1./(len(colors) - 1), color]) return colorscale else: colorscale = [list(tup) for tup in zip(scale, colors)] return colorscale
def _make_violin_rugplot(vals, pdf_max, distance, color='#1f77b4'): """ Returns a rugplot fig for a violin plot. """ from plotly.graph_objs import graph_objs return graph_objs.Scatter( y=vals, x=[-pdf_max-distance]*len(vals), marker=graph_objs.Marker( color=color, symbol='line-ew-open' ), mode='markers', name='', showlegend=False, hoverinfo='y' )
def _make_quartiles(q1, q3): """ Makes the upper and lower quartiles for a violin plot. """ from plotly.graph_objs import graph_objs return graph_objs.Scatter( x=[0, 0], y=[q1, q3], text=['lower-quartile: ' + '{:0.2f}'.format(q1), 'upper-quartile: ' + '{:0.2f}'.format(q3)], mode='lines', line=graph_objs.Line( width=4, color='rgb(0,0,0)' ), hoverinfo='text' )
def _make_XAxis(xaxis_title, xaxis_range): """ Makes the x-axis for a violin plot. """ from plotly.graph_objs import graph_objs xaxis = graph_objs.XAxis(title=xaxis_title, range=xaxis_range, showgrid=False, zeroline=False, showline=False, mirror=False, ticks='', showticklabels=False, ) return xaxis
def make_rug(self): """ Makes the rug plot(s) for create_distplot(). :rtype (list) rug: list of rug plot representations """ rug = [None] * self.trace_number for index in range(self.trace_number): rug[index] = dict(type='scatter', x=self.hist_data[index], y=([self.group_labels[index]] * len(self.hist_data[index])), xaxis='x1', yaxis='y2', mode='markers', name=self.group_labels[index], legendgroup=self.group_labels[index], showlegend=(False if self.show_hist or self.show_curve else True), text=self.rug_text[index], marker=dict(color=self.colors[index], symbol='line-ns-open')) return rug
def general_feature_coverage(self): """ :return: """ self.stream(0) fig = { 'data': [{ 'labels': [IMPLEMENTED_LABEL, NOT_IMPLEMENTED_LABEL], 'values': [ self.document.get_number_of_implemented_features(), self.document.get_number_of_features(), ], 'type': 'pie'} ], 'layout': {'title': OVERALL_TESTS_IMPLEMENTATION_LABEL} } return py.plot(fig, filename='python-streaming')
def core_feature_coverage(self): """ :return: """ self.stream(1) fig = { 'data': [{ 'labels': [IMPLEMENTED_LABEL, NOT_IMPLEMENTED_LABEL], 'values': [ self.document.get_number_of_implemented_core_features(), self.document.get_number_of_core_features(), ], 'type': 'pie'} ], 'layout': {'title': CORE_TESTS_IMPLEMENTATION_LABEL} } return py.plot(fig, filename='python-streaming')
def scenarios_coverage(self): """ :return: """ self.stream(0) fig = { 'data': [{ 'labels': [IMPLEMENTED_LABEL, NOT_IMPLEMENTED_LABEL], 'values': [ self.document.get_number_of_implemented_scenarios(), self.document.get_number_of_scenarios(), ], 'type': 'pie'} ], 'layout': {'title': SCENARIOS_IMPLEMENTATION_LABEL} } return py.plot(fig, filename='python-streaming')
def core_scenarios_coverage(self): """ :return: """ self.stream(0) fig = { 'data': [{ 'labels': [IMPLEMENTED_LABEL, NOT_IMPLEMENTED_LABEL], 'values': [ self.document.get_number_of_implemented_core_scenarios(), self.document.get_number_of_core_scenarios(), ], 'type': 'pie'} ], 'layout': {'title': CORE_SCENARIOS_IMPLEMENTATION_LABEL} } return py.plot(fig, filename='python-streaming')
def running_times(): rospack = rospkg.RosPack() data_path = os.path.join(rospack.get_path('vslam_evaluation'), 'out') df = pd.read_csv(os.path.join(data_path, 'runtimes.txt'), header=None, index_col=0) bars = [] for col_idx in df: this_stack = df[col_idx].dropna() bars.append( go.Bar( x=this_stack.index, y=this_stack.values, name='Thread {}'.format(col_idx))) layout = go.Layout( barmode='stack', yaxis={'title': 'Running time [s]'}) fig = go.Figure(data=bars, layout=layout) url = py.plot(fig, filename='vslam_eval_run_times')
def __init__(self, labels, values, username, api_key, plot_name): self.logger = logging.getLogger(self.__class__.__name__) py.sign_in(username, api_key) fig = { 'data': [{'labels': labels, 'values': values, 'type': 'pie'}], 'layout': {'title': "Valentines week - %s #LoveIsInTheAir" % plot_name} } url = py.plot(fig, filename="Pie Chart %s" % plot_name) self.logger.info("Plotted Pie Chart: %s" % url)
def cumulativegraph(data,vec1,high,k=5,weightf=gaussian): t1 = np.arange(0.0, high, 0.1) cprob = np.array([probguess(data, vec1, 0, v, k, weightf) for v in t1]) data = go.Scatter(x=t1, y=cprob) fig = go.Figure(data=[data]) py.plot(fig, filename='wineguess')
def _make_linear_colorscale(colors): """ Makes a list of colors into a colorscale-acceptable form For documentation regarding to the form of the output, see https://plot.ly/python/reference/#mesh3d-colorscale """ scale = 1./(len(colors) - 1) return[[i * scale, color] for i, color in enumerate(colors)]
def _calc_stats(data): """ Calculate statistics for use in violin plot. """ import numpy as np x = np.asarray(data, np.float) vals_min = np.min(x) vals_max = np.max(x) q2 = np.percentile(x, 50, interpolation='linear') q1 = np.percentile(x, 25, interpolation='lower') q3 = np.percentile(x, 75, interpolation='higher') iqr = q3 - q1 whisker_dist = 1.5 * iqr # in order to prevent drawing whiskers outside the interval # of data one defines the whisker positions as: d1 = np.min(x[x >= (q1 - whisker_dist)]) d2 = np.max(x[x <= (q3 + whisker_dist)]) return { 'min': vals_min, 'max': vals_max, 'q1': q1, 'q2': q2, 'q3': q3, 'd1': d1, 'd2': d2 }
def _make_median(q2): """ Formats the 'median' hovertext for a violin plot. """ from plotly.graph_objs import graph_objs return graph_objs.Scatter( x=[0], y=[q2], text=['median: ' + '{:0.2f}'.format(q2)], mode='markers', marker=dict(symbol='square', color='rgb(255,255,255)'), hoverinfo='text' )
def _make_non_outlier_interval(d1, d2): """ Returns the scatterplot fig of most of a violin plot. """ from plotly.graph_objs import graph_objs return graph_objs.Scatter( x=[0, 0], y=[d1, d2], name='', mode='lines', line=graph_objs.Line(width=1.5, color='rgb(0,0,0)') )
def _validate_distplot(hist_data, curve_type): """ Distplot-specific validations :raises: (PlotlyError) If hist_data is not a list of lists :raises: (PlotlyError) If curve_type is not valid (i.e. not 'kde' or 'normal'). """ try: import pandas as pd _pandas_imported = True except ImportError: _pandas_imported = False hist_data_types = (list,) if _numpy_imported: hist_data_types += (np.ndarray,) if _pandas_imported: hist_data_types += (pd.core.series.Series,) if not isinstance(hist_data[0], hist_data_types): raise exceptions.PlotlyError("Oops, this function was written " "to handle multiple datasets, if " "you want to plot just one, make " "sure your hist_data variable is " "still a list of lists, i.e. x = " "[1, 2, 3] -> x = [[1, 2, 3]]") curve_opts = ('kde', 'normal') if curve_type not in curve_opts: raise exceptions.PlotlyError("curve_type must be defined as " "'kde' or 'normal'") if _scipy_imported is False: raise ImportError("FigureFactory.create_distplot requires scipy")
def _plot_option_logic(plot_options_from_call_signature): """ Given some plot_options as part of a plot call, decide on final options. Precedence: 1 - Start with DEFAULT_PLOT_OPTIONS 2 - Update each key with ~/.plotly/.config options (tls.get_config) 3 - Update each key with session plot options (set by py.sign_in) 4 - Update each key with plot, iplot call signature options """ default_plot_options = copy.deepcopy(DEFAULT_PLOT_OPTIONS) file_options = tools.get_config_file() session_options = get_session_plot_options() plot_options_from_call_signature = copy.deepcopy(plot_options_from_call_signature) # Validate options and fill in defaults w world_readable and sharing for option_set in [plot_options_from_call_signature, session_options, file_options]: utils.validate_world_readable_and_sharing_settings(option_set) utils.set_sharing_and_world_readable(option_set) # dynamic defaults if ('filename' in option_set and 'fileopt' not in option_set): option_set['fileopt'] = 'overwrite' user_plot_options = {} user_plot_options.update(default_plot_options) user_plot_options.update(file_options) user_plot_options.update(session_options) user_plot_options.update(plot_options_from_call_signature) user_plot_options = {k: v for k, v in user_plot_options.items() if k in default_plot_options} return user_plot_options
def plot_mpl(fig, resize=True, strip_style=False, update=None, **plot_options): """Replot a matplotlib figure with plotly. This function: 1. converts the mpl figure into JSON (run help(plolty.tools.mpl_to_plotly)) 2. makes a request to Plotly to save this figure in your account 3. opens your figure in a browser tab OR returns the unique figure url Positional agruments: fig -- a figure object from matplotlib Keyword arguments: resize (default=True) -- allow plotly to choose the figure size strip_style (default=False) -- allow plotly to choose style options update (default=None) -- update the resulting figure with an 'update' dictionary-like object resembling a plotly 'Figure' object Additional keyword arguments: plot_options -- run help(plotly.plotly.plot) """ fig = tools.mpl_to_plotly(fig, resize=resize, strip_style=strip_style) if update and isinstance(update, dict): fig.update(update) fig.validate() elif update is not None: raise exceptions.PlotlyGraphObjectError( "'update' must be dictionary-like and a valid plotly Figure " "object. Run 'help(plotly.graph_objs.Figure)' for more info." ) return plot(fig, **plot_options)
def __init__(self, stream_id): """ Initialize a Stream object with your unique stream_id. Find your stream_id at {plotly_domain}/settings. For more help, see: `help(plotly.plotly.Stream)` or see examples and tutorials here: https://plot.ly/python/streaming/ """ self.stream_id = stream_id self.connected = False self._stream = None
def open(self): """ Open streaming connection to plotly. For more help, see: `help(plotly.plotly.Stream)` or see examples and tutorials here: https://plot.ly/python/streaming/ """ streaming_specs = self.get_streaming_specs() self._stream = chunked_requests.Stream(**streaming_specs)
def ishow(cls, figure_or_data, format='png', width=None, height=None, scale=None): """Display a static image of the plot described by `figure_or_data` in an IPython Notebook. positional arguments: - figure_or_data: The figure dict-like or data list-like object that describes a plotly figure. Same argument used in `py.plot`, `py.iplot`, see https://plot.ly/python for examples - format: 'png', 'svg', 'jpeg', 'pdf' - width: output width - height: output height - scale: Increase the resolution of the image by `scale` amount Only valid for PNG and JPEG images. example:
import plotly.plotly as py fig = {'data': [{'x': [1, 2, 3], 'y': [3, 1, 5], 'type': 'bar'}]} py.image.ishow(fig, 'png', scale=3) """ if format == 'pdf': raise exceptions.PlotlyError( "Aw, snap! " "It's not currently possible to embed a pdf into " "an IPython notebook. You can save the pdf " "with the `image.save_as` or you can " "embed an png, jpeg, or svg.") img = cls.get(figure_or_data, format, width, height, scale) from IPython.display import display, Image, SVG if format == 'svg': display(SVG(img)) else: display(Image(img))
```
def delete(cls, grid=None, grid_url=None): """ Delete a grid from your Plotly account. Only one of `grid` or `grid_url` needs to be specified. `grid` is a plotly.grid_objs.Grid object that has already been uploaded to Plotly. `grid_url` is the URL of the Plotly grid to delete Usage example 1: Upload a grid to plotly, then delete it
from plotly.grid_objs import Grid, Column import plotly.plotly as py column_1 = Column([1, 2, 3], 'time') column_2 = Column([4, 2, 5], 'voltage') grid = Grid([column_1, column_2]) py.grid_ops.upload(grid, 'time vs voltage') # now delete it, and free up that filename py.grid_ops.delete(grid) ``` Usage example 2: Delete a plotly grid by url ``` import plotly.plotly as py grid_url = 'https://plot.ly/~chris/3' py.grid_ops.delete(grid_url=grid_url) ``` """ grid_id = _api_v2.parse_grid_id_args(grid, grid_url) api_url = _api_v2.api_url('grids') + '/' + grid_id res = requests.delete(api_url, headers=_api_v2.headers(), verify=get_config()['plotly_ssl_verification']) _api_v2.response_handler(res)
def parse_grid_id_args(cls, grid, grid_url): """ Return the grid_id from the non-None input argument. Raise an error if more than one argument was supplied. """ if grid is not None: id_from_grid = grid.id else: id_from_grid = None args = [id_from_grid, grid_url] arg_names = ('grid', 'grid_url') supplied_arg_names = [arg_name for arg_name, arg in zip(arg_names, args) if arg is not None] if not supplied_arg_names: raise exceptions.InputError( "One of the two keyword arguments is required:\n" " `grid` or `grid_url`\n\n" "grid: a plotly.graph_objs.Grid object that has already\n" " been uploaded to Plotly.\n\n" "grid_url: the url where the grid can be accessed on\n" " Plotly, e.g. 'https://plot.ly/~chris/3043'\n\n" ) elif len(supplied_arg_names) > 1: raise exceptions.InputError( "Only one of `grid` or `grid_url` is required. \n" "You supplied both. \n" ) else: supplied_arg_name = supplied_arg_names.pop() if supplied_arg_name == 'grid_url': path = six.moves.urllib.parse.urlparse(grid_url).path file_owner, file_id = path.replace("/~", "").split('/')[0:2] return '{0}:{1}'.format(file_owner, file_id) else: return grid.id
def add_share_key_to_url(plot_url, attempt=0): """ Update plot's url to include the secret key """ urlsplit = six.moves.urllib.parse.urlparse(plot_url) file_owner = urlsplit.path.split('/')[1].split('~')[1] file_id = urlsplit.path.split('/')[2] url = _api_v2.api_url("files/") + file_owner + ":" + file_id new_response = requests.patch(url, headers=_api_v2.headers(), data={"share_key_enabled": "True", "world_readable": "False"}) _api_v2.response_handler(new_response) # decode bytes for python 3.3: https://bugs.python.org/issue10976 str_content = new_response.content.decode('utf-8') new_response_data = json.loads(str_content) plot_url += '?share_key=' + new_response_data['share_key'] # sometimes a share key is added, but access is still denied # check for access, and retry a couple of times if this is the case # https://github.com/plotly/streambed/issues/4089 embed_url = plot_url.split('?')[0] + '.embed' + plot_url.split('?')[1] access_res = requests.get(embed_url) if access_res.status_code == 404: attempt += 1 if attempt == 5: return plot_url plot_url = add_share_key_to_url(plot_url.split('?')[0], attempt) return plot_url
def create_plots(): # We make a plot for every room plotly_logger.info('max points per graph: %s', ploty_max_points_per_graph) for zone in zones: plotly_logger.info('Creating graph for: %s' % zone) stream_id = zones[zone] stream = Stream( token=stream_id, maxpoints=ploty_max_points_per_graph ) trace1 = Scatter( x=[], y=[], mode='lines+markers', line=Line( shape='spline' ), stream=stream ) data = Data([trace1]) layout = Layout(title=zone) fig = Figure(data=data, layout=layout) py.plot(fig, filename=zone, fileopt='extend') # if called directly then this is what will execute # It will create the initial plot.ly reports if need be.
def position_comparison(): plot_layout = go.Layout( title='X position comparison', xaxis={'title': 'Time [s]'}, yaxis={'title': 'X position [m]'} ) plot_data = [] for i, (label, bag_file_name, odometry_topic_name) in enumerate(comparisons): td_visual, td_vicon = load_one_comparison(bag_file_name, odometry_topic_name) plot_data.append( go.Scatter(x=td_visual.col(0)[::4], y=td_visual.col(1)[::4], mode='lines+markers', name=label, marker={'maxdisplayed': 150})) if i == 0: # Only plot ground truth once plot_data.append( go.Scatter(x=td_vicon.col(0)[::20], y=td_vicon.col(1)[::20], mode='lines+markers', name='Truth', marker={'maxdisplayed': 150})) fig = go.Figure(data=plot_data, layout=plot_layout) url = py.plot(fig, filename='vslam_eval_x_pos')
def renderPlot(): ''' Prepares the initial plot on the plotly engine and then streams the response one by one ''' global totalpages start = 1 c = 0 x = [] y = [] text = [] while True: if totalpages is not None and start > totalpages: break else: URL = url_prefix + mse_ip + url_suffix + mac + url_query_parameters1 + str(start) + url_query_parameters2 + str(interval) c += 1 start = c * interval + 1 data_dict = get_response(URL, username, password, response_format) if data_dict.get("isError") == True: break if totalpages is None: totalpages = data_dict["totalpages"] data = data_dict["data"] length = data_dict["length"] width = data_dict["width"] plotTemplate(data[0][1], data[0][2], length, width) x.extend([a[1] for a in data]) y.extend([a[2] for a in data]) text.extend([(a[1], a[2]) for a in data]) scatter_write_stream.open() end_write_stream.open() scatter = dict(x=x, y=y, text=text) scatter_write_stream.write(scatter) end_scatter = dict(x=[x[-1]], y=[y[-1]]) end_write_stream.write(end_scatter) # scatter_write_stream.close() # end_write_stream.close()
def help(talk_user_id): talk_user = TalkUser.objects.get(pk=talk_user_id) sm = SlackMessage(talk_user.slack_auth.bot_access_token, talk_user.slack_id) sm.send_text("You can view this again", [ # {"text": "login", "value": "login"}, # {"text": "register", "value": "register"}, {"text": "help", "value": "help"}]) sm.send_text("You can request for historical price plots. Afterwards, you can get insights or" " compare with other tickers", [{"text": "goog 17 oct to 10 nov", "value": "goog 17 oct to 10 nov"}, {"text": "apple last month", "value": "apple last month"}]) sm.send_text("You can request for current price or price on a specific day", [{"text": "yahoo price now", "value": "yahoo price now"}, {"text": "aapl on 10 nov 2015", "value": "aapl on 10 nov 2015"}]) sm.send_text("You can buy or sell shares", [{"text": "buy 2 goog", "value": "buy 2 goog"}, {"text": "sell apple", "value": "sell apple"}]) sm.send_text("You can check your portfolio, or plot the portfolio performance", [{"text": "portfolio", "value": "portfolio"}, {"text": "portfolio plot", "value": "portfolio plot"}]) sm.send_text("You can find out how you are performing compared to others, and see who's doing well", [{"text": "how am i doing?", "value": "how am i doing?"}]) sm.send_text("You can update your notification preferences", actions=[{"text": "notification preferences", "value": "notification preferences"}]) sm.send_text("You can always give feedback. Whether it is feature request, any bugs you encounter, " "and in general if you have any comments. We would love to hear from you!", [{"text": "feedback", "value": "feedback"}])
def portfolio_plot(talk_user_id): talk_user = TalkUser.objects.get(pk=talk_user_id) slack_auth = talk_user.slack_auth sm = SlackMessage(slack_auth.bot_access_token, talk_user.slack_id) dates, values = last_week_values(talk_user) scatter = go.Scatter(x=dates, y=values) graph_url = plot_graph([scatter], 'Portfolio plot from {} to {}'.format(pretty_date(dates[0]), pretty_date(dates[-1]))) sm.send_image(graph_url)
def plot_graph(traces, title): py.sign_in(settings.PLOTLY_USERNAME, settings.PLOTLY_PASSWORD) filename = str(uuid.uuid4()) + ".png" layout = go.Layout(title=title, width=800, height=640) fig = go.Figure(data=traces, layout=layout) # plot_file = offline.plot(fig, show_link=False, auto_open=False, # filename=settings.MEDIA_ROOT + filename, # include_plotlyjs=True) # ghost = Ghost() # page, resources = ghost.open(plot_file) plot_url = py.plot(fig, filename=filename, auto_open=False, file_opt='new') return plot_url + ".png" # return "http://8d30bf7d.ngrok.io/media/" + filename + ".html"
def collisions_per_number_of_cars(file_location): """ Plot the number of collisions per car present in the intersection at the collision moment. :param file_location: absolute path to the file to read. The file must be in json format. :return: url to plot.ly with the interactive graph """ reading_file = open(file_location) file_string = '[' for line in reading_file: file_string += line reading_file.close() file_string = file_string[:len(file_string)-2] + ']' json_data = json.JSONDecoder().decode(file_string) x = [] y = [] collision_dict = {} for value in json_data: if "collision_code" in value["message"]: number_of_cars = len(value["message"]["collision_initial_conditions"]) if number_of_cars not in collision_dict: collision_dict[number_of_cars] = 0 collision_dict[number_of_cars] += 1 for key in collision_dict: x.append(key) y.append(collision_dict[key]) trace0 = go.Scatter(x=x, y=y, mode='markers', name='cars in collition') data = [trace0] return py.plot(data, filename='prueba')
def generatePlot(trace, traceLabels, plotname): data = [trace, traceLabels] layout = go.Layout( margin=dict( l=0, r=0, b=0, t=32, ), title=plotname, scene=dict( xaxis=dict( showgrid=False, showticklabels=False, showspikes=False, showline=False, showaxeslabels=False, zeroline=False, title='', ), yaxis=dict( showgrid=False, showticklabels=False, showspikes=False, showline=False, showaxeslabels=False, zeroline=False, title='', ), zaxis=dict( showgrid=False, showticklabels=False, showspikes=False, showline=False, showaxeslabels=False, zeroline=False, title='', ), ) ) fig = go.Figure(data=data, layout=layout) return py.plot(fig, filename=plotname, auto_open=False)
def _violinplot(vals, fillcolor='#1f77b4', rugplot=True): """ Refer to FigureFactory.create_violin() for docstring. """ import numpy as np from scipy import stats vals = np.asarray(vals, np.float) # summary statistics vals_min = FigureFactory._calc_stats(vals)['min'] vals_max = FigureFactory._calc_stats(vals)['max'] q1 = FigureFactory._calc_stats(vals)['q1'] q2 = FigureFactory._calc_stats(vals)['q2'] q3 = FigureFactory._calc_stats(vals)['q3'] d1 = FigureFactory._calc_stats(vals)['d1'] d2 = FigureFactory._calc_stats(vals)['d2'] # kernel density estimation of pdf pdf = stats.gaussian_kde(vals) # grid over the data interval xx = np.linspace(vals_min, vals_max, 100) # evaluate the pdf at the grid xx yy = pdf(xx) max_pdf = np.max(yy) # distance from the violin plot to rugplot distance = (2.0 * max_pdf)/10 if rugplot else 0 # range for x values in the plot plot_xrange = [-max_pdf - distance - 0.1, max_pdf + 0.1] plot_data = [FigureFactory._make_half_violin( -yy, xx, fillcolor=fillcolor), FigureFactory._make_half_violin( yy, xx, fillcolor=fillcolor), FigureFactory._make_non_outlier_interval(d1, d2), FigureFactory._make_quartiles(q1, q3), FigureFactory._make_median(q2)] if rugplot: plot_data.append(FigureFactory._make_violin_rugplot( vals, max_pdf, distance=distance, color=fillcolor) ) return plot_data, plot_xrange
def _violin_no_colorscale(data, data_header, group_header, colors, use_colorscale, group_stats, height, width, title): """ Refer to FigureFactory.create_violin() for docstring. Returns fig for violin plot without colorscale. """ from plotly.graph_objs import graph_objs import numpy as np # collect all group names group_name = [] for name in data[group_header]: if name not in group_name: group_name.append(name) group_name.sort() gb = data.groupby([group_header]) L = len(group_name) fig = make_subplots(rows=1, cols=L, shared_yaxes=True, horizontal_spacing=0.025, print_grid=True) color_index = 0 for k, gr in enumerate(group_name): vals = np.asarray(gb.get_group(gr)[data_header], np.float) if color_index >= len(colors): color_index = 0 plot_data, plot_xrange = FigureFactory._violinplot( vals, fillcolor=colors[color_index] ) layout = graph_objs.Layout() for item in plot_data: fig.append_trace(item, 1, k + 1) color_index += 1 # add violin plot labels fig['layout'].update({'xaxis{}'.format(k + 1): FigureFactory._make_XAxis(group_name[k], plot_xrange)}) # set the sharey axis style fig['layout'].update( {'yaxis{}'.format(1): FigureFactory._make_YAxis('')} ) fig['layout'].update( title=title, showlegend=False, hovermode='closest', autosize=False, height=height, width=width ) return fig
def _validate_scatterplotmatrix(df, index, diag, colormap_type, **kwargs): """ Validates basic inputs for FigureFactory.create_scatterplotmatrix() :raises: (PlotlyError) If pandas is not imported :raises: (PlotlyError) If pandas dataframe is not inputted :raises: (PlotlyError) If pandas dataframe has <= 1 columns :raises: (PlotlyError) If diagonal plot choice (diag) is not one of the viable options :raises: (PlotlyError) If colormap_type is not a valid choice :raises: (PlotlyError) If kwargs contains 'size', 'color' or 'colorscale' """ if _pandas_imported is False: raise ImportError("FigureFactory.scatterplotmatrix requires " "a pandas DataFrame.") # Check if pandas dataframe if not isinstance(df, pd.core.frame.DataFrame): raise exceptions.PlotlyError("Dataframe not inputed. Please " "use a pandas dataframe to pro" "duce a scatterplot matrix.") # Check if dataframe is 1 column or less if len(df.columns) <= 1: raise exceptions.PlotlyError("Dataframe has only one column. To " "use the scatterplot matrix, use at " "least 2 columns.") # Check that diag parameter is a valid selection if diag not in DIAG_CHOICES: raise exceptions.PlotlyError("Make sure diag is set to " "one of {}".format(DIAG_CHOICES)) # Check that colormap_types is a valid selection if colormap_type not in VALID_COLORMAP_TYPES: raise exceptions.PlotlyError("Must choose a valid colormap type. " "Either 'cat' or 'seq' for a cate" "gorical and sequential colormap " "respectively.") # Check for not 'size' or 'color' in 'marker' of **kwargs if 'marker' in kwargs: FORBIDDEN_PARAMS = ['size', 'color', 'colorscale'] if any(param in kwargs['marker'] for param in FORBIDDEN_PARAMS): raise exceptions.PlotlyError("Your kwargs dictionary cannot " "include the 'size', 'color' or " "'colorscale' key words inside " "the marker dict since 'size' is " "already an argument of the " "scatterplot matrix function and " "both 'color' and 'colorscale " "are set internally.")
def 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 """ if 'auto_open' not in plot_options: plot_options['auto_open'] = False url = plot(figure_or_data, **plot_options) if isinstance(figure_or_data, dict): layout = figure_or_data.get('layout', {}) else: layout = {} embed_options = dict() embed_options['width'] = layout.get('width', '100%') embed_options['height'] = layout.get('height', 525) try: float(embed_options['width']) except (ValueError, TypeError): pass else: embed_options['width'] = str(embed_options['width']) + 'px' try: float(embed_options['height']) except (ValueError, TypeError): pass else: embed_options['height'] = str(embed_options['height']) + 'px' return tools.embed(url, **embed_options)
def save_as(cls, figure_or_data, filename, format=None, width=None, height=None, scale=None): """Save a image of the plot described by `figure_or_data` locally as `filename`. Valid image formats are 'png', 'svg', 'jpeg', and 'pdf'. The format is taken as the extension of the filename or as the supplied format. positional arguments: - figure_or_data: The figure dict-like or data list-like object that describes a plotly figure. Same argument used in `py.plot`, `py.iplot`, see https://plot.ly/python for examples - filename: The filepath to save the image to - format: 'png', 'svg', 'jpeg', 'pdf' - width: output width - height: output height - scale: Increase the resolution of the image by `scale` amount Only valid for PNG and JPEG images. example:
import plotly.plotly as py fig = {'data': [{'x': [1, 2, 3], 'y': [3, 1, 5], 'type': 'bar'}]} py.image.save_as(fig, 'my_image.png', scale=3) ``` """ # todo: format shadows built-in name (base, ext) = os.path.splitext(filename) if not ext and not format: filename += '.png' elif ext and not format: format = ext[1:] elif not ext and format: filename += '.' + format img = cls.get(figure_or_data, format, width, height, scale) f = open(filename, 'wb') f.write(img) f.close()
def upload(cls, meta, grid=None, grid_url=None): """ Upload Metadata to a Plotly grid. Metadata is any JSON-encodable object. For example, a dictionary, string, or list. Only one of `grid` or `grid_url` needs to be specified. `grid` is a plotly.grid_objs.Grid object that has already been uploaded to Plotly. `grid_url` is the URL of the Plotly grid to attach Metadata to. Usage example 1: Upload a grid to Plotly, then attach Metadata to it
from plotly.grid_objs import Grid, Column import plotly.plotly as py column_1 = Column([1, 2, 3], 'time') column_2 = Column([4, 2, 5], 'voltage') grid = Grid([column_1, column_2]) py.grid_ops.upload(grid, 'time vs voltage') # now attach Metadata to the grid meta = {'experment': 'GaAs'} py.meta_ops.upload(meta, grid=grid) ``` Usage example 2: Upload Metadata to an existing Plotly grid ``` import plotly.plotly as py grid_url = 'https://plot.ly/~chris/3143' meta = {'experment': 'GaAs'} py.meta_ops.upload(meta, grid_url=grid_Url) ``` """ grid_id = _api_v2.parse_grid_id_args(grid, grid_url) payload = { 'metadata': json.dumps(meta, cls=utils.PlotlyJSONEncoder) } api_url = _api_v2.api_url('grids') + '/{grid_id}'.format(grid_id=grid_id) res = requests.patch(api_url, data=payload, headers=_api_v2.headers(), verify=get_config()['plotly_ssl_verification']) return _api_v2.response_handler(res)
def _send_to_plotly(figure, **plot_options): """ """ fig = tools._replace_newline(figure) # does not mutate figure data = json.dumps(fig['data'] if 'data' in fig else [], cls=utils.PlotlyJSONEncoder) credentials = get_credentials() validate_credentials(credentials) username = credentials['username'] api_key = credentials['api_key'] kwargs = json.dumps(dict(filename=plot_options['filename'], fileopt=plot_options['fileopt'], world_readable=plot_options['world_readable'], sharing=plot_options['sharing'], layout=fig['layout'] if 'layout' in fig else {}), cls=utils.PlotlyJSONEncoder) # TODO: It'd be cool to expose the platform for RaspPi and others payload = dict(platform='python', version=version.__version__, args=data, un=username, key=api_key, origin='plot', kwargs=kwargs) url = get_config()['plotly_domain'] + "/clientresp" r = requests.post(url, data=payload, verify=get_config()['plotly_ssl_verification']) r.raise_for_status() r = json.loads(r.text) if 'error' in r and r['error'] != '': raise exceptions.PlotlyError(r['error']) # Check if the url needs a secret key if (plot_options['sharing'] == 'secret' and 'share_key=' not in r['url']): # add_share_key_to_url updates the url to include the share_key r['url'] = add_share_key_to_url(r['url']) if 'error' in r and r['error'] != '': print(r['error']) if 'warning' in r and r['warning'] != '': warnings.warn(r['warning']) if 'message' in r and r['message'] != '': print(r['message']) return r
def allocation_bar_plotly(allocation): ''' Modified from https://plot.ly/python/bar-charts/ Function to create interactive bar graph of our recommended portfolio allocation to a user using the Python package plotly. Input: allocation: recommended allocation (ex: 'Aggressive') Output: 'User-Allocation': Interactive plotly bar graph of allocation. First graph on results webpage ''' funds = list(ETF_ALLOCATION_DICT[allocation].keys()) percentages = [x * 100 for x in ETF_ALLOCATION_DICT[allocation].values()] data = [ go.Bar( x = funds, y = percentages, marker = dict( color = 'rgb(158,202,225)', line = dict( color = 'rgb(8,48,107)', width = 1.5 ), ), opacity = 0.6 ) ] layout = go.Layout( annotations = [ dict( x = xi, y = yi, text = str(yi) + '%', xanchor = 'center', yanchor = 'bottom', showarrow = False, ) for xi, yi in zip(funds, percentages)], title = 'Your Portfolio Allocation: ' + allocation, yaxis = dict( title = 'Percentage of Portfolio (%)'), xaxis = dict( title = 'Vanguard ETFs Ticker Symbols') ) fig = go.Figure(data = data, layout = layout) plot_url = py.plot(fig, filename = 'User-Allocation', auto_open = False)
def fund_performance_graph_plotly(allocation, wealth, hist_period = '10y'): ''' Modified from https://plot.ly/python/line-charts/ Create interactive line graph of performance of user's wealth invested in recommended allocation over past hist_period years using Python package plotly. Inputs: allocation: recommended allocation (ex: 'Aggressive') wealth: starting money that person can invest (ex: 1000) hist_period: string of years for historical portfolio prices (ex: '10y') Output: 'User-Portfolio-Performance': plotly interactive line graph of person's growth in wealth of recommended allocation over past hist_period years ''' connection = sqlite3.connect(DB) c = connection.cursor() # Get portfolio prices for proper hist_period and allocation pf_prices = c.execute("SELECT * FROM " + allocation + "_" + \ TIME_DICT[hist_period] + "_Year_PF;") prices = pf_prices.fetchall() # Get dates in datetime format for label purposes date_list = [datetime.datetime.strptime(x[0], "%Y-%m-%d %H:%M:%S") \ for x in prices] price_list = [x[1] * wealth for x in prices] data = [ go.Scatter( x = date_list, y = price_list, line = dict( color = ('rgb(8,48,107)') ) ) ] layout = go.Layout( title = 'Your Growth in Wealth Over Past 10 Years: ' + allocation, yaxis = dict( title = 'Your Portfolio Value ($)'), xaxis = dict( title = 'Year') ) fig = go.Figure(data = data, layout = layout) plot_url = py.plot(fig, filename = 'User-Portfolio-Performance', \ auto_open = False) annualized_return = (((price_list[-1] / price_list[0]) ** \ (1 / int(hist_period[:-1]))) - 1) * 100 connection.commit() connection.close return str("{0:.2f}".format(annualized_return)) + "%"
def graph_worst_year_plotly(allocation, wealth, worst_year_start_date, worst_year_end_date, hist_period = '10y'): ''' Modified from https://plot.ly/python/line-charts/ Create interative line graph of person's decrease in wealth over worst 12-month period over past hist_period years using Python package plotly. Inputs: allocation: recommended allocation (ex: 'Aggressive') wealth: starting money that person can invest (ex: 1000) worst_year_start_date: Start date of worst 12-month period worst_year_end_date: End date of worst 12-month period hist_period: string of years for historical portfolio prices (ex: '10y') Output: 'User-Worst-Year': Interactive plotly line graph of worst 12-month performance of user's wealth with recommended allocation ''' connection = sqlite3.connect(DB) c = connection.cursor() pf_prices = c.execute("SELECT * FROM " + allocation + "_" + \ TIME_DICT[hist_period] + "_Year_PF WHERE Date >= '" + \ worst_year_start_date + "' AND Date <= '" + worst_year_end_date + "';") prices = pf_prices.fetchall() # Get dates in datetime format date_list = [datetime.datetime.strptime(x[0], "%Y-%m-%d %H:%M:%S") \ for x in prices] price_list = [(x[1] / prices[0][1]) * wealth for x in prices] data = [ go.Scatter( x = date_list, y = price_list, line = dict( color = ('rgb(259, 0, 0)') ) ) ] layout = go.Layout( title = 'Worst 12-Month Performance Over Past 10 Years: ' + allocation, yaxis = dict( title = 'Your Portfolio Value ($)'), xaxis = dict( title = 'Date') ) fig = go.Figure(data = data, layout = layout) plot_url = py.plot(fig, filename = 'User-Worst-Year', auto_open = False) connection.commit() connection.close
def graph_best_year_plotly(allocation, wealth, best_year_start_date, best_year_end_date, hist_period = '10y'): ''' Modified from https://plot.ly/python/line-charts/ Function to create interative line graph of user's increase in wealth over best 12-month period over past hist_period years using Python package plotly. Inputs: allocation: recommended allocation (ex: 'Aggressive') wealth: starting money that person can invest (ex: 1000) best_year_start_date: Start date of best 12-month period best_year_end_date: End date of best 12-month period hist_period: string of years for historical portfolio prices (ex: '10y') Output: 'User-Best-Year': Interactive plotly line graph of best 12-month performance of user's wealth with recommended allocation ''' connection = sqlite3.connect(DB) c = connection.cursor() # Get portfolio prices for proper hist_period and allocation pf_prices = c.execute("SELECT * FROM " + allocation + "_" + \ TIME_DICT[hist_period] + "_Year_PF WHERE Date >= '" + \ best_year_start_date + "' AND Date <= '" + best_year_end_date + "';") prices = pf_prices.fetchall() # Get dates in datetime format date_list = [datetime.datetime.strptime(x[0], "%Y-%m-%d %H:%M:%S") \ for x in prices] price_list = [(x[1] / prices[0][1]) * wealth for x in prices] data = [ go.Scatter( x = date_list, y = price_list, line = dict( color = ('rgb(8,48,107)') ) ) ] layout = go.Layout( title = 'Best 12-Month Performance Over Past 10 Years: ' + allocation, yaxis = dict( title = 'Your Portfolio Value ($)'), xaxis = dict( title = 'Date') ) fig = go.Figure(data = data, layout = layout) plot_url = py.plot(fig, filename = 'User-Best-Year', auto_open = False) connection.commit() connection.close
def send_performance_update(slack_auth_id): slack_auth = SlackAuth.objects.get(pk=slack_auth_id) values = ranked_porfolios_team(slack_auth) scatters = [] messages = [] user_1, value_1 = values[0] dates, values_1 = last_week_values(user_1) dates.append(date.today()) values_1.append(value_1) scatters.append(go.Scatter(x=dates, y=values_1, name=user_1.natural_identifier)) messages.append("{} is leading with a portfolio value of ${:.2f}".format(user_1.natural_identifier, value_1)) if len(values) > 1: user_2, value_2 = values[1] _, values_2 = last_week_values(user_2) values_2.append(value_2) scatters.append(go.Scatter(x=dates, y=values_2, name=user_2.natural_identifier)) messages.append( "Just behind is {}, with a portfolio value of ${:.2f}".format(user_2.natural_identifier, value_2)) if len(values) > 2: user_3, value_3 = values[2] _, values_3 = last_week_values(user_3) values_3.append(value_3) scatters.append(go.Scatter(x=dates, y=values_3, name=user_3.natural_identifier)) messages.append( "{} is ranked 3rd, with a portfolio value of ${:.2f}".format(user_3.natural_identifier, value_3)) graph_url = plot_graph(scatters, 'Portfolio plot from {} to {}'.format(pretty_date(dates[0]), pretty_date(dates[-1]))) sm = SlackMessage(slack_auth.bot_access_token, slack_auth.general_channel_id) res = sm.send_image(graph_url) if json.loads(res.content)["ok"]: for message in messages: sm.send_text(message) return for user in slack_auth.talkuser_set.all(): if user.notification_frequency == NOTIFY_OFF: continue if user.notification_frequency == NOTIFY_WEEKLY: today = date.today() if today.weekday() != 4: continue sm = SlackMessage(slack_auth.bot_access_token, user.slack_id) sm.send_image(graph_url, actions=[{"text": "notification preferences", "value": "notification preferences"}]) for message in messages: sm.send_text(message)