我们从Python开源项目中,提取了以下17个代码示例,用于说明如何使用plotly.graph_objs.Margin()。
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 open_figure(self, fig, props): """Creates a new figure by beginning to fill out layout dict. The 'autosize' key is set to false so that the figure will mirror sizes set by mpl. The 'hovermode' key controls what shows up when you mouse around a figure in plotly, it's set to show the 'closest' point. Positional agurments: fig -- a matplotlib.figure.Figure object. props.keys(): [ 'figwidth', 'figheight', 'dpi' ] """ self.msg += "Opening figure\n" self.mpl_fig = fig self.plotly_fig['layout'] = go.Layout( width=int(props['figwidth'] * props['dpi']), height=int(props['figheight'] * props['dpi']), autosize=False, hovermode='closest') self.mpl_x_bounds, self.mpl_y_bounds = mpltools.get_axes_bounds(fig) margin = go.Margin( l=int(self.mpl_x_bounds[0] * self.plotly_fig['layout']['width']), r=int( (1-self.mpl_x_bounds[1]) * self.plotly_fig['layout']['width']), t=int((1-self.mpl_y_bounds[1]) * self.plotly_fig['layout'][ 'height']), b=int(self.mpl_y_bounds[0] * self.plotly_fig['layout']['height']), pad=0) self.plotly_fig['layout']['margin'] = margin
def create_layout(self): return Layout( title=self.plot_title, xaxis=dict(title='Tijd'), yaxis=dict(title='Kamervragen per week'), margin=Margin(t=20), legend=dict( x=0.01, y=1, bordercolor='#E2E2E2', bgcolor='#FFFFFF', borderwidth=2 ) )
def create_layout(self): return Layout( yaxis=dict(title='Kamervragen per maand'), margin=Margin(t=20, b=30), legend=dict( # x=0.01, # y=1, bordercolor='#E2E2E2', bgcolor='#FFFFFF', borderwidth=2 ) )
def create_layout(self): return Layout( yaxis=dict(title='Kamervragen per partijzetel per maand', range=[0, 6]), margin=Margin(t=20, b=30), legend=dict( # x=0.01, # y=1, bordercolor='#E2E2E2', bgcolor='#FFFFFF', borderwidth=2 ) )
def create_layout(self): return Layout( # title="Kamervraag Antwoordtijd vs Tijd", xaxis=dict(title='Kamervraag Ingediend [tijd]'), yaxis=dict(title='Antwoordtijd [dagen]'), autosize=False, width=1000, height=500, margin=Margin(t=20) )
def create_layout(self): return Layout( # title="Kamervragen per Week", xaxis=dict(title='Tijd'), yaxis=dict(title='Zetels per partij'), margin=Margin(t=20), legend=dict( # x=0.01, # y=1, bordercolor='#E2E2E2', bgcolor='#FFFFFF', borderwidth=2 ) )
def kamervragen_reply_time_per_party(parties, kamervraag_durations): fig = ff.create_distplot( kamervraag_durations, parties, # colors=colors, bin_size=1, show_curve=True, show_hist=False, show_rug=False ) xaxis = XAxis( range=[0, 60], ) fig['layout'].update(xaxis=xaxis) # fig['layout'].update(title="Kamervraag Antwoordtijd per Partij (probability distributie)") fig['layout'].update(xaxis=dict(title='Antwoordtijd [dagen]')) # fig['layout'].update(yaxis=dict(title='Kamervraag Ingediend [tijd]')) fig['layout'].update(height=700) legend = dict( # x=0.01, # y=1, bordercolor='#E2E2E2', bgcolor='#FFFFFF', borderwidth=2 ) fig['layout'].update(legend=legend) fig['layout'].update(margin=Margin(t=20)) return Plot.create_plot_html_default(figure_or_data=fig)
def kamervragen_reply_time_per_ministry(ministries, kamervraag_durations): fig = ff.create_distplot( kamervraag_durations, ministries, # colors=colors, bin_size=1, show_curve=True, show_hist=False, show_rug=False ) xaxis = XAxis(range=[0, 70]) fig['layout'].update(xaxis=xaxis) # fig['layout'].update(title="Kamervraag Antwoordtijd per Ministerie tijdens Rutte-II (KDE probability distributie)") fig['layout'].update(xaxis=dict(title='Antwoordtijd [dagen]')) # fig['layout'].update(yaxis=dict(title='')) fig['layout'].update(height=700) fig['layout'].update(margin=Margin(t=20)) legend = dict( # x=0.01, # y=1, bordercolor='#E2E2E2', bgcolor='#FFFFFF', borderwidth=2 ) fig['layout'].update(legend=legend) return Plot.create_plot_html_default(figure_or_data=fig)
def kamervragen_reply_time_per_year(years, kamervraag_durations): fig = ff.create_distplot( kamervraag_durations, years, # colors=colors, bin_size=1, show_curve=True, show_hist=False, show_rug=False ) xaxis = XAxis(range=[0, 60]) fig['layout'].update(xaxis=xaxis) # fig['layout'].update(title="Kamervraag Antwoordtijd per Ministerie tijdens Rutte-II (KDE probability distributie)") fig['layout'].update(xaxis=dict(title='Antwoordtijd [dagen]')) # fig['layout'].update(yaxis=dict(title='')) fig['layout'].update(height=700) fig['layout'].update(margin=Margin(t=20)) legend = dict( # x=0.01, # y=1, bordercolor='#E2E2E2', bgcolor='#FFFFFF', borderwidth=2 ) fig['layout'].update(legend=legend) return Plot.create_plot_html_default(figure_or_data=fig)
def _update_graph(map_style, region): dff = dataframe radius_multiplier = {'inner': 1.5, 'outer': 3} layout = go.Layout( title=metadata['title'], autosize=True, hovermode='closest', height=750, font=dict(family=theme['font-family']), margin=go.Margin(l=0, r=0, t=45, b=10), mapbox=dict( accesstoken=mapbox_access_token, bearing=0, center=dict( lat=regions[region]['lat'], lon=regions[region]['lon'], ), pitch=0, zoom=regions[region]['zoom'], style=map_style, ), ) data = go.Data([ # outer circles represent magnitude go.Scattermapbox( lat=dff['Latitude'], lon=dff['Longitude'], mode='markers', marker=go.Marker( size=dff['Magnitude'] * radius_multiplier['outer'], colorscale=colorscale_magnitude, color=dff['Magnitude'], opacity=1, ), text=dff['Text'], # hoverinfo='text', showlegend=False, ), # inner circles represent depth go.Scattermapbox( lat=dff['Latitude'], lon=dff['Longitude'], mode='markers', marker=go.Marker( size=dff['Magnitude'] * radius_multiplier['inner'], colorscale=colorscale_depth, color=dff['Depth'], opacity=1, ), # hovering behavior is already handled by outer circles hoverinfo='skip', showlegend=False ), ]) figure = go.Figure(data=data, layout=layout) return figure
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_thread_sizes(self): """Returns a plotly scatter/bubble graph showing the sizes (by message count) of chat thread over time. """ c = self.conn.cursor() c.execute('''SELECT gmail_thread_id, strftime('%Y-%m-%d', `date`) AS thread_date, COUNT(message_key) as thread_size, GROUP_CONCAT(DISTINCT `from`) AS participants FROM messages WHERE gmail_labels LIKE '%Chat%' GROUP BY gmail_thread_id;''') messages = [] marker_sizes = [] dates = [] descriptions = [] for row in c.fetchall(): messages.append(row[2]) marker_sizes.append(max(10, row[2]/5)) dates.append(row[1]) descriptions.append('Messages: ' + str(row[2]) + '<br>Date: ' + str(row[1]) + '<br>Participants:<br> - ' + str(row[3]).replace(',', '<br> - ') ) trace = pgo.Scatter( x=dates, y=messages, mode='markers', marker=dict( size=marker_sizes, ), text=descriptions ) layout_args = plotly_default_layout_options() layout_args['title'] = 'Chat Thread Sizes' layout_args['hovermode'] = 'closest' layout_args['height'] = 800 layout_args['margin'] = pgo.Margin(**layout_args['margin']) layout_args['xaxis']['title'] = 'Date' layout_args['yaxis']['title'] = 'Messages in thread' layout = pgo.Layout(**layout_args) return plotly_output(pgo.Figure(data=[trace], 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 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