def BP_display(df): DF = df DF['bp_cat'] = "" for i in range(len(DF)): if DF.ap_lo[i] <= 60 and DF.ap_hi[i] <= 100: DF.bp_cat[i] = 'low' elif (DF.ap_lo[i] > 60 and DF.ap_lo[i] <= 80) or (DF.ap_hi[i] > 100 and DF.ap_hi[i] <= 120): DF.bp_cat[i] = 'normal' elif (DF.ap_lo[i] > 80) or (DF.ap_hi[i] > 120): DF.bp_cat[i] = 'high' DF['bp_sum'] = "" for i in range(len(DF)): DF.bp_sum[i] = float(0.25 * (DF.ap_lo[i] + DF.ap_hi[i])) DF.bp_sum = pd.to_numeric(DF.bp_sum) fig = px.scatter_3d(DF, x='ap_lo', y='ap_hi', z='date', color='bp_cat', size='bp_sum', size_max=100, hover_name='bp_cat') py.plot(fig, filename='bp_graph', auto_open=True)
def Real_time_plot1(request): ######### Phase 1:- Data aloocating and defining import plotly.graph_objects as go import plotly import numpy as np import plotly.express as px ########### phase :: Accessing the downloaded file (Data1.csv) import os from smartfasal_project.settings import BASE_DIR STATIC_ROOT = os.path.join(BASE_DIR, 'static') path = STATIC_ROOT os.chdir(path) import pandas as pd filename = "data1.csv" #Local_data_smartfasal = pd.read_csv(filename, names=['Timestamp', 'S_M_10cm','S_M_45cm','S_M_80cm', 'Temperature', 'Humidity', 'Pressure', 'Luxes']) #Local_data_smartfasal = pd.read_csv(filename) import plotly.express as px df = pd.read_csv('Last_rows.csv') x_Time = df['Time'] y0 = df['SM10'] y1 = df['SM45'] y2 = df['SM80'] y3 = df['Temp'] y4 = df['Humd'] y5 = df['LMNS'] y6 = df['PRSR'] fig = go.Figure() fig.add_trace(go.Scatter(x=x_Time, y=y0, mode='lines', name='SM @ 10 cm', marker = dict(color = 'rgba(255,0,0,0.8)'))) fig.add_trace(go.Scatter(x=x_Time, y=y1, mode='lines', name='SM @ 45 cm', marker = dict(color = 'rgba(0,255,0,0.8)'))) fig.add_trace(go.Scatter(x=x_Time, y=y2, mode='lines', name='SM @ 80 cm', marker = dict(color = 'rgba((26, 102, 255,0.8)'))) fig.add_trace(go.Scatter(x=x_Time, y=y3, mode='lines', name='Temperature', marker = dict(color = 'rgba(204, 0, 204, 0.8)'))) fig.add_trace(go.Scatter(x=x_Time, y=y4, mode='lines', name='Humidity', marker = dict(color = 'rgba(0, 153, 51, 0.8)'))) fig.add_trace(go.Scatter(x=x_Time, y=y5, mode='lines', name='Luminisity', marker = dict(color = 'rgba(0, 0, 204, 0.8)'))) fig.add_trace(go.Scatter(x=x_Time, y=y6, mode='lines', name='Pressure', marker = dict(color = 'rgba(80, 26, 80, 0.8)'))) fig.show() import chart_studio username = '******' # your usernam api_key = 'VQ5pvk3TMJi50tDGdWne' # your api key - go to profile > settings > regenerate keychart_studio.tools.set_credentials_file(username=username, api_key=api_key) chart_studio.tools.set_credentials_file(username=username, api_key=api_key) import chart_studio.plotly as csp csp.plot(fig, showLink= 'false'); #Plotly.plot(divid, data, layout, {showLink: false}) #plt_div = plot(fig, output_type='div', include_plotlyjs=False) #return render(request,'www.http://smartfasal.in/wp/?page_id=277') return HttpResponse("Prcoessed completed")
def investor_vs_category(self, cat_inv_list, plot_type='plotly'): # group by category labels = [] sizes = [] texts = [] sorted_list = sorted(cat_inv_list, key=lambda row: (row[0]) if len(row)>0 else (' ')) cat_idx = 0 for category, rows in groupby(sorted_list, lambda x: x[0] if len(x)>0 else (' ')): count = 0 for row in rows: for idx in range(1, len(row)): count += len(row[idx].split(',')) labels.append(cat_idx) sizes.append(count) texts.append(category) print(cat_idx, ":: ", category) cat_idx += 1 # plot data if plot_type == 'plotly': fig = go.Figure(data=[go.Pie(labels=labels, values=sizes, name='Category vs Investor', text=texts)]) fig.update_layout(title=go.layout.Title(text="Category vs Investor")) py.plot(fig, filename = 'Category vs Investor', auto_open=True) # fig.show() elif plot_type == 'matplotlib': fig1, ax1 = plt.subplots() ax1.pie(sizes, labels=labels) ax1.axis('equal') fig1.savefig('Category vs Investor.png') pass
def funding_pie(self, funding_list, plot_type='plotly'): funding_list = funding_list[0]+funding_list[1] funding_list = [[fund.strip() for fund in funding_string.split(',')] for funding_string in funding_list] funding_count = Counter(list(chain.from_iterable(funding_list))) # {'blue': 3, 'red': 2, 'yellow': 1} print(funding_count) print() labels = [] sizes = [] texts = [] for idx, (funding, count) in enumerate(funding_count.items()): if funding != 'n/a' and funding != '' and funding != '--': # if len(funding) > 12: # # print([fund.strip() for fund in funding.split(',')]) # labels.append([fund.strip() for fund in funding.split(',')]) # else: labels.append(idx) texts.append(funding) sizes.append(count) if plot_type == 'plotly': fig = go.Figure(data=[go.Pie(labels=labels, values=sizes, name='Volume of Each Investor', text=texts)]) fig.update_layout(title=go.layout.Title(text="Volume of Each Investor")) py.plot(fig, filename = 'Volume of Each Investor', auto_open=True) # fig.show() elif plot_type == 'matplotlib': fig1, ax1 = plt.subplots() ax1.pie(sizes, labels=labels) ax1.axis('equal') fig1.savefig('Volume of Each Investor.png') pass
def skuRevenu(self): sku = [] #get sku list for order in self.Collection.find({"orderStatus":{"$in":["Shipped","Pending"]}}): if order["sku"] not in sku: sku.append(order["sku"]) #for each sku get it curve and add to trace plotData = [] for targetSku in sku: orderDates = {} for order in self.Collection.find({"orderStatus":{"$in":["Shipped","Pending"]},"sku":targetSku}).sort("purchaseDate",pymongo.ASCENDING): if order["purchaseDate"] not in orderDates.keys(): try: orderDates[order["purchaseDate"]] = float(order["itemPrice"]) except ValueError: print(order["itemPrice"]) else: orderDates[order["purchaseDate"]] += float(order["itemPrice"]) x = [] y = [] for date in orderDates.keys(): x.append(date) y.append(orderDates[date]) trace = go.Scatter( x = x, y = y, name = targetSku ) plotData.append(trace) #plot(plotData,filename="skuRevenu.html") py.plot(plotData, filename="skuRevenue", auto_open=True)
def subtag_pie(self, subtag_list, plot_type='plotly'): data = [] for subtag_col in subtag_list: data = data + subtag_col subtag_list = np.array(data) subtag_count = Counter( subtag_list) # {'blue': 3, 'red': 2, 'yellow': 1} print(subtag_count) print() labels = [] sizes = [] texts = [] for idx, (subtag, count) in enumerate(subtag_count.items()): if subtag: labels.append(idx) texts.append(subtag) sizes.append(count) print(subtag, ": ", idx) if plot_type == 'plotly': fig = go.Figure( data=[go.Pie(labels=labels, values=sizes, text=texts)]) fig.update_layout(title=go.layout.Title(text="Subtag Prevalence")) py.plot(fig, filename='Subtag Prevalence', auto_open=True) # fig.show() elif plot_type == 'matplotlib': fig1, ax1 = plt.subplots() ax1.pie(sizes, labels=labels) ax1.axis('equal') fig1.savefig('subtag_prevalence.png') pass
def draw_gross_rating(): """ The function plots total rating against average weekly gross """ # read in data gs = pd.read_csv("part2cleanedGrosses.csv", sep=',', encoding='latin1') rt = pd.read_csv("Musical_ratings-withoutNa-cleaned.csv") # prepare data # limit the time scope to recent 5 years testData2 = gs[gs['year'] >= 2015] testData2 = testData2[['show', 'year', 'month', 'this_week_gross']] # calculate avg weekly grosses mean (by show) testData2['avg_weekly_gross'] = testData2.groupby('show')['this_week_gross'].transform('mean') testData2_1 = pd.merge(testData2, rt, on='show') # select distinct show testData2_1 = testData2_1.drop_duplicates('show') # Select relevant columns testData2_1 = testData2_1[['show', 'avg_weekly_gross', 'total_rating']] fig = px.scatter(testData2_1, x="avg_weekly_gross", y="total_rating", color="total_rating", hover_name="show", labels=dict(avg_weekly_gross="Average Weekly Grosses (in USD)", total_rating="Ratings"), color_continuous_scale=px.colors.colorbrewer.RdYlGn, title="Ratings vs. Average weekly grosses of recent 5 years") py.plot(fig, "gross-rating", auto_open=True)
def plot_work_hours(rows): daily = work_hours_daily(rows) weekly = work_hours_weekly(daily) monthly = work_hours_monthly(daily) data = [ go.Scatter( x=daily.Date, y=daily.Hours, mode='markers', name='Days', ), go.Scatter( x=weekly.index, y=weekly.values, mode='lines+markers', name='Weeks', ), go.Scatter( x=monthly.index, y=monthly.values, mode='lines', name='Months', line={ 'dash': 'dash', 'color': 'firebrick', }, ), ] plotly_setup() py.plot(data, filename=f'woкk_hours_{datetime.now().date()}', sharing='public')
def review_overall_hist(yelp): # plot a histogram of the review count figure9 = px.histogram(yelp, x="Review Count") # add title and axis label figure9.update_layout(title_text='Histogram of Review Count') # Display the plot py.plot(figure9, auto_open=True)
def price_overall_hist(yelp): # plot a histogram of the rating figure8 = px.histogram(yelp, x="Price Level") # add title and axis label figure8.update_layout(title_text='Histogram of Price Level') # Display the plot py.plot(figure8, auto_open=True)
def rating_overall_hist(yelp): # plot a histogram of the review count figure10 = px.histogram(yelp, x="Rating") # add title and axis label figure10.update_layout(title_text='Histogram of Rating') # Display the plot py.plot(figure10, auto_open=True)
def create_candlestick(self): r = requests.get( f'https://financialmodelingprep.com/api/v3/historical-price-full/{self.quote}?timeseries={self.days}' ) r = r.json() stockdata = r['historical'] stockdata_df = pd.DataFrame(stockdata) fig = go.Figure(data=[ go.Candlestick(x=stockdata_df['date'], open=stockdata_df['open'], high=stockdata_df['high'], low=stockdata_df['low'], close=stockdata_df['close']) ]) fig.update_layout(title={ 'text': self.quote, 'y': 0.9, 'x': 0.5, 'xanchor': 'center', 'yanchor': 'top' }, font=dict(family="Courier New, monospace", size=20, color="#7f7f7f")) fig.show() py.plot(fig, filename='data', auto_open=True)
def plotMap(draftClassData, latitudeData, longitudeData, colourList): data = [] for i in range(len(playerNames)): trace = go.Scattermapbox(lat=[sitelat[i]], lon=[sitelon[i]], name=playerNames[i], mode='markers', marker=dict(size=draftClassData[i], color='red', opacity=0.7), text=playerNames[i], hoverinfo='text') data.append(trace) layout = go.Layout( title='Popular Cities', autosize=True, hovermode='closest', showlegend=False, mapbox=dict(accesstoken=mapbox_access_token, bearing=0, center=dict(lat=38, lon=-94), pitch=0, zoom=3, style='light'), ) fig = dict(data=data, layout=layout) py.plot(fig, filename='Popular Cities')
def createGraph(listOfYears, proportionsForGenreAll, proportionsForGenreAction, proportionsForOverview): # will prepare data for a t-test / correlation # set up so that it will save to plotly account chart_studio.tools.set_credentials_file(username='******', api_key='quWnfkS81TFD5CzuIDYU') # the listToCheck is the list that will define the binary violent column fig = go.Figure(data=[ go.Bar(name='All Violent Genres', x=listOfYears, y=proportionsForGenreAll), go.Bar( name='Action Movies', x=listOfYears, y=proportionsForGenreAction), go.Bar(name='Violent Movie Descriptions', x=listOfYears, y=proportionsForOverview) ]) # Change the bar mode fig.update_layout( title='proportion of violent movies through the years', barmode='group', yaxis=dict(title='proportion of violent movies in a given year', ), xaxis=dict(title='year', ), ) # save graph to account py.plot(fig, filename="violent_movies_over_time.html", auto_open=True) fig.show()
def nat_bar_plot(df, file_name): plotly_fig = go.Figure(data=[ go.Bar(name='USAU Members', x=df['Race/Ethnicity'], y=df['member_percent_rounded'], text=df['member_percent_rounded'], textposition='outside', hoverinfo='skip'), go.Bar(name='US Census Population', x=df['Race/Ethnicity'], y=df['us_pop_percent_rounded'], text=df['us_pop_percent_rounded'], textposition='outside', hoverinfo='skip') ]) # Change the bar mode plotly_fig.update_layout( barmode='group', legend=dict(orientation="h", y=1.1), xaxis_title="", yaxis_title="Percent of Group", # width=1000, # height=2000, ) # plot(plotly_fig) py.plot(plotly_fig, filename=file_name, auto_open=True)
def makeHeatMap(presyn_connectDict): df = pd.DataFrame.from_dict(presyn_connectDict) #g = sns.clustermap(df, method='ward', metric='euclidean') g = sns.clustermap(df, metric='euclidean') mask = g.mask colList = list(mask.columns) indList = list(mask.index) df = df.reindex(columns=colList) df = df.reindex(indList) x = list(df.columns) y = list(df.index) colorscale = [[0.0, '#000000'], [.000001, '#6D00D1'], [.0002, '#1600FF'], [.0003, '#00FF2C'], [.001, '#DFFF0A'], [.0015, '#FF8A0A'], [.05, '#ff0f0a'], [1, '#BB0000']] heatmap = go.Heatmap(z=df, x=x, y=y, colorscale=colorscale) layout = go.Layout(title="GF Input Type Interconnectivity", xaxis=dict(title="Input", tickmode='linear'), yaxis=dict(title="Output", tickmode='linear')) data = [heatmap] fig = go.Figure(data=data, layout=layout) py.plot( fig, filename='GFInput_Interconnectivity: yaxis = Output; xaxis = Input') return
def plotly_graph(): """ Create interactive plotly graph :return: """ import plotly.graph_objects as go import chart_studio.plotly as py d = Dataset() vocabulary = [f'topic.{i}' for i in range(1, 71)] d_dtm = d.get_document_topic_matrix() male = d.copy().filter(author_gender='male') female = d.copy().filter(author_gender='female') c1_dtm = female.get_document_topic_matrix() * 300 c2_dtm = male.get_document_topic_matrix() * 300 s = StatisticalAnalysis(d_dtm, c1_dtm, c2_dtm, vocabulary) correlated_terms = s.correlation_coefficient( return_correlation_matrix=True) for i in range(70): correlated_terms[i, i] = 0 l = [TOPICS[i]['name'] for i in range(1, 71)] # interactive viz with plotly fig = go.Figure(data=go.Heatmap(z=correlated_terms, x=l, y=l)) fig.show() # online with plotly data = go.Heatmap(z=correlated_terms, x=l, y=l) py.plot([data], filename='topic_cors')
def main(): parser = argparse.ArgumentParser() parser.add_argument('--csv_file_path') args = parser.parse_args() st = TokyoCovid19Stat(args.csv_file_path) cases_by_age = melt(st.cases_by_age, value_columns=TokyoCovid19Stat.AGECOLNAMES, var_name='Age') sma_by_age = melt(sma(st.cases_by_age), value_columns=TokyoCovid19Stat.AGECOLNAMES, var_name='Age') title = 'Tokyo Covid-19 New Cases By Age' fig = px.area(cases_by_age, x='Date', y='Cases', color='Age', title=title) py.plot(fig, filename=title, auto_open=False) title = 'Tokyo Covid-19 New Cases 7-day Moving Average By Age' fig = px.line(sma_by_age, x='Date', y='Cases', color='Age', title=title) fig.add_bar(x=st.cases.index, y=st.cases['Cases'], name='Raw Total', marker=dict(color='#dddddd')) py.plot(fig, filename=title, auto_open=False)
def main(): parser = argparse.ArgumentParser() parser.add_argument('--csv_file_path') args = parser.parse_args() if args.csv_file_path is None: return st = TokyoCovid19Stat(args.csv_file_path) cases_by_area = melt(st.cases_by_area, value_columns=st.area_list, var_name='Area') sma_by_area = melt(sma(st.cases_by_area), value_columns=st.area_list, var_name='Area') # title = 'Tokyo Covid-19 New Cases By Area' # fig = px.area(cases_by_area, x='Date', y='Cases', color='Area', title=title) # py.plot(fig, filename=title, auto_open=False) title = '[TEST] Tokyo Covid-19 New Cases 7-day Moving Average By Area' fig = px.line(sma_by_area, x='Date', y='Cases', color='Area', title=title) fig.add_bar(x=st.cases.index, y=st.cases['Cases'], name='Raw Total', marker=dict(color='#dddddd')) py.plot(fig, filename=title, auto_open=False)
def createFigure(myDataFrame): myDataFrame['text'] = myDataFrame['case'] + \ '<br>Total Victims: ' + (myDataFrame['total_victims']).astype(str) limits = [(0, 6), (7, 15), (16, 605)] colors = ["royalblue", "crimson", "lightseagreen"] fig = go.Figure() fig.add_trace( go.Scattergeo(locationmode='USA-states', lon=myDataFrame['longitude'], lat=myDataFrame['latitude'], text=myDataFrame['text'], marker=dict(size=myDataFrame['total_victims'], color=colors[0], line_color='rgb(40,40,40)', line_width=0.5, sizemode='area'), name="mass shootings by location and number of victims")) fig.update_layout( title_text= 'Mass Shootings Corresponding to Total Victims Across the United States', showlegend=True, geo=dict( scope='usa', landcolor='rgb(217, 217, 217)', ), ) py.plot(fig, filename="map_of_mass_shootings.html", auto_open=True) fig.show()
def plotly_graph(deaths_array, cases_array): """ WHAT IT DOES: creates a Plotly graph containing data from the last 14 days PARAMETERS: passes in a deaths and cases array RETURNS: a graph """ length = len(deaths_array) i = 1 pd = [] pc = [] while i < 15: pd.append(deaths_array[length - i]) pc.append(cases_array[length - i]) i = i + 1 deaths = go.Scatter(x=[14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1], y=[ pd[0], pd[1], pd[2], pd[3], pd[4], pd[5], pd[6], pd[7], pd[8], pd[9], pd[10], pd[11], pd[12], pd[13] ]) cases = go.Scatter(x=[14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1], y=[ pc[0], pc[1], pc[2], pc[3], pc[4], pc[5], pc[6], pc[7], pc[8], pc[9], pc[10], pc[11], pc[12], pc[13] ]) data = [deaths, cases] py.plot(data, filename='basic-line', auto_open=True)
def onlyFindSoma(DN_DF): FindSoma_DF = DN_DF[DN_DF['Soma Hemisphere'] == "FindSoma"] fig = px.sunburst(FindSoma_DF, path=['DT Hemisphere', 'Soma Hemisphere', 'Status'], title="DN Tract - FindSoma - Status") py.plot(fig, filename="DN Tract - FindSoma - Status") return
def vis4(permits2018): # Get all rows where permit type is Construction constPermits = permits2018.loc[permits2018['PERMIT_TYPE_NAME'] == 'CONSTRUCTION'] # The labels will be the cluser numbers (1-39) clusterLabels = [] # The values will be the count permits in each cluster clusterValues = [] for x in range(1,40): # Get all rows in permits2010 dataframe where the cluster is equal to x clusterRows = constPermits.loc[constPermits['NEIGHBORHOODCLUSTER'] == x] # Count how many permits were filled in cluster x rowCount = clusterRows.shape[0] # Add it to the values list clusterValues.append(rowCount) # Add value of x to labels list clusterLabels.append(x) # Add title myLayout = go.Layout( title = "Percentage of Construction Permits Filed in DC Clusters in 2018", ) # Assign data to appropriate axis on heatmap myData = go.Pie( labels = clusterLabels, values = clusterValues ) # Setup figure myFigure = go.Figure(data=myData, layout=myLayout) # Display the scatterplot py.plot(myFigure, filename='2018 Permits Pie Chart')
def vis6(census2010): # Create trace with x-axis as % white and y-axis as median income trace = go.Scatter( x = census2010['%WHITE'], y = census2010['FAGI_MEDIAN_2015'], hovertext = census2010['NEIGHBORHOODCLUSTER'], mode = 'markers' ) # Assign it to an trace object named myData myData = [trace] # Add axis and title myLayout = go.Layout( title = "Relationship Between Population of White People and Income in 2015", xaxis=dict( title = 'Population of White People in Tract' ), yaxis=dict( title = 'Median Income (USD)' ) ) # Setup figure myFigure = go.Figure(data=myData, layout=myLayout) # Display the scatterplot py.plot(myFigure, filename='2015 ScatterPlot')
def plotMap(latitudeData, longitudeData, draftYears, colourList, draftClassData): data = [] for i in range(len(colourList)): roundNumber = str(i) trace = go.Scattermapbox(lat=latitudeData[i], lon=longitudeData[i], name=str(draftYears[i]) + ' Class', mode='markers', marker=dict(size=(i + 10) / 2, color=colourList[i], opacity=0.7), text=draftClassData[i], hoverinfo='text') data.append(trace) layout = go.Layout( title='1996 to 2017 NBA Draft', autosize=True, hovermode='closest', showlegend=True, #scope='usa', mapbox=dict(accesstoken=mapbox_access_token, bearing=0, center=dict(lat=38, lon=-94), pitch=0, zoom=3, style='light'), legend=dict(traceorder='reversed')) fig = dict(data=data, layout=layout) py.plot(fig, filename='1996 to 2017 NBA Player Drafts')
def api(key, fig): username = '******' api_key = str(key) chart_studio.tools.set_credentials_file(username=username, api_key=api_key) py.plot(fig, filename='nlp_protein_papers', auto_open=False) print( tls.get_embed('https://plotly.com/~tadorfer/1/')) #change to your url
def graph_OHLC(self): #not quite there, but the other one works, which is what i really care about OHLC_trace = go.Ohlc(x=self.OHLC_data.Date_Time, open=self.OHLC_data.Open, high=self.OHLC_data.High, low=self.OHLC_data.Low, close=self.OHLC_data.Close, name="OHLC Data", increasing=dict(line=dict(color='#408e4a')), decreasing=dict(line=dict(color='#cc2718'))) swing_data = pd.read_csv( self.swing_file, names=['Date_Time', 'Price', 'Direction', 'Row'], parse_dates=True) swing_trace = go.Scatter(x=swing_data.Date_Time, y=swing_data.Price, mode='lines+markers', name='Swings', line=dict(color=('rgb(111, 126, 130)'), width=3)) data = [OHLC_trace, swing_trace] layout = go.Layout(xaxis=dict(rangeslider=dict(visible=False)), title=self.data_file[:-4]) fig = go.Figure(data=data, layout=layout) py.plot(fig, filename=self.data_file + ".html", output_type='file')
def maturity_vs_tag(self, mat_tag_list, plot_type='plotly'): # group by tag data = {} labels = [] sizes = [] subplot_titles = [] sorted_list = sorted(mat_tag_list, key=lambda row: (row[4]) if len(row)>4 else (' ')) for tag1, tag1_rows in groupby(sorted_list, lambda x: x[4] if len(x)>4 else ' '): if tag1 != '' and tag1 != ' ': for maturity, mat_rows in groupby(list(tag1_rows), lambda x: x[0] if len(x)>0 else ' '): if maturity != ' ' and maturity != '': sizes.append(len(list(mat_rows))) labels.append(maturity) print(":: ", tag1) data[tag1] = [sizes[:], labels[:]] subplot_titles.append(tag1) sorted_list = sorted(mat_tag_list, key=lambda row: (row[5]) if len(row)>5 else (' ')) for tag2, tag2_rows in groupby(sorted_list, lambda x: x[5] if len(x)>5 else ' '): if tag2 != ' ' and tag2 != '': for maturity, mat_rows in groupby(list(tag2_rows), lambda x: x[0] if len(x)>0 else ' '): if maturity != ' ' and maturity != '': sizes.append(len(list(mat_rows))) labels.append(maturity) if tag2 in list(data.keys()): for new_idx, label in enumerate(labels): if label in data[tag2][1]: old_idx = data[tag2][1].index(label) data[tag2][0][old_idx] += sizes[new_idx] else: data[tag2].append([sizes[new_idx], label]) else: print("&& ", tag2) data[tag2] = [sizes[:], labels[:]] subplot_titles.append(tag2) # plot data if plot_type == 'plotly': domain = [[{'type':'domain'}, {'type':'domain'}, {'type':'domain'}], [{'type':'domain'}, {'type':'domain'}, {'type':'domain'}]] fig = make_subplots(rows=2, cols=3, specs=domain, subplot_titles=subplot_titles[:7]) print("Subplot Title: ", subplot_titles) for idx, (key, value) in enumerate(data.items()): if idx+1<4: fig.add_trace(go.Pie(labels=value[1], values=value[0], name=key, text=value[1]), 1,idx+1) elif idx+1<7: fig.add_trace(go.Pie(labels=value[1], values=value[0], name=key, text=value[1]), 2,idx-2) fig.update_layout(title_text="Maturity vs Tag") py.plot(fig, filename = 'Maturity vs Tag', auto_open=True) # fig.show() elif plot_type == 'matplotlib': fig1, ax1 = plt.subplots() ax1.pie(sizes, labels=labels) ax1.axis('equal') fig1.savefig('Maturity vs Tag.png') pass
def review_city_box(yelp): # second plot # it will be a boxplot figure1 = px.box(yelp, x="City", y="Review Count") figure1.update_layout(title_text="Boxplot of Review Count in Each City") # Display the plot py.plot(figure1, auto_open=True)
def SankeyItemTrees(Com_dfs=[], Labels=[], Projection='Item'): """Create Sankey diagrams illustrating shifts in community belonging with variable number of timepoints. Keyword arguments: Coms_dfs -- list of dataframes of community belonging by item from either FindCommunities or IterativeCommunityFinding Labels -- list of labels to associate with each community dataframe Projection -- either Item or Students, which level the networks have been projected """ assert (len(Com_dfs) == len(Labels)) Colors = cl.scales[str(max(len(Com_dfs), 3))]['div']['RdYlBu'] Source = [] Target = [] Value = [] for df in Com_dfs: df['Item'] = df.index for i, df in enumerate(Com_dfs): if (i == len(Com_dfs) - 1): break Com_dfs[i + 1].loc[:, 'Community'] = Com_dfs[ i + 1].loc[:, 'Community'] + Com_dfs[i].loc[:, 'Community'].max() + 1 for c_pre in range(Com_dfs[i].loc[:, 'Community'].max() + 1): for c_post in range(Com_dfs[i + 1].loc[:, 'Community'].min(), Com_dfs[i + 1].loc[:, 'Community'].max() + 1): Link = sum(Com_dfs[i + 1].loc[ Com_dfs[i + 1].loc[:, 'Community'] == c_post, Projection].isin( Com_dfs[i].loc[Com_dfs[i].loc[:, 'Community'] == c_pre, Projection])) Source.append(c_pre) Target.append(c_post) Value.append(Link) data = dict( type='sankey', node=dict(pad=15, thickness=20, line=dict(color="black", width=0.5), label=[ Labels[i] + str(c) for i in range(len(Com_dfs)) for c in range(Com_dfs[i].loc[:, 'Community'].max() - Com_dfs[i].loc[:, 'Community'].min() + 1) ], color=[ Colors[i] for i in range(len(Com_dfs)) for c in range(Com_dfs[i].loc[:, 'Community'].max() - Com_dfs[i].loc[:, 'Community'].min() + 1) ]), link=dict(source=Source, target=Target, value=Value)) layout = dict(title="Response choice community Shifts", font=dict(size=20)) fig = dict(data=[data], layout=layout) py.plot(fig, validate=False)
def test_initialize_stream_plot(self): py.sign_in(un, ak) stream = Stream(token=tk, maxpoints=50) url = py.plot([Scatter(x=[], y=[], mode='markers', stream=stream)], auto_open=False, world_readable=True, filename='stream-test') assert url == 'https://plot.ly/~PythonAPI/461' time.sleep(.5)
def test_stream_multiple_points(self): py.sign_in(un, ak) stream = Stream(token=tk, maxpoints=50) url = py.plot([Scatter(x=[], y=[], mode='markers', stream=stream)], auto_open=False, world_readable=True, filename='stream-test') time.sleep(.5) my_stream = py.Stream(tk) my_stream.open() my_stream.write(Scatter(x=[1, 2, 3, 4], y=[2, 1, 2, 5])) time.sleep(.5) my_stream.close()
def test_stream_layout(self): py.sign_in(un, ak) stream = Stream(token=tk, maxpoints=50) url = py.plot([Scatter(x=[], y=[], mode='markers', stream=stream)], auto_open=False, world_readable=True, filename='stream-test') time.sleep(.5) title_0 = "some title i picked first" title_1 = "this other title i picked second" my_stream = py.Stream(tk) my_stream.open() my_stream.write(Scatter(x=[1], y=[10]), layout=Layout(title=title_0)) time.sleep(.5) my_stream.close() my_stream.open() my_stream.write(Scatter(x=[1], y=[10]), layout=Layout(title=title_1)) my_stream.close()
def _handle_msg(self, message): """Handle a msg from the front-end. Args: content (dict): Content of the msg. """ content = message['content']['data']['content'] if content.get('event', '') == 'pong': self._graphId = content['graphId'] # ready to recieve - pop out all of the items in the deque while self._clientMessages: _message = self._clientMessages.popleft() _message['graphId'] = self._graphId _message = _json.dumps(_message) self._message = _message if content.get('event', '') in ['click', 'hover', 'zoom']: # De-nest the message if content['event'] == 'click' or content['event'] == 'hover': message = content['message']['points'] elif content['event'] == 'zoom': message = content['message']['ranges'] self._event_handlers[content['event']](self, message) if content.get('event', '') == 'getAttributes': self._attributes = content.get('response', {}) # there might be a save pending, use the plotly module to save if self._flags['save_pending']: self._flags['save_pending'] = False url = py.plot(self._attributes, auto_open=False, filename=self._filename, validate=False) self._new_url = url self._fade_to('slow', 1)