我们从Python开源项目中,提取了以下18个代码示例,用于说明如何使用plotly.graph_objs.Bar()。
def ml_plot_feature_importances(importance_dict, title, plot=False): new_list = sorted(importance_dict.items(), key=lambda x: x[1], reverse=False) importance_keys = [] importance_values = [] for tuple in new_list: importance_keys.append(tuple[0]) importance_values.append(tuple[1]) fig = go.Bar( x=importance_values, y=importance_keys, orientation = 'h', name=title ) if plot == True: iplot(fig, config={'showLink' : False, 'displaylogo' : False, 'modeBarButtonsToRemove' : ['sendDataToCloud']}) else: return fig
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 generate_chart(self, _): try: import plotly import plotly.graph_objs as go data = [[0, 0, 0], [0, 0, 0]] ok, viol = self.results.get_ok_viol() x = ["OK (%d)" % ok, "Tampering (%d)" % viol] for ret in self.results: i = 1 if ret.is_tampering() else 0 data[i][0] += ret.is_aligned() data[i][1] += ret.is_disaligned() data[i][2] += ret.is_single() final_data = [go.Bar(x=x, y=[x[0] for x in data], name="Aligned"), go.Bar(x=x, y=[x[1] for x in data], name="Disaligned"), go.Bar(x=x, y=[x[2] for x in data], name="Single")] fig = go.Figure(data=final_data, layout=go.Layout(barmode='group', title='Call stack tampering labels')) plotly.offline.plot(fig, output_type='file', include_plotlyjs=True, auto_open=True) except ImportError: self.log("ERROR", "Plotly module not available")
def get_example_plot_html(number_of_points=30): import plotly.offline from plotly.graph_objs import Scatter, Layout, Bar, Margin data_x = [] data_y = [] for i in range(0, number_of_points): data_x.append(i) data_y.append(random.randint(-10, 10)) return plotly.offline.plot( figure_or_data={ "data": [Scatter(x=data_x, y=data_y)], "layout": Layout(title="Plot Title") }, show_link=False, output_type='div', include_plotlyjs=False, auto_open=False, )
def create_origin_histogram(origin: int) -> dict: """ This function calculates the histogram values for the specified column of data and returns a Plotly bar chart object for that data :param origin: The region of origin (1, 2 or 3) on which to create the histogram :return: A Plotly bar chart object to be added to the display """ df_slice = df.query('origin == {}'.format(origin)) origin_hist_data = get_cylinder_histogram_data(df_slice) return go.Bar( x=origin_hist_data[0], y=origin_hist_data[1], name=origin ) # Create a list of the bar charts by origin and add them to the notebook as a # single plot
def build_grouped_bar_chart(chart_data): print "Building Chart with data: " + str(chart_data) py.sign_in(config.PLOTLY_USERNAME, config.PLOTLY_PASSWORD) bars = [] for name in chart_data['groups']: x_data_list = chart_data["x"]["data"][name] y_data_list = chart_data["y"]["data"][name] bar = go.Bar( x=x_data_list, y=y_data_list, name=name ) bars.append(bar) chart_layout = dict( title=chart_data['title'], xaxis=dict(title=chart_data['x']['label'], tickangle=-45, rangemode='tozero'), yaxis=dict(title=chart_data['y']['label'], rangemode='tozero') ) chart = go.Figure(data=bars, layout=chart_layout) filename = id_generator.generate_chart_image_filename() filepath = config.LOCAL_CHARTS_DIR_PATH + filename py.image.save_as(chart, filename=filepath) s3.upload_file(filename, filepath, config.S3_USER_CHARTS_BUCKET) download_url = s3.get_download_url( bucket=config.S3_USER_CHARTS_BUCKET, path=filename, expiry=603148) cleanup_file(filepath) return download_url
def generate_group_bar_charts(y_values, x_values, trace_header, output_directory, output_file_name): """ Plots multiple bar graphs on same graph example usage: generate_group_bar_charts([ [5.10114882, 5.0194652482, 4.9908093076], [4.5824497358, 4.7083614037, 4.3812775722], [2.6839471308, 3.0441476209, 3.6403820447] ], ['#kubuntu-devel', '#ubuntu-devel', '#kubuntu'], ['head1', 'head2', 'head3'], '/home/rohan/Desktop/', 'multi_box' ) Args: x_in (list of int): x_axis data y_in (list of int): y_axis data output_drectory(str): location to save graph output_file_name(str): name of the image file to be saved Returns: null """ data = [ go.Bar( x=x_values, y=y_values[i], name=trace_header[i] ) for i in range(len(y_values)) ] layout = go.Layout( barmode='group' ) fig = go.Figure(data=data, layout=layout) py.image.save_as(fig, output_directory + "/" + output_file_name+".png")
def skew_plot(skew_list): data = [go.Bar( x=['True', 'False'], y=[skew_list[1], skew_list[2]], )] layout = go.Layout(title="Skew Balance", width=300, height=300) fig = go.Figure(data=data, layout=layout) iplot(fig, config={'showLink' : False, 'displaylogo' : False, 'modeBarButtonsToRemove' : ['sendDataToCloud']})
def plotly_metric_plot(alg_names, x_axis, y_axis, color_list=None, title=None): #TODO: Check if the x axis and y axis are the same length if color_list == None: color_list = ['rgb(244, 167, 66)', 'rgb(49,130,189)', 'rgb(244, 65, 86)','rgb(100, 201, 137)'] barList = [] # List of bar plots to be plotted i = 0 for name in alg_names: y_axis_holder = [] #PROBLEM: The dict entries may be out of order. This would cause the # incorrect entries to be graphed. for metric_dict in y_axis: y_axis_holder.append(metric_dict[name]) barList.append( go.Bar( x=x_axis, y=y_axis_holder, name=name, marker=dict( color=color_list[i], ))) i += 1 layout = go.Layout(barmode='group', legend=dict(x=20.0, y=20.0), title = title) fig = go.Figure(data=barList, layout=layout) return fig
def barDiv(slope, value, suffix, bar_suffix, bar_format, color, layoutRange): infoText=(str(value) + str(suffix)) tendancy = (slope*timedelta(days=7).total_seconds()) # ToDO: round instead if tendancy > 0: tendancyText="+" tendancyOrigin=0.825 else: tendancyText="" tendancyOrigin=0.675 tendancyText+=str(bar_format % tendancy)+' '+bar_suffix tendancyPosition=tendancyOrigin+((1.2*tendancy)/layoutRange[1]/4) # Bar barChart = go.Bar( x=['tendancy',], y=[float(tendancy),], name="Bar", showlegend=False, hoverinfo="none", marker=dict(color=color), ) # Layout layout = go.Layout( xaxis=dict(showticklabels=False, autotick=False, showgrid=False, zeroline=True, fixedrange=True, domain=[0, 1], ), yaxis=dict(showticklabels=False, autotick=False, showgrid=False, zeroline=False, fixedrange=True, domain=[0.5, 1], range=layoutRange, ), annotations=[ dict(xref='paper', yref='paper', x=0.5, y=0, text=infoText, font=dict(size='20', color='#ffffff'), xanchor='center', yanchor='middle', showarrow=False), dict(xref='paper', yref='paper', x=0.5, y=tendancyPosition, text=tendancyText, font=dict(size='14', color='#ffffff'), xanchor='center', yanchor='middle', showarrow=False), ], height=260, width=120, margin=dict(l=0, r=0, t=40, b=40, autoexpand=False), plot_bgcolor="rgba(0,0,0,0)", paper_bgcolor="rgba(0,0,0,0)" ) # Build HTML div div = plotly.plot(dict(data=[barChart], layout=layout), include_plotlyjs=False, show_link=False, output_type='div') return div #----------------------------------------------------------------------------------------- # Get arguments
def plot_collection( data_frame, title, color_column='boarding_method', color_values=None ): data_frame = data_frame.sort_values(by='trial_label') times = data_frame['elapsed'] labels = data_frame['trial_label'] colors = [] if color_values is None: color_values = dict( r='rgba(204, 204, 204, 0.8)', b=plotting.get_color(0, 0.8), default=plotting.get_color(1, 0.8) ) for index, row in data_frame.iterrows(): method = row[color_column] colors.append( color_values.get(method, color_values.get('default')) ) project.display.plotly( data=go.Bar( y=times, x=labels, marker=dict(color=colors), ), layout=plotting.create_layout( title=title, y_label='Boarding Time (s)', x_label='Trial', y_bounds=[times.min() - 10, times.max() + 10] ), scale=0.75 )
def top_recipients(self, limit=10): """Returns a bar graph showing the top `limit` number of recipients of emails sent. Keyword arguments: limit -- Number of recipients to include. """ c = self.conn.cursor() c.execute('''SELECT address, COUNT(r.message_key) AS message_count FROM recipients AS r LEFT JOIN messages AS m ON(m.message_key = r.message_key) WHERE m.gmail_labels LIKE '%Sent%' GROUP BY address ORDER BY message_count DESC LIMIT ?''', (limit,)) addresses = OrderedDict() longest_address = 0 for row in c.fetchall(): addresses[row[0]] = row[1] longest_address = max(longest_address, len(row[0])) data = dict( x=addresses.values(), y=addresses.keys(), marker=dict( color=self.config.get('color', 'primary_light'), line=dict( color=self.config.get('color', 'primary'), width=1, ), ), orientation='h', ) layout = plotly_default_layout_options() layout['margin']['l'] = longest_address * self.config.getfloat('font', 'size')/1.55 layout['margin'] = pgo.Margin(**layout['margin']) layout['title'] = 'Top ' + str(limit) + ' Recipients' layout['xaxis']['title'] = 'Emails sent to' layout['yaxis']['title'] = 'Recipient address' return plotly_output(pgo.Figure(data=[pgo.Bar(**data)], layout=pgo.Layout(**layout)))
def top_senders(self, limit=10): """Returns a bar graph showing the top `limit` number of senders of emails received. Keyword arguments: limit -- Number of senders to include. """ c = self.conn.cursor() c.execute('''SELECT `from`, COUNT(message_key) AS message_count FROM messages WHERE gmail_labels NOT LIKE '%Sent%' AND gmail_labels NOT LIKE '%Chat%' GROUP BY `from` ORDER BY message_count DESC LIMIT ?''', (limit,)) addresses = OrderedDict() longest_address = 0 for row in c.fetchall(): addresses[row[0]] = row[1] longest_address = max(longest_address, len(row[0])) data = dict( x=addresses.values(), y=addresses.keys(), marker=dict( color=self.config.get('color', 'primary_light'), line=dict( color=self.config.get('color', 'primary'), width=1, ), ), orientation='h', ) layout = plotly_default_layout_options() layout['margin']['l'] = longest_address * self.config.getfloat('font', 'size')/1.55 layout['margin'] = pgo.Margin(**layout['margin']) layout['title'] = 'Top ' + str(limit) + ' Senders' layout['xaxis']['title'] = 'Emails received from' layout['yaxis']['title'] = 'Sender address' return plotly_output(pgo.Figure(data=[pgo.Bar(**data)], layout=pgo.Layout(**layout)))
def talk_days(self): """Returns a stacked bar chart showing percentage of chats and emails on each day of the week. """ c = self.conn.cursor() c.execute('''SELECT strftime('%w', `date`) AS dow, COUNT(CASE WHEN gmail_labels LIKE '%Chat%' THEN 1 ELSE NULL END) AS talk_messages, COUNT(CASE WHEN gmail_labels NOT LIKE '%Chat%' THEN 1 ELSE NULL END) AS email_messages FROM messages WHERE dow NOTNULL GROUP BY dow;''') talk_percentages = OrderedDict() talk_messages = OrderedDict() email_percentages = OrderedDict() email_messages = OrderedDict() for row in c.fetchall(): dow = calendar.day_name[int(row[0]) - 1] # sqlite strftime() uses 0 = SUNDAY. talk_percentages[dow] = str(round(float(row[1]) / sum([row[1], row[2]]) * 100, 2)) + '%' email_percentages[dow] = str(round(float(row[2]) / sum([row[1], row[2]]) * 100, 2)) + '%' talk_messages[dow] = row[1] email_messages[dow] = row[2] chats_trace = pgo.Bar( x=talk_messages.keys(), y=talk_messages.values(), text=talk_percentages.values(), name='Chat messages', marker=dict( color=self.config.get('color', 'primary'), ), ) emails_trace = pgo.Bar( x=email_messages.keys(), y=email_messages.values(), text=email_percentages.values(), name='Email messages', marker=dict( color=self.config.get('color', 'secondary'), ), ) layout = plotly_default_layout_options() layout['barmode'] = 'stack' layout['margin'] = pgo.Margin(**layout['margin']) layout['title'] = 'Chat (vs. Email) Days' layout['xaxis']['title'] = 'Day of the week' layout['yaxis']['title'] = 'Messages exchanged' return plotly_output(pgo.Figure(data=[chats_trace, emails_trace], layout=pgo.Layout(**layout)))
def talk_top_chatters(self, limit=10): """Returns a plotly bar graph showing top chat senders with an email comparison. Keyword arguments: limit -- How many chat senders to return. """ c = self.conn.cursor() c.execute('''SELECT `from`, COUNT(CASE WHEN gmail_labels LIKE '%Chat%' THEN 1 ELSE NULL END) AS talk_messages, COUNT(CASE WHEN gmail_labels NOT LIKE '%Chat%' THEN 1 ELSE NULL END) AS email_messages FROM messages WHERE `from` NOT LIKE ? GROUP BY `from` ORDER BY talk_messages DESC LIMIT ?;''', ('%' + self.owner_email + '%', limit,)) chats = OrderedDict() emails = OrderedDict() longest_address = 0 for row in c.fetchall(): chats[row[0]] = row[1] emails[row[0]] = row[2] longest_address = max(longest_address, len(row[0])) chats_trace = pgo.Bar( x=chats.keys(), y=chats.values(), name='Chat messages', marker=dict( color=self.config.get('color', 'primary'), ), ) emails_trace = pgo.Bar( x=emails.keys(), y=emails.values(), name='Email messages', marker=dict( color=self.config.get('color', 'secondary'), ), ) layout = plotly_default_layout_options() layout['barmode'] = 'grouped' layout['height'] = longest_address * 15 layout['margin']['b'] = longest_address * self.config.getfloat('font', 'size') / 2 layout['margin'] = pgo.Margin(**layout['margin']) layout['title'] = 'Top ' + str(limit) + ' Chatters' layout['xaxis']['title'] = 'Sender address' layout['yaxis']['title'] = 'Messages received from' return plotly_output(pgo.Figure(data=[chats_trace, emails_trace], layout=pgo.Layout(**layout)))
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 get_context_data(self, **kwargs): import plotly.offline from plotly.graph_objs import Layout, Bar, Margin context = super().get_context_data(**kwargs) domains = self.get_domains() x = [] y = [] domains_selection = [] min_mentions = 10 for domain in domains: if domain[1] < min_mentions: break domains_selection.append(domain) for domain in reversed(domains): if domain[1] < 20: continue if domain[0] == 'zoek.officielebekendmakingen.nl': continue x.append(domain[0]) y.append(domain[1]) data = [Bar( x=y, y=x, orientation='h' )] plot_html = plotly.offline.plot( figure_or_data={ "data": data, "layout": Layout( title="Vermeldingen per website", autosize=True, height=1200, margin=Margin( l=200, r=50, b=40, t=40, pad=4 ), ) }, show_link=False, output_type='div', include_plotlyjs=False, auto_open=False, ) context['plot_html'] = mark_safe(plot_html) context['domains'] = domains_selection context['min_mentions'] = min_mentions return context
def tornadoPlot(self, simId, scenario, resultName, tornadoType, sliderValue, selectedData): corrDF = self.getCorrDF(simId, scenario, resultName) if tornadoType == 'normalized': squared = corrDF.spearman ** 2 corrDF['normalized'] = squared / squared.sum() corrDF['sign'] = 1 corrDF.ix[(corrDF.spearman < 0), 'sign'] = -1 corrDF['value'] = corrDF.normalized * corrDF.sign # normalized squares with signs restored plotColumn = 'value' title = 'Normalized rank correlation' else: plotColumn = 'spearman' title = 'Rank correlation' varCount = min(20, len(corrDF)) # if sliderValue is None else len(corrDF[corrDF['abs'] >= sliderValue])) varNames = list(reversed(corrDF.index[:varCount])) values = list(reversed(corrDF[plotColumn][:varCount])) plotData = go.Bar( orientation='h', x=values, y=varNames, width=0.6, marker=dict( color=getColor('TornadoPlotBar'), line=dict( color=getColor('TornadoPlotLine'), width=0), ), textposition='none', name='Rank correlation', hoverinfo='skip', # prevents hover events ) layout = updateStyle('Plot', title=title, margin=updateStyle('PlotMargin', l=200), xaxis=dict(range=[-1, 1]), dragmode='select') figure = dict(data=[plotData], layout=layout) return figure