def channel_analytics(message): # Slack user web API token token = os.environ.get('USER_TOKEN') users_endpoint=urlopen('https://slack.com/api/users.list?token='+token+'&pretty=1').read() users_endpoint_result = json.loads(users_endpoint) users_arr = [] for i in users_endpoint_result['members']: data = [] data.append(i['name']) data.append(i['id']) users_arr.append(data) count_dict = defaultdict(int) len_user_arr = len(users_arr) channel_endpoint = urlopen('https://slack.com/api/channels.history?token='+token+'&channel=C1R5Z1FT3&count=1000&pretty=1').read() channel_endpoint_result = json.loads(channel_endpoint) for i in channel_endpoint_result['messages']: for j in range(0,len_user_arr): if i['user'] == users_arr[j][1]: count_dict[users_arr[j][1]] += 1 pprint(count_dict) pprint(count_dict[users_arr[0][1]]) labels=[users_arr[0][0],users_arr[1][0],users_arr[2][0],users_arr[3][0],users_arr[4][0],users_arr[5][0],users_arr[6][0],users_arr[7][0]] values=[count_dict[users_arr[0][1]],count_dict[users_arr[1][1]],count_dict[users_arr[2][1]],count_dict[users_arr[3][1]],count_dict[users_arr[4][1]],count_dict[users_arr[5][1]],count_dict[users_arr[6][1]], count_dict[users_arr[7][1]]] trace=go.Pie(labels=labels,values=values) py.iplot([trace]) message.reply('https://plot.ly/~simmeringc/39/')
def graph(lstmin, lstmax, lstmean, lstname): """printgraph""" trace0 = go.Scatter( x = lstname, y = lstmin, name = 'คะเเนนน้อยสุด', mode = 'lines+markers', line = dict( color = ('rgb(255, 0, 0)'), width = 2) ) trace1 = go.Scatter( x = lstname, y = lstmax, name = 'คะเเนนมากสุด', mode = 'lines+markers', line = dict( color = ('rgb(255, 255, 0)'), width = 2) ) trace2 = go.Scatter( x = lstname, y = lstmean, name = 'คะเเนนเฉลี่ย', mode = 'lines+markers', line = dict( color = ('rgb(51, 255, 51)'), width = 2) ) data = [trace0, trace1, trace2] layout = dict(title = 'คะเเนนของเเต่ละคณะ', yaxis = dict(title = 'คะเเนน'), ) fig = dict(data=data, layout=layout) py.iplot(fig, filename='styled-line')
def ribbon2(spectra, alpha, title): import plotly.plotly as py import plotly.graph_objs as go import numpy as np traces = [] y_raw = spectra[:, 0] sample_size = spectra.shape[1] for i in range(0, sample_size): print i z_raw = spectra[:, i] x = [] y = [] z = [] ci = int(255/sample_size*i) # ci = "color index" for j in range(0, len(z_raw)): z.append([z_raw[j], z_raw[j]]) y.append([alpha[j], alpha[j]]) x.append([i, i+1]) traces.append(dict( xsrc="xsrc", z=z, x=x, y=y, colorscale=[ [i, 'rgb(%d,%d,255)'%(ci, ci)] for i in np.arange(0,1.1,0.1) ], showscale=False, type='surface', )) #traces = traces[::-1] fig = go.Figure( data=traces, layout={'title':'Pyramid Gradient MFS'}) py.iplot(fig, filename='ribbon-plot-python')
def plot_graph(var1, var2): ''' input: Receives two string variables from django Receives scatter, list of 9 lists, each interior list with an x, y, and neighborhood get_scatter_array Receives colors, an ordered list corresponding with the interior lists of scatter output: Creates a trace for each of 9 lists , append to data file and creating scatterplot ''' scatter, colors = get_scatter_array(var1, var2) graph_title = var1 + ' vs ' + var2 data = [] for i, val in enumerate(scatter): trace = create_trace(i, val, colors) if trace: data.append(trace) layout = go.Layout( showlegend = False, title = graph_title, hovermode = 'closest', xaxis = dict( title = var1, ticklen = 5, zeroline = False, gridwidth = 2, ), yaxis = dict( title = var2, ticklen = 5, gridwidth = 2, ), ) fig = go.Figure(data=data, layout=layout) py.iplot(fig, filename='healthy-neighborhoods')
def plot(self): fig = pytls.make_subplots(shared_xaxes=True, rows=30, cols=1) for colname in self.normalized.columns.values: fig.append_trace({'x': self.normalized.index, 'y': self.normalized[colname], 'type':'scatter', 'name': self.PRETTYCOLNAMES[colname][0]}, self.PRETTYCOLNAMES[colname][1], 1) py.iplot(fig,filename='biostampy')
def setup_metric_streams(self, local_stream_ids, metric_name, num_channels): for i in range(num_channels): stream_id = local_stream_ids[i] self.stream_ids.append(stream_id) py_stream = py.Stream(stream_id) py_stream.open() self.py_streams.append(py_stream) go_stream = go.Stream(token=stream_id, maxpoints=self.max_points) self.go_streams.append(go_stream) traces = [] for i in range(num_channels): channel_name = "channel_%s" % i go_stream = self.go_streams[i] trace = go.Scatter( x=[], y=[], mode='splines', stream=go_stream, name=channel_name ) traces.append(trace) data = go.Data(traces) layout = go.Layout(title=metric_name) fig = go.Figure(data=data, layout=layout) py.iplot(fig, filename=metric_name)
def vignereLength(ciphertext, minv=2, maxv=50, filename=None): lowest_distance = 1000000 best_length = 0 lengths = [] scores = [] for ks in range(minv, maxv): distance = vignereScore(ks) lengths.append(ks) scores.append(distance) # print("size={} dist={}".format(ks, distance)) if distance < lowest_distance: best_length = ks lowest_distance = distance if filename: fig = dict( data = [go.Scatter( x = lengths, y = scores )], layout = dict( title = "Averaged Hamming distance between ciphertext blocks ", xaxis = dict(title = 'Line'), yaxis = dict(title = 'Hamming distance (avg)'), ) ) py.iplot(fig, filename=filename) return best_length
def value_investing_investigate(filename): with open('tools/plotly_credentials.json', 'r') as creds: credentials = json.load(creds) py.sign_in(credentials['plotly']['username'], credentials['plotly']['key']) # plot top industries (selected by market cap), make sure # enough to colors in colors_array of make_plotly_data fun top = 10 stats = pd.read_csv(filename + '.csv') top_sorted = get_most_popular('industry', stats, top) title = "Value Investing Strategy (find companies with pb <1 and peg <1)." x_title = "Price/Book Value" y_title = "Price/Earnings/Growth" data = make_plotly_data(stats, top_sorted) layout = set_layout(title, x_title, y_title) fig = go.Figure(data=data, layout=layout) fig = hover_over_text(fig, stats, top_sorted) fig = add_data_source_note(fig) py.iplot(fig, filename=filename)
def plotly_graph(self, gx, filename, image_filename): axis=dict(showbackground=False, showline=False, zeroline=False, showgrid=False, showticklabels=False, title='') trace1=go.Scatter3d(x=gx.Xe,y=gx.Ye,z=gx.Ze, mode='lines', line=go.Line(color='rgb(125,125,125)', width=1), hoverinfo='none') trace2=go.Scatter3d(x=gx.Xn,y=gx.Yn,z=gx.Zn, mode='markers',name='artwork', marker=go.Marker(symbol='diamond',size=6,color=gx.group,colorscale='Viridis', line=go.Line(color='rgb(50,50,50)', width=0.5)), text=gx.labels, hoverinfo='text',) layout_grid = go.Layout(title="", width=1000, height=1000, showlegend=False, scene=go.Scene( xaxis=go.XAxis(axis),yaxis=go.YAxis(axis),zaxis=go.ZAxis(axis)), margin=go.Margin(t=35,b=0), hovermode='closest', paper_bgcolor='rgb(233,233,233)', annotations=go.Annotations([ go.Annotation( showarrow=False, text="", xref='paper',yref='paper',x=0,y=0.01,xanchor='left',yanchor='bottom', font=go.Font(size=14) ) ]), ) data=go.Data([trace1, trace2]) fig=go.Figure(data=data, layout=layout_grid) py.iplot(fig, filename=filename) py.image.save_as(fig, filename=image_filename) return fig
def plot_pca(self, ncomponents=6): pca_df = self.get_pca_dataframe(ncomponents=ncomponents) fig = pytls.make_subplots(shared_xaxes=True, rows=ncomponents, cols=1) for col in range(0, ncomponents): fig.append_trace({'x': pca_df.index, 'y': pca_df[col], 'type':'scatter', 'name': ("Component " + str(col+1))}, col+1, 1) py.iplot(fig, filename=('biostampy-pca:' + str(ncomponents)))
def make_graph(data, filename, layout=go.Layout()): fig = go.Figure(data=data, layout=layout) if ONLINE: py.iplot(fig, filename=filename) else: filename = './graphs/{}.png'.format(filename) py.image.save_as(fig, filename=filename)
def plotly_daily_by_week(): plotly_name = 'My Electricity Use Visualizations/Heatmap Daily by Week' daily_totals = pd.DataFrame(np.zeros([len(elec['USAGE'].resample('W-MON', how='sum')),7]), index = elec['USAGE'].resample('W-MON', how='sum').index) # Drop the last two rows to ensure each row is a full week daily_totals = pd.DataFrame(np.zeros([len(elec['USAGE'].resample('W-MON', how='sum')),7]), index = elec['USAGE'].resample('W-MON', how='sum').index) daily_totals.drop(daily_totals.tail(2).index, inplace=True) for j in range(len(daily_totals)): for i in range(7): #print i, j daily_totals[i].ix[j] = elec['USAGE'].resample('D', how='sum').ix[(daily_totals.ix[j].name + pd.to_timedelta(i, unit='d'))] daily_totals.columns = ['Mon','Tues','Wed','Thurs','Fri','Sat','Sun'] daily_totals.sort_index(ascending=False, inplace=True) data = Data([ Heatmap( y = daily_totals.columns, x = daily_totals.index, z = np.transpose(np.array(daily_totals)), colorscale='YIOrRd', reversescale=True, colorbar = ColorBar( title = 'Kilowatt-Hours', titleside='right' ) ) ]) layout = Layout( yaxis = YAxis(tickangle=0), autosize = False, width = 800, height = 300, margin=Margin( l=50, r=50, b=50, t=50, pad=4 ) ) #plot_url = py.plot(data, layout=layout, filename='Daily_Totals_by_Week') fig = Figure(data=data, layout=layout) py.iplot(fig, filename=plotly_name) print "Sent to Plotly: ", plotly_name
def build_plotly_table(plotly_df): plotly_df = plotly_df[['Passer_Name', 'Receiver_Name', 'Assists']] plotly_df = plotly_df.sort_values(by='Assists', ascending=False) plotly_df = plotly_df.head(25) plotly_df.columns = ['Passer', 'Receiver', 'Assists'] plotly_df = plotly_df.as_matrix() plotly_df = np.insert(plotly_df, 0, np.array(('Passer', 'Receiver', 'Assists')), 0) table = FF.create_table(plotly_df) py.iplot(table, filename='assist_pairs')
def plotly_notebook(traces, filename=None, title=None): if filename is None: filename = "plotly_graph" fig = Figure(data=Data(traces), layout=Layout(title=title, plot_bgcolor="rgb(217, 217, 217)", showlegend=True, xaxis=XAxis(showgrid=False, zeroline=False, showticklabels=False), yaxis=YAxis(showgrid=False, zeroline=False, showticklabels=False))) py.iplot(fig, filename=filename)
def fig1(): trace1 = Scatter( x=df['LifeExpectancy'], y=df['GNP'], text=country_names, mode='markers' ) layout = Layout( xaxis=XAxis(title='Life Expectancy'), yaxis=YAxis(type='log', title='GNP') ) data = Data([trace1]) fig = Figure(data=data, layout=layout) py.iplot(fig, filename='world GNP vs life expectancy')
def graph_vector_space(self): """ 3D Scatter plot of first 3 word features with Plotly""" vocab = OrderedDict(sorted(self.vocabulary.items(), key = lambda t: t[1])) W_D = np.concatenate((self.WI, self.D), axis=0) text = vocab.keys() for i in range(len(self.sentences)): text.append('S' + str(i+1)) trace1 = Scatter3d( x = W_D.T[0], y = W_D.T[1], z = W_D.T[2], mode ='markers+text', text = text, marker = Marker( size = 8, line = Line( color = 'rgba(217, 217, 217, 0.14)', width = 0.5 ), opacity = 0.8 ) ) data = Data([trace1]) layout = Layout( margin = Margin( l = 0, r = 0, b = 0, t = 0 ) ) fig = Figure(data = data, layout = layout) return py.iplot(fig)
def graph_vector_space(self): """ 3D Scatter plot of first 3 word features with Plotly""" vocab = OrderedDict(sorted(self.vocabulary.items(), key = lambda t: t[1])) trace1 = Scatter3d( x = self.WI.T[0], y = self.WI.T[1], z = self.WI.T[2], mode ='markers+text', text = vocab.keys(), marker = Marker( size = 8, line = Line( color = 'rgba(217, 217, 217, 0.14)', width = 0.5 ), opacity = 0.8 ) ) data = Data([trace1]) layout = Layout( margin = Margin( l = 0, r = 0, b = 0, t = 0 ) ) fig = Figure(data = data, layout = layout) return py.iplot(fig)
def pyplot(fig, ci=True, legend=True): # Convert mpl fig obj to plotly fig obj, resize to plotly's default py_fig = tls.mpl_to_plotly(fig, resize=True) # Add fill property to lower limit line if ci == True: style1 = dict(fill='tonexty') # apply style py_fig['data'][2].update(style1) # Change color scheme to black py_fig['data'].update(dict(line=Line(color='black'))) # change the default line type to 'step' py_fig['data'].update(dict(line=Line(shape='hv'))) # Delete misplaced legend annotations py_fig['layout'].pop('annotations', None) if legend == True: # Add legend, place it at the top right corner of the plot py_fig['layout'].update( showlegend=True, legend=Legend( x=1.05, y=1 ) ) # Send updated figure object to Plotly, show result in notebook return py.iplot(py_fig)
def drop_down_scatter(data_df): parser = {} loop_list = [] #list([dict(arg=[],lable=,method='restyle',),dict(,,,)]) #stopped here default_list = [False] * len(data_df.columns.tolist()) plotly_tuple = () counter=0 button_list = [] #for column in data_df.columns for column in data_df.columns: temp_df = data_df[column].dropna() name = 'trace' + str(counter) parser[name] = Scatter( x=temp_df.index, y=temp_df.values, name=temp_df.name) loop_list.append(parser[name]) counter = counter + 1 counter = 0 loop_list_menus = [] for column in data_df.columns: loop_list_menus = default_list.copy() loop_list_menus[counter] = True counter = counter + 1 button_list.append(dict(args=['visible', loop_list_menus],label=column,method='restyle')) layout = Layout(title='C1 Ratio Adj. 1st of Month Roll',autosize=False,margin=go.Margin(l=5,r=50,pad=0), updatemenus=list([dict( x=-0.5, y=5, yanchor='top', buttons=button_list)])) fig = Figure(data=loop_list,layout=layout) py.iplot(fig,filename='drop_down_chart')
def scatter_df_plotly(df, x, y, z, text_fnct = hover_all, streaming = True, filename= None): """ a wrapper function for `plotlyi.graph_objs.Scatter` on `pandas.Dataframe` usage: ===== d """ layout = Layout( title='colour map: %s' % z, hovermode='closest', # (!) hover -> closest data pt showlegend=False, # remove legend (info in hover) autosize=False, # turn off autosize width=650, # plot width height=500, # plot height xaxis=XAxis( title= x, titlefont=Font( family='Courier New, monospace', size=14, color='#7f7f7f' ) ), yaxis=YAxis( title= y, titlefont=Font( family='Courier New, monospace', size=14, color='#7f7f7f' ) ) ) # print('marker sizes:') # print(rescale_marker(df[z], square = True)) SC = Scatter(x=df[x], y = df[y], mode='markers', marker = Marker(size = rescale_marker(df[z], square = True), color = df[z], colorscale = 'Jet', sizeref = 1, sizemode = 'area') ) FIG = Figure(data = Data([SC]) , layout=layout ) #FIG['layout'].update( ) if text_fnct is not None: FIG['data'][0].update(text = \ df.apply(lambda ds: text_fnct(ds, x=x, y=y,z=z), axis = 1).tolist() ) if not streaming: if filename is not None: return py.plot(FIG, filename = filename) else: return py.plot(FIG) else: return py.iplot(FIG)
def main(): py.sign_in('rowan.coleman', '9m36u5ly1v') time_range = datetime.datetime.now() - datetime.timedelta(days=3) filename = 'evohome.db' filepath = os.path.join(sys.path[0],filename) engine = create_engine('sqlite:///%s' % filepath) Base = automap_base() Base.prepare(engine,reflect=True) temp = Base.classes.temperatures session = Session(engine) graph_data = [] #Find all uniqe zones for zone_row in session.query(temp.name,temp.thermostat,temp.id).distinct(): if zone_row.thermostat == 'DOMESTIC_HOT_WATER': zone_name = 'Hot Water' else: zone_name = zone_row.name print zone_name #Find temperatures within the time range x = [] temp_y = [] setpoint_y = [] for row in session.query(temp).filter(temp.timestamp >= time_range).filter(temp.id == zone_row.id): #print row.timestamp,row.temp,row.setpoint x.append(row.timestamp) temp_y.append(row.temp) setpoint_y.append(row.setpoint) temp_trace = go.Scatter(x = x, y = temp_y, mode = 'lines', name = zone_name) graph_data.append(temp_trace) #if zone_row.thermostat == 'DOMESTIC_HOT_WATER': #continue #setpoint_trace = go.Scatter(x = x, y = setpoint_y, mode = 'lines', name = zone_name + '-setpoint', opacity=0.5) #graph_data.append(setpoint_trace) #print graph_data py.iplot(graph_data, filename='line-mode')
def plot_bar(data_df): new_df = pd.DataFrame(data=data_df.values[0], index=data_df.columns.tolist(),columns=['1 year return']).sort(columns='1 year return',ascending=False) data = [go.Bar( x= new_df.index.values, y= new_df[new_df.columns[0]].values #orientation = 'h' )] layout = go.Layout(title='1 Year Total Return as of ' + data_df.index[0].strftime('%m-%d-%Y'), yaxis=dict(tickformat = '%')) fig = go.Figure(data=data,layout=layout) py.iplot(fig,filename='one_yr_total_return')
def plotlysurface(zdata, extent, mpl_axes, mpl_cb, colorscale): x = np.linspace(extent[0], extent[1], zdata.shape[0]) y = np.linspace(extent[2], extent[3], zdata.shape[1]) cblabel = mpl_cb title = mpl_axes.get_title() xlabel = mpl_axes.get_xlabel() ylabel = mpl_axes.get_ylabel() plotdata = [ pyg.Heatmap( z=zdata.tolist(), x=x, y=y, colorscale=colorscale, colorbar=dict(title=cblabel, titleside="right", len=1.058, outlinewidth=0), ) ] layout = pyg.Layout(title=title, xaxis=dict(title=xlabel), yaxis=dict(title=ylabel)) fig = pyg.Figure(data=plotdata, layout=layout) py.iplot(fig, filename=title)
def histplot(feature): # Add histogram data and feature labels x = tracks[feature] data = Data([ Histogram( x=x ) ]) return py.iplot(data)
def iplot(data_or_figure,validate=True,world_readable=False,filename='',online=None): if offline.is_offline() and not online: show_link = auth.get_config_file()['offline_show_link'] link_text = auth.get_config_file()['offline_link_text'] return offline.py_offline.iplot(data_or_figure,show_link=show_link,link_text=link_text) else: if 'layout' in data_or_figure: validate = False if 'shapes' in data_or_figure['layout'] else True return py.iplot(data_or_figure,validate=validate,world_readable=world_readable, filename=filename)
def positive_graph(data, candidate): ''' INPUT DataFrame, string OUTPUT plotly graph ''' data = Data([ Bar( y=data['pos_keys'], x=data['pos_percent'], text=data['pos_example'], orientation = 'h', marker=Marker( color='rgb(224, 102, 102)', opacity=0.6, ), opacity=0.6, ) ]) layout = Layout( title='Positive Sentiment', xaxis=XAxis( title='Proportion of comments', titlefont=Font( family='Courier New, monospace', size=18, color='#7f7f7f' ) ), width=900, height=600, margin=Margin( # set frame to plotting area margins t=100, # top, b=100, # bottom, r=10, # right, l=250# left ), yaxis=YAxis( title='', titlefont=Font( family='Courier New, monospace', size=18, color='#7f7f7f' ) ) ) fig = Figure(data=data, layout=layout) return py.iplot(fig, validate=False, filename= candidate + '_pos')
def value_investing_strategy_check(filename1, filename2): with open('tools/plotly_credentials.json', 'r') as creds: credentials = json.load(creds) py.sign_in(credentials['plotly']['username'], credentials['plotly']['key']) initial_state = pd.read_csv(filename1 + '.csv') # # pb,industry,peg,name,mc # 1.61,Health Care,2.24,Allergan plc,117460000000.0 # final_state = pd.read_csv(filename2 + '.csv') # # name,mc,industry,pb,r,peg # Allergan plc,100260000000.0,Health Care,1.4,-0.13221840299542262,1.34 # py.iplot(fig, filename=('comapre' + filename1 + 'and' + filename2))
def plotly_monthtags(mcounts): ml=mcounts.index.tolist()[:25] mln=mcounts.txt.tolist()[:25] ml.reverse() mln.reverse() trace0 = go.Bar( y = ml, x = mln, marker=dict( color='rgba(50, 171, 96, 0.6)', line=dict( color='rgba(50, 171, 96, 1.0)', width=1), ), name='', orientation='h' ) data = [trace0] # Edit the layout layout = dict( title = 'Hot topics on Kashmir this September', xaxis = dict(title = 'Impressions'), margin=dict( l=200, r=50, t=70, b=70 )) # Plot and embed in ipython notebook! # options in the graph such as displaying edit text and other tools # can be hidden in iframe options in HTMS fig = dict(data=data, layout=layout) py.iplot(fig,filename='styled-line')
def iplot(data_or_figure,validate=True,sharing=None,filename='',online=None,**kwargs): """ Plots a figure in IPython data_or_figure : figure Plotly figure to be charted validate : bool If True then all values are validated before it is charted sharing : string Sets the sharing level permission public - anyone can see this chart private - only you can see this chart secret - only people with the link can see the chart filename : string Name to be used to save the file in the server online : bool If True then charts are rendered in the server Other Kwargs ============ legend : bool If False then the legend will not be shown """ valid_kwargs=['world_readable','legend'] for key in list(kwargs.keys()): if key not in valid_kwargs: raise Exception("Invalid keyword : '{0}'".format(key)) if 'legend' in kwargs: if 'layout' in data_or_figure: data_or_figure['layout'].update(showlegend=kwargs['legend']) if all(['world_readable' in kwargs,sharing is None]): sharing=kwargs['world_readable'] if isinstance(sharing,bool): if sharing: sharing='public' else: sharing='private' if sharing is None: sharing=auth.get_config_file()['sharing'] if offline.is_offline() and not online: show_link = auth.get_config_file()['offline_show_link'] link_text = auth.get_config_file()['offline_link_text'] return offline.py_offline.iplot(data_or_figure,show_link=show_link,link_text=link_text) else: if 'layout' in data_or_figure: validate = False if 'shapes' in data_or_figure['layout'] else validate if not filename: filename='Plotly Playground {0}'.format(time.strftime("%Y-%m-%d %H:%M:%S")) return py.iplot(data_or_figure,validate=validate,sharing=sharing, filename=filename)
def main(): ''' This the plot.ly sample choropleth method modified to use our Pubmed Data Sample: https://plot.ly/python/choropleth-maps/#world-choropleth-map ''' df = pd.read_csv("country_M_code.csv") data = [ dict( type = "choropleth", locations = df["Code"], z = df["M>2"], text = df["Country"], autocolorscale = True, reversescale = False, marker = dict( line = dict ( color = "rgb(180, 180, 180)", width = 0.5 ) ), colorbar = dict( autotick = False, tickprefix = "", title = "M"), ) ] layout = dict( title = "Countries with M > 1", geo = dict( showframe = False, showcoastlines = False, projection = dict( type = "Mercator" ) ) ) fig = dict( data=data, layout=layout ) py.iplot( fig, validate=False, filename="M-world-map" )
fig = ff.create_choropleth( fips=fips, values=values, binning_endpoints=endpts, colorscale=colorscale, show_state_data=False, show_hover=True, centroid_marker={'opacity': 0}, asp=2.9, title='Rent by county in United States ', county_outline={'color': 'rgb(255,255,255)', 'width': 0.5}, legend_title='rent in United States', ) # In[35]: py.iplot(fig, filename='choropleth_full_usa') # <div class="alert alert-success"> # <b>The above map shows the distribution of rent and helps us to visualize which locations have concentration of higher rent prices.<br> # So we have found that specific counties in California and NewYork have the highest rent prices # eg - Santa Clara County of California # <div> # ## <b>Finding 1:</b> rent vs debt # In[36]: import matplotlib.pyplot as pyplt sns.set_context("notebook", font_scale=1.3)
width = 0.5 ), label = data['data'][0]['node']['label'], color = data['data'][0]['node']['color'] ), link = dict( source = data['data'][0]['link']['source'], target = data['data'][0]['link']['target'], value = data['data'][0]['link']['value'], label = data['data'][0]['link']['label'] )) layout = dict( title = "Energy forecast for 2050<br>Source: Department of Energy & Climate Change, Tom Counsell via <a href='https://bost.ocks.org/mike/sankey/'>Mike Bostock</a>", font = dict( size = 10 ) ) fig = dict(data=[data_trace], layout=layout) py.iplot(fig, validate=False)
line=dict(width=2), )) data = [trace0, trace1, trace2, trace3, trace4] layout = go.Layout( title='Life Expectancy v. Per Capita GDP, 2007', xaxis=dict( title='GDP per capita (2000 dollars)', gridcolor='rgb(255, 255, 255)', range=[2.003297660701705, 5.191505530708712], type='log', zerolinewidth=1, ticklen=5, gridwidth=2, ), yaxis=dict( title='Life Expectancy (years)', gridcolor='rgb(255, 255, 255)', range=[36.12621671352166, 91.72921793264332], zerolinewidth=1, ticklen=5, gridwidth=2, ), paper_bgcolor='rgb(243, 243, 243)', plot_bgcolor='rgb(243, 243, 243)', ) fig = go.Figure(data=data, layout=layout) plotly.offline.plot(fig, filename='name.html') py.iplot(fig, filename='life-expectancy-per-GDP-2007')
def plot_feats(): decs = [decade + 1 for decade in range(20)] # Initialization Y = dict() error_Y = dict() for feature in th[2:]: # [D,I,F] Y[feature] = list() error_Y[feature] = list() feats = { 'D': "Contextual diversity", 'I': "Word informativeness", 'F': "Word frequency" } ranges = { 'D': [-0.0007, 0.000400], 'I': [-0.0006, 0.003], 'F': [-0.005, -0.0009] } # Get data for mdf in lms: for feature in th[2:]: # Coefficient coef = mdf.params[feature] Y[feature].append(coef) # Std. dev. std = mdf.bse[feature] error_Y[feature].append(std) # Plot (1 = 'all') choice = 1 if choice == 1: traces = list() for feature in th[2:]: trace = go.Bar(x=decs, y=Y[feature], name=feats[feature], error_y=dict(type='data', array=error_Y[feature], visible=True)) traces.append(trace) layout = go.Layout(barmode='group', yaxis=dict(range=ranges[feature])) fig = go.Figure(data=traces, layout=layout) py.iplot(fig, filename="comb-bar") else: for feature in th[2:]: trace1 = go.Bar(x=decs, y=Y[feature], error_y=dict(type='data', array=error_Y[feature], visible=True)) if feature == 'D': layout = go.Layout(xaxis=dict(title="Decades", showticklabels=True, range=[1, 20]), yaxis=dict(title="Coefficients (" + feats[feature] + ")", showticklabels=True, exponentformat='e', showexponent="all")) else: layout = go.Layout(xaxis=dict(title="Decades", showticklabels=True, range=[1, 20]), yaxis=dict(title="Coefficients (" + feats[feature] + ")", showticklabels=True, range=ranges[feature])) data = [trace1] fig = go.Figure(data=data, layout=layout) py.iplot(fig, filename=feature + '_bar')
"#323268", "#3d4b94", "#3e6ab0", "#4989bc", "#60a7c7", "#85c5d3", "#b7e0e4", "#eafcfd" ] #colorscale=cl.scales['7']['seq']['Purples'] #endpts = list(np.linspace(1, 12, len(colorscale) - 1)) fig = ff.create_choropleth( fips=fips, values=values, scope=['Oregon'], show_state_data=True, colorscale=colorscale, binning_endpoints=endpts, round_legend_values=True, plot_bgcolor='rgb(229,229,229)', paper_bgcolor='rgb(255,255,255)', legend_title='Population Per Square Mile by County in Oregon State', county_outline={ 'color': 'rgb(255,255,255)', 'width': 0.5 }, exponent_format=True, ) py.iplot(fig, filename='oregon_pop_density')
name='thalach' ) trace8 = go.Box( y=heartDisease['exang'], name='exang' ) trace9 = go.Box( y=heartDisease['oldpeak'], name='oldpeak' ) trace10 = go.Box( y=heartDisease['heartdisease'], name='heart disease status' ) plotdata = [trace0, trace1, trace2, trace3, trace4, trace5, trace6, trace7, trace8, trace9, trace10] py.iplot(plotdata) #we need to normalize the data for item in heartDisease: #converts everything to floats heartDisease[item] = pd.to_numeric(heartDisease[item]) def normalize(heartDisease, toNormalize): #normalizes result = heartDisease.copy() for item in heartDisease.columns: if (item in toNormalize): max_value = heartDisease[item].max() min_value = heartDisease[item].min() result[item] = (heartDisease[item] - min_value) / (max_value - min_value) return result
range=[-6, 6], showgrid=True, showline=True, zeroline=False, mirror='ticks', ticks='inside', linewidth=2, tickwidth=2, ) layout = dict(title='P80 bands', width=500, height=700, xaxis=bandxaxis, yaxis=bandyaxis) fig = go.Figure(data=data + vlines, layout=layout) plt.iplot(fig, filename=structure + ' bands') fig, ax = plot.subplots(figsize=(3, 4)) nodes = [0.0, 1.0000, 1.7071, 2.2071, 3.0731, 3.7802] label = (r'$\Gamma$', r'$H$', r'$N$', r'$P$', r'$\Gamma$', r'$N$') ax.set_xticks(node_x) ax.set_xticklabels(label) for n in range(len(nodes)): ax.axvline(x=nodes[n], linewidth=.3, color='black') ax.set_title('P80 band structure') ax.set_xlabel('Path in k-space') ax.set_ylabel(r'$E$' + '–' + r'$E_f$')
import plotly.plotly as py import numpy as np data = [ dict( visible=False, line=dict(color='#00CED1', width=6), # 配置线宽和颜色 name='𝜈 = ' + str(step), x=np.arange(0, 10, 0.01), # x 轴参数 y=np.sin(step * np.arange(0, 10, 0.01))) for step in np.arange(0, 5, 0.1) ] # y 轴参数 data[10]['visible'] = True py.iplot(data, filename='Single Sine Wave')
mode="markers", marker=dict(size=1, color="blue")) layout = go.Layout( dict( title="Customer Attrition with Numeric Variables", scene=dict(camera=dict(up=dict(x=0, y=0, z=0), center=dict(x=0, y=0, z=0), eye=dict(x=1.25, y=1.25, z=1.25)), xaxis=dict(title="monthly charges", gridcolor='rgb(255, 255, 255)', zerolinecolor='rgb(255, 255, 255)', showbackground=True, backgroundcolor='rgb(230, 230,230)'), yaxis=dict(title="total charges", gridcolor='rgb(255, 255, 255)', zerolinecolor='rgb(255, 255, 255)', showbackground=True, backgroundcolor='rgb(230, 230,230)'), zaxis=dict(title="tenure", gridcolor='rgb(255, 255, 255)', zerolinecolor='rgb(255, 255, 255)', showbackground=True, backgroundcolor='rgb(230, 230,230)')), height=600, )) data = [trace1, trace2] fig = go.Figure(data=data, layout=layout) py.iplot(fig)
print state_count.keys() data1 = [go.Choropleth( colorscale = colorscale, autocolorscale = False, locations = state_count.keys(), z=state_count.values(), text=state_count.keys(), locationmode = 'USA-states', marker = go.choropleth.Marker( line = go.choropleth.marker.Line( color = 'rgb(255,255,225)', width = 2 )), colorbar = go.choropleth.ColorBar( title = "No of Complaints") )] layout = go.Layout( title = go.layout.Title( text = 'Consumer Complaints by State<br>(Hover for breakdown)' ), geo = go.layout.Geo( scope = 'usa', projection = go.layout.geo.Projection(type = 'albers usa'), showlakes = True, lakecolor = 'rgb(0, 0, 255)'), ) fig = go.Figure(data = data1, layout = layout) py.iplot(fig, filename = 'd3-cloropleth-map')
x=[], y=[], mode='lines+markers', stream=stream_obj[i] # (!) embed stream id, 1 per trace ) data = go.Data([trace[i]]) # Add title to layout object layout = go.Layout(title=map_sensor_id_to_title(i)) # Make a figure object fig = go.Figure(data=data, layout=layout) # Send fig to Plotly, initialize streaming plot, open new tab py.iplot(fig, filename=map_sensor_id_to_title(i)) # We will provide the stream link object the same token that's associated with the trace we wish to stream to s[i] = py.Stream(stream_id[i]) s[i].open() def draw_to_plotly(jsonstr): """ :param sensor_bundle: sensor_bundle[0] -> time sensor_bundle[1] -> ch4 sensor_bundle[2] -> lpg sensor_bundle[3] -> co2 sensor_bundle[4] -> dust sensor_bundle[5] -> temp
def hmmPlot(results, uid, feats, br1, br2, br3, filename=''): for res in results: if uid in res.uid.unique(): samp1 = res.loc[res.uid == uid].sort_values('ts').copy() break # obs1 = samp1.iloc[::max(1,int(samp1.shape[0]/50)),:].copy() # statemap = {0:"Stationary",1:"Walking",2:'Slow Moving',3:"Parking",4:"Traffic Light",5:"Driving"} samp1.reset_index(drop=True, inplace=True) ft = np.vectorize(datetime.fromtimestamp) def sft(dt): return datetime.strftime(dt, '%H:%M:%S') vsft = np.vectorize(sft) samp1['time'] = vsft(ft(samp1.ts / 1000)) br1_flg = np.array( [any(x in y for x in br1) * 5.0 for y in samp1.fp_brand.values]) br2_flg = np.array( [any(x in y for x in br2) * 5.0 for y in samp1.fp_brand.values]) br1_txt = [[br1[x] for x in br1 if x in y] for y in samp1.fp_brand.values] br1_txt = pd.Series([x[0] if x else "" for x in br1_txt]) br2_txt = np.array([[br2[x] for x in br2 if x in y] for y in samp1.fp_brand.values]) br2_txt = pd.Series([x[0] if x else "" for x in br2_txt]) br3_txt = np.array([[br3[x] for x in br3 if x in y] for y in samp1.fp_brand.values]) br3_txt = pd.Series([x[0] if x else "" for x in br3_txt]) samp1['text'] = samp1.time + " " + br1_txt + br2_txt + br3_txt + " " for i in range(len(feats)): samp1['text'] = samp1['text'] + feats[i] + ":" + samp1[feats[i]].map( str) + " " statemap = {0: "Stationary", 1: "Driving"} cdict = {0: 'darkgoldenrod', 1: 'royalblue'} mapbox_access_token = 'pk.eyJ1Ijoid2VpcWluZ3kiLCJhIjoiY2ppZG56N3lnMGRtMzN3cXZ4bm95dmtxNyJ9.fe7Jmdf44QWOnGCLKsTReg' samp1_m = samp1[['lat', 'long']].copy().values rec = {} for i in range(samp1_m.shape[0]): ll = tuple(samp1_m[i]) if ll not in rec: rec[ll] = tuple([ll[0] + 0.00003, ll[1]]) else: samp1_m[i] = rec[ll] rec[ll] = tuple([rec[ll][0] + 0.00003, rec[ll][1]]) data = [ go.Scattermapbox(lat=samp1['lat'], lon=samp1['long'], mode='lines+markers', marker=dict(size=5 + br1_flg + br2_flg, opacity=1, color=samp1.hs.map(cdict)), hovertext=samp1.hs.map(statemap) + " " + samp1['text']), go.Scattermapbox( lat=samp1_m[:, 0] + 0.00002, lon=samp1_m[:, 1], mode='text', text=[ str(x) + " " + samp1.time.values[x] for x in range(samp1_m.shape[0]) ], marker=dict(size=5, opacity=1, color='darkblue'), ), go.Scattermapbox( lat=samp1_m[:, 0] + 0.00002, lon=samp1_m[:, 1], mode='text', text=[ str(x) + " " + samp1.time.values[x] for x in range(samp1_m.shape[0]) ], marker=dict(size=5, opacity=1, color='darkblue'), ) ] layout = go.Layout( autosize=True, hovermode='closest', mapbox=dict(accesstoken=mapbox_access_token, bearing=0, center=dict(lat=samp1.lat.mean(), lon=samp1.long.mean()), pitch=0, zoom=11), ) fig = dict(data=data, layout=layout) py.iplot(fig, filename=filename + " " + uid)
cuisine_pie_values = [] for value in cuisine_dict.values(): cuisine_pie_values.append(value) data = { 'data': [{ 'labels': cuisine_pie_keys, 'values': cuisine_pie_values, 'type': 'pie' }], 'layout': { 'title': "Cuisine Types of Athens' Restaurants" } } py.iplot(data, filename='basic-line') #E). QQ Plots (answer in next cell) import scipy.stats as stats stats.probplot(food_df.Rating, dist="norm", plot=plt) plt.title('QQ Plot of Rating') plt.show() stats.probplot(food_df.Number_of_Reviews, dist="norm", plot=plt) plt.title('QQ Plot of Reviews') plt.show() stats.probplot(food_df.Number_of_Photos, dist="norm", plot=plt) plt.title('QQ Plot of Photos')
tempLat = latStr[:2] tempLong = lonStr[:3] data = Data([ Scattermapbox( lat=[float(latitude)], lon=[float(longitude)], mode='markers', marker=Marker(size=14), text=['BROCKTON'], ) ]) layout = Layout( autosize=True, hovermode='closest', mapbox=dict( accesstoken= 'pk.eyJ1IjoicHZvbmxlaCIsImEiOiJjamYzOHZ6bmswNnkyMnlsdHptYjlkNGM2In0.Eu3jSih10cgvdG-FiYWF4w', #pk.eyJ1IjoicHZvbmxlaCIsImEiOiJjamYzOHZ6bmswNnkyMnlsdHptYjlkNGM2In0.Eu3jSih10cgvdG - FiYWF4w bearing=0, center=dict(lat=float(tempLat), lon=float(tempLong)), pitch=0, zoom=5), ) fig = dict(data=data, layout=layout) py.iplot(fig, filename='Stackoverflow Jobs') print(location.address)
import plotly.plotly as py import plotly.figure_factory as ff df = [ dict(Task='Day1', Start='2016-01-01', Finish='2016-01-01 6:00:00', Resource='Sleep'), dict(Task='Day1', Start='2016-01-01 7:00:00', Finish='2016-01-01 7:30:00', Resource='Food'), dict(Task='Day1', Start='2016-01-01 9:00:00', Finish='2016-01-01 11:25:00', Resource='Brain'), dict(Task='Day1', Start='2016-01-01 11:30:00', Finish='2016-01-01 12:00:00', Resource='Rest'), dict(Task='Day1', Start='2016-01-01 12:00:00', Finish='2016-01-01 13:00:00', Resource='Food'), dict(Task='Day1', Start='2016-01-01 13:00:00', Finish='2016-01-01 17:00:00', Resource='Brain'), dict(Task='Day1', Start='2016-01-01 17:30:00', Finish='2016-01-01 18:30:00', Resource='Cardio'), dict(Task='Day1', Start='2016-01-01 18:30:00', Finish='2016-01-01 19:00:00', Resource='Rest'), dict(Task='Day1', Start='2016-01-01 19:00:00', Finish='2016-01-01 20:00:00', Resource='Food'), dict(Task='Day1', Start='2016-01-01 21:00:00', Finish='2016-01-01 23:59:00', Resource='Sleep') ] colors = dict(Cardio = 'rgb(46, 137, 205)', Food = 'rgb(114, 44, 121)', Sleep = 'rgb(198, 47, 105)', Brain = 'rgb(58, 149, 136)', Rest = 'rgb(107, 127, 135)') fig = ff.create_gantt(df, colors=colors, index_col='Resource', title='Daily Schedule', show_colorbar=True, bar_width=0.2, showgrid_x=True, showgrid_y=True, group_tasks=True) py.iplot(fig, filename='practiceganttplottime', world_readable=True)
def sendfunc(rows7): l = [] for i in rows7: l.append(list(i)) schema = [i[0] for i in l] nos = [i[1] for i in l] nos = [int(x) for x in nos] i = 0 t = 0 while i < len(nos): t += nos[i] i += 1 P = [float(x/t*100) for x in nos] trace1 = go.Bar( y=[''], x=[P[0]], name = (f"{schema[0]}"), text = (f"{nos[0]}"), textposition = 'auto', orientation = 'h', marker = dict( color = 'rgba(103, 240, 160, 0.75)', line = dict( color = '#43BD78', width = 3) ) ) trace2 = go.Bar( y=[''], x=[P[1]], name=(f"{schema[1]}"), text = (f"{nos[1]}"), textposition = 'auto', orientation = 'h', marker = dict( color = 'rgba(255, 172, 188, 0.75)', line = dict( color = '#E67188', width = 3) ) ) trace3 = go.Bar( y=[''], x=[P[2]], name=(f"{schema[2]}"), text = (f"{nos[2]}"), textposition = 'auto', orientation = 'h', marker = dict( color = 'rgba(177, 193, 216, 1.0)', line = dict( color = '#82A1D0', width = 3) ) ) trace4 = go.Bar( y=[''], x=[P[3]], name=(f"{schema[3]}"), text = (f"{nos[3]}"), textposition = 'auto', orientation = 'h', marker = dict( color = 'rgba(250, 184, 126, 0.75)', line = dict( color = '#DF8E47', width = 3) ) ) trace5 = go.Bar( y=[''], x=[P[4]], name=(f"{schema[4]}"), text = (f"{nos[4]}"), textposition = 'inside', orientation = 'h', marker = dict( color = '#C8A8CD', line = dict( color = '#9C7DA1', width = 3) ) ) data = [trace1, trace2, trace3, trace4, trace5] layout = go.Layout( autosize=False, width=700, height=110, barmode='stack', xaxis=dict(ticksuffix="%"), legend=dict( orientation="h", x=0.06, y=-0.27, font=dict( size=10.5 ) ), margin=go.layout.Margin( l=60, r=60, b=0, t=0, pad=0 ) ) fig = go.Figure(data=data, layout=layout) py.iplot(fig, filename='marker-h-bar') pio.write_image(fig,'schemas_invsr.png')
def plotGraph(X,W,labeledIndexes,vertex_opt,plot_filepath = None, online = False, interactive=False,title = "", plot_size = [1000,1000], edge_width = 0.5,labeled_only=False): """ Plots a GSSL graph. Creates a plot showing vertices connected by edges from the affinity matrix in 2D/3D. A number of different configurations is possible by the use of a vertexplotOpt object. Args: X (`NDArray[float].shape[N,D]`): A 2D or 3D matrix containing the vertex positions. W (`NDArray[float].shape[N,N]`): Optional. The affinity matrix defining the graph. vertex_opt (vertexOptObject) : The size/color/group vertex configuration object. title (string, default = ``''``) : The title to be printed above the image. online (bool, default = ``False``) : whether to create an online plot interactive (bool, default = ``False``) : whether to open an interactive plot on the browser plot_size (`List[int].shape[2]`, default = ``[1000,1000]``) : size of the canvas for the plotting operation. edge_width (float, default = ``0.5``) : thickness of the edges. Raises: ValueError: ``if X.shape[1] not in [2, 3]`` Returns: None """ if plot_filepath is None: plot_filepath = path.join(PLOT_FOLDER,str(datetime.datetime.now()) + ".png") plot_dim = X.shape[1] if plot_dim < 2 or plot_dim > 3: raise ValueError("plot_dim must be either 2 or 3") if (not W is None) and W.shape[0] != X.shape[0]: raise ValueError("Shapes of W, X do not match") if plot_dim > X.shape[1]: #Add missing dimensions temp = np.zeros((X.shape[0],plot_dim)) temp[0:X.shape[0],0:X.shape[1]] = X X = temp if not os.path.exists(os.path.dirname(plot_filepath)): os.makedirs(os.path.dirname(plot_filepath)) def axis(dim_num): M = np.max(X[:,dim_num]) m = np.min(X[:,dim_num]) x = (M-m)/2 M = M + (M-x)*0.2 m = m + (m-x)*0.2 axis=dict( showline=False, zeroline=False, showgrid=False, showticklabels=False, visible=True, title='', range = [m,M] ) return(axis) scene = {} scene["xaxis"] = dict(axis(0)) scene["yaxis"] = dict(axis(1)) if plot_dim == 3: scene["zaxis"] = dict(axis(2)) layout = go.Layout( title=title, font=dict(family='Courier New, bold', size=30, color='black'), width=plot_size[0], height=plot_size[1], legend=dict(x=0, y=1, traceorder='normal', font=dict( family='sans-serif', size=30, color='#000' ), bgcolor='#E2E2E2', bordercolor='#FFFFFF', borderwidth=2), showlegend=True, xaxis=scene["xaxis"], yaxis=scene["yaxis"], margin=dict( t=100 ), hovermode='closest', annotations=[ dict( showarrow=False, text="</a>", xref='paper', yref='paper', x=0, y=0.1, xanchor='left', yanchor='bottom', font=dict( size=14 ) ) ], ) if "zaxis" in scene.keys(): layout.update(go.Layout(zaxis=scene["zaxis"])) #Create Traces data = [] if not W is None: trace_edge = _traceEdges(X=X, W=W,plot_dim=plot_dim, edge_width=edge_width) data = trace_edge trace_vertex = _traceVertex(X=X,labeledIndexes=labeledIndexes, plot_dim=plot_dim, v_opt = vertex_opt) data += trace_vertex #Create figure fig=go.Figure(data=data, layout=layout) LOG.info("Plotting graph ({}) ...".format(title),LOG.ll.OUTPUT) if online: try: py.iplot(fig) except plotly.exceptions.PlotlyRequestError: LOG.warn("Warning: Could not plot online",LOG.ll.OUTPUT) if interactive: pyoff.offline.plot(fig) pio.write_image(fig,plot_filepath) LOG.info("Plotting graph({})...Done!".format(title),LOG.ll.OUTPUT)
trace = dict(x=range(0, len(inData)), y=inData[:, i], stackgroup='one', mode='lines', line=dict(width=3, color=colors[i]), name=labels[i]) tracesList.append(trace) layout = go.Layout(title='Genotypes Breakdown', xaxis=dict(title='Time [days]', titlefont=dict(size=20, color='#7f7f7f')), yaxis=dict(title='Allele Frequency', titlefont=dict(size=20, color='#7f7f7f')), width=1500, height=400) fig = go.Figure(data=go.Data(tracesList), layout=layout) py.iplot(fig, filename='stacked-area-plot-hover', validate=False) plotly.offline.plot(fig, filename='alleleFrequency.html') # Plot allele ratio dynamics .................................................. tracesList = [] for i in range(0, len(labels)): trace = dict(x=range(0, len(inData)), y=inData[:, i], stackgroup='one', groupnorm='fraction', mode='lines', line=dict(width=3, color=colors[i]), name=labels[i]) tracesList.append(trace) layout = go.Layout(title='Genotypes Breakdown', xaxis=dict(title='Time [days]',
#add column that calculates growth from 1970-2017 for population df_UrbSub_Pop['Growth'] = (df_UrbSub_Pop['2017'] - df_UrbSub_Pop['1970']) / (df_UrbSub_Pop['1970']) df_UrbSub_Emp['Growth'] = (df_UrbSub_Emp['2017'] - df_UrbSub_Emp['1990']) / (df_UrbSub_Emp['1990']) # In[16]: data = [ go.Bar(x=df_UrbSub_Pop.index, y=df_UrbSub_Pop['Growth'], name='Population Growth 1970-2017') ] py.iplot(data, filename='basic-bar') # In[21]: trace1 = go.Bar(y=df.cbsa_code, x=df['2017'], name=df.index, orientation='h') trace2 = go.Bar( y=df_PS.cbsa_code, x=df_PS['2017'], name=df_PS.index, orientation='h', ) data = [trace1, trace2] layout = go.Layout(barmode='stack', # shapes=rectangle
font=dict(family='Courier New, monospace', size=24, color='#000000'), xaxis=dict( domain=[0, 1.00], title='Time Period', titlefont=dict(family='Courier New, monospace',size=16,color='#000000') ), yaxis=dict( domain=[0, 1.00], title='Measurement', titlefont=dict(family='Courier New, monospace',size=16,color='#000000'), )) fig = go.Figure(data=data, layout=layout) py.iplot(fig, filename='IoT Predictive Maintenance Demo') s_1 = py.Stream(stream_id=token_1) s_2 = py.Stream(stream_id=token_2) s_1.open() s_2.open() while True: stream_data(IoT_Demo_Topic,max) # Close the stream when done plotting s_1.close() s_2.close()
colorscale = [[0.0, 'rgb(242,240,247)'],[0.2, 'rgb(218,218,235)'],[0.4, 'rgb(188,189,220)'],[0.6, 'rgb(158,154,200)'],[0.8, 'rgb(117,107,177)'],[1.0, 'rgb(84,39,143)']], autocolorscale = False, reversescale = True, marker = dict( line = dict ( color = 'rgb(180,180,180)', width = 0.5 ) ), colorbar = dict( autotick = False, tickprefix = '$', title = 'Spatial analysis of Replies'), ) ] layout = dict( title = 'Spatial analysis of Trump Tweets', geo = dict( showframe = False, showcoastlines = False, projection = dict( type = 'Mercator' ) ) ) fig = dict( data=data, layout=layout ) return fig y,z=plotdata(tr['user']) plot_worldmap(y,z,c) py.iplot( fig, validate=False, filename='d3-world-map' ) #https://www.kaggle.com/shep312/plotlycountrycodes
import plotly.plotly as py import plotly.graph_objs as go trace0 = go.Bar(x=[ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ], y=[20, 14, 25, 16, 18, 22, 19, 15, 12, 16, 14, 17], name='Primary Product', marker=dict(color='rgb(49,130,189)')) trace1 = go.Bar(x=[ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ], y=[19, 14, 22, 14, 16, 19, 15, 14, 10, 12, 12, 16], name='Secondary Product', marker=dict(color='rgb(204,204,204)', )) data = [trace0, trace1] layout = go.Layout(barmode='group', ) fig = go.Figure(data=data, layout=layout) py.iplot(fig, filename='angled-text-bar')
data['DataSource'].value_counts().plot(kind='bar') plt.show() data['Topic'].value_counts().plot(kind='bar') plt.show() data['DataValueType'].value_counts().plot(kind='bar') plt.show() data['StratificationCategory1'].value_counts().plot(kind='bar') plt.show() import plotly plotly.tools.set_credentials_file(username='******', api_key='hghqq2ST4H5jQI09Apqa') import networkx as nx import plotly.plotly as py import plotly.graph_objs as go trace = go.Heatmap(z=data.YearStart,x= data['LocationAbbr'],y=data['Topic']) d=[trace] py.iplot(d, filename='basic-heatmap') # plot Yearstart data with label bar data_sorted = data.sort_values(by = 'YearStart', ascending = False) ax = sns.countplot(x="YearStart", data=data) total = float(len(data)) for p in ax.patches: height = p.get_height() ax.text(p.get_x()+p.get_width()/2,height, '{:1.0f}'.format(height),ha="center",rotation=90) plt.show() # remove the insignificant data dataclear = data[data['YearStart']>= 2009] for_alcohol = data[data.Topic == 'Alcohol'] for_alcohol['Question'].value_counts().plot(kind='bar') plt.show() for_alcohol['DataValueType'].value_counts().plot(kind='bar') plt.show()
import csv import plotly.plotly as py import plotly.graph_objs as go with open('voucher.csv') as csvfile: reader = csv.reader(csvfile, delimiter=";") for row in reader: eins = row[1] zwei = row[2] trace = go.Table(header=dict(values=['A Scores', 'B Scores']), cells=dict(values=[[100, 90, 80, 90], [95, 85, 75, 95]])) data = [trace] py.iplot(data, filename='basic_table') # print(row[1])
# colorscale=pl_colorscale, showscale=False, line=dict(width=0.5, color='rgb(230,230,230)')), showupperhalf=False) axis = dict(showline=True, zeroline=False, gridcolor="#fff", ticklen=4) layout = go.Layout( title='stomp std dev evaluation', dragmode='select', width=1500, height=1500, autosize=True, hovermode='closest', plot_bgcolor='rgba(240,240,240, 0.95)', xaxis1=dict(axis), xaxis2=dict(axis), xaxis3=dict(axis), xaxis4=dict(axis), yaxis1=dict(axis), yaxis2=dict(axis), yaxis3=dict(axis), yaxis4=dict(axis)) fig1 = dict(data=[trace1], layout=layout) py.iplot(fig1, filename='std_devs_stomp')
for i in range(len(lat)): for j in range(len(long)): coord = lat[i], long[j] list_lat.append(lat[i]) list_long.append(long[j]) grid.append(coord) mapbox_access_token = "pk.eyJ1IjoibWF0ZXVzLW5vcm1hbmRlIiwiYSI6ImNqczF6cG9oMzIwNnc0NHFyd2VqbGpheHUifQ.OZYbhTGC7-BXFMUhEQXRNg" data = [ go.Scattermapbox(lat=list_lat, lon=list_long, mode='markers', marker=dict(size=3)) ] layout = go.Layout( autosize=True, hovermode='closest', mapbox=dict(accesstoken=mapbox_access_token, bearing=0, center=dict( lat=-9.551585, lon=-35.775490, ), pitch=0, zoom=10), ) fig = dict(data=data, layout=layout) py.iplot(fig, filename='Coordenadas')
def draw_network(graph): G = nx.Graph() # G is an empty Graph my_edges = create_edges(graph) my_nodes = range(m * k) grouped_nodes = [] for i in range(m): grouped_nodes.append([i * k + x for x in range(k)]) pos = {} # generate m circular points for i in range(m): TempGraph = nx.Graph() TempGraph.add_nodes_from(grouped_nodes[i]) new_dict = nx.circular_layout(TempGraph) #change each elem of new_dict into lists instead of numpy arrays # for coords in new_dict: # new_dict[coords] = list(new_dict[coords]) t = float(i) / m #goes from 0-1 r = 4 displacement = [ r * math.sin(t * 2 * math.pi), r * math.cos(t * 2 * math.pi) ] for coords in new_dict: for i in [0, 1]: new_dict[coords][i] = new_dict[coords][i] + displacement[i] new_dict[coords] = list(new_dict[coords]) pos.update(new_dict) G.add_nodes_from(my_nodes) G.add_edges_from(my_edges) ######### # G=nx.random_geometric_graph(200,0.125) # pos=nx.get_node_attributes(G,'pos')# {nodeid: [x, y], ... # dmin=1 # ncenter=0 # for n in pos: # x,y=pos[n] # d=(x-0.5)**2+(y-0.5)**2 # if d<dmin: # ncenter=n # dmin=d # p=nx.single_source_shortest_path_length(G,ncenter) # Create edges edge_trace = go.Scatter(x=[], y=[], line=dict(width=0.5, color='#888'), hoverinfo='none', mode='lines') for edge in my_edges: #G.edges(): x0, y0 = pos[edge[0]][0], pos[edge[0]][1] #G.node[edge[0]]['pos'] x1, y1 = pos[edge[1]][0], pos[edge[1]][1] #G.node[edge[1]]['pos'] edge_trace['x'] += tuple([x0, x1, None]) edge_trace['y'] += tuple([y0, y1, None]) node_trace = go.Scatter( x=[], y=[], text=[], mode='markers', hoverinfo='text', marker=dict( showscale=True, # colorscale options #'Greys' | 'YlGnBu' | 'Greens' | 'YlOrRd' | 'Bluered' | 'RdBu' | #'Reds' | 'Blues' | 'Picnic' | 'Rainbow' | 'Portland' | 'Jet' | #'Hot' | 'Blackbody' | 'Earth' | 'Electric' | 'Viridis' | colorscale='YlGnBu', reversescale=True, color=[], size=10, colorbar=dict(thickness=15, title='Node Connections', xanchor='left', titleside='right'), line=dict(width=2))) for key in pos: #G.nodes(): x, y = pos[key][0], pos[key][1] #G.node[node]['pos'] node_trace['x'] += tuple([x]) node_trace['y'] += tuple([y]) # Colour node points for node, adjacencies in enumerate(G.adjacency()): node_trace['marker']['color'] += tuple([len(adjacencies[1])]) node_info = '# of connections: ' + str(len(adjacencies[1])) node_trace['text'] += tuple([node_info]) # Create network graph fig = go.Figure( data=[edge_trace, node_trace], layout=go.Layout( title='<br>Network graph made with Python', titlefont=dict(size=16), showlegend=False, hovermode='closest', margin=dict(b=20, l=5, r=5, t=40), annotations=[ dict( text= "Python code: <a href='https://plot.ly/ipython-notebooks/network-graphs/'> https://plot.ly/ipython-notebooks/network-graphs/</a>", showarrow=False, xref="paper", yref="paper", x=0.005, y=-0.002) ], xaxis=dict(showgrid=False, zeroline=False, showticklabels=False), yaxis=dict(showgrid=False, zeroline=False, showticklabels=False))) py.iplot(fig, filename='Ring group graph')
@author: zww @contact: [email protected] @software: 2017/12/10 12:36 @file: vislize.py @time: 2017/12/10 12:36 @desc: ''' import plotly.plotly as py import plotly.graph_objs as go import pandas as pd # Read data from a csv z_data = pd.read_csv('data\zcdata.csv') data = [go.Surface(z=z_data.as_matrix())] layout = go.Layout(title='Mt Bruno Elevation', autosize=False, width=500, height=500, margin=dict(l=65, r=50, b=65, t=90)) fig = go.Figure(data=data, layout=layout) py.iplot(fig, filename='elevations-3d-surface')
def plotState(dat, uid, myhmm): try: samp1 = dat.loc[(dat.uid == uid) & (np.isnan(dat.haflg))].sort_values('ts') except: samp1 = dat.loc[(dat.uid == uid)].sort_values('ts') # obs1 = samp1.iloc[::max(1,int(samp1.shape[0]/50)),:].copy() obs1 = samp1.copy() obs = np.array(obs1[['dspd', 'angle', 'td', 'dd', 'geo', 'cflg']]) # statemap = {0:"Stationary",1:"Walking",2:'Slow Moving',3:"Parking",4:"Traffic Light",5:"Driving"} statemap = {0: "Stationary", 1: "Driving"} mapbox_access_token = 'pk.eyJ1Ijoid2VpcWluZ3kiLCJhIjoiY2ppZG56N3lnMGRtMzN3cXZ4bm95dmtxNyJ9.fe7Jmdf44QWOnGCLKsTReg' samp1['hs'] = choice(myhmm.viterbi_k_log(obs, 20), 0)[1] try: samp1_g = samp1.loc[np.isnan(samp1.haflg)] except: samp1_g = samp1 samp1_m = samp1_g[['lat', 'long']].copy().values rec = {} for i in range(samp1_m.shape[0]): ll = tuple(samp1_m[i]) if ll not in rec: rec[ll] = tuple([ll[0] + 0.00003, ll[1]]) else: samp1_m[i] = rec[ll] rec[ll] = tuple([rec[ll][0] + 0.00003, rec[ll][1]]) data = [ go.Scattermapbox(lat=samp1_g['lat'], lon=samp1_g['long'], mode='lines+markers', marker=dict(size=5, opacity=1, color=samp1.hs), hovertext=samp1_g.hs.map(statemap) + " " + samp1_g['text']), go.Scattermapbox( lat=samp1_m[:, 0] + 0.00002, lon=samp1_m[:, 1], mode='text', text=[ str(x) + " " + samp1.time.values[x] for x in range(samp1_m.shape[0]) ], marker=dict(size=5, opacity=1, color='darkblue'), ), go.Scattermapbox( lat=samp1.loc[samp1.flg == 1]['lat'], lon=samp1.loc[samp1.flg == 1]['long'], mode='markers', text="Map Plot", marker=dict(size=10, opacity=1, color='burlywood'), ) ] layout = go.Layout( autosize=True, hovermode='closest', mapbox=dict(accesstoken=mapbox_access_token, bearing=0, center=dict(lat=37.42, lon=-122.0945), pitch=0, zoom=11), ) fig = dict(data=data, layout=layout) py.iplot(fig, filename='manual inspection')
y=[20, 21, 22, 23], text=[ 'A</br>size: 40</br>sixeref: 2', 'B</br>size: 60</br>sixeref: 2', 'C</br>size: 80</br>sixeref: 2', 'D</br>size: 100</br>sixeref: 2' ], mode='markers', marker=dict( size=[400, 600, 800, 1000], sizeref=0.2, sizemode='area', )) data = [trace0, trace1, trace2] py.iplot(data, filename='bubblechart-size-ref') #-----------------------------------------------------------------------------------------------------------------# #------------------------------------------CLASSIFIER CODE--------------------------------------------------------# #-----------------------------------------------------------------------------------------------------------------# def getRoundedPhotoData(): traitFile = open("C:/Users/rrenv/Desktop/Level4Project/averageRatings.csv", "r") for line in traitFile: line = line[:-1] values = line.split(",") traitValues = [] if (values[0][:12] not in photoData): photoData[values[0][:12]] = []