def make_traces(self, main_chart=ChartType.kline, sub_chart="bar", yaxis="y", scale_value=None, **kwargs): traces = [] sub_traces = [] for entity_id, df in self.main_data.entity_map_df.items(): df = df.select_dtypes(np.number) df = df.copy() if scale_value: for col in df.columns: first = None for i in range(0, len(df)): first = df[col][i] if first != 0: break if first == 0: continue scale = scale_value / first df[col] = df[col] * scale code = entity_id try: _, _, code = decode_entity_id(entity_id) except Exception: pass # 构造主图 if main_chart == ChartType.bar: for col in df.columns: trace_name = "{}_{}".format(code, col) ydata = df[col].values.tolist() traces.append( go.Bar(x=df.index, y=ydata, name=trace_name, yaxis=yaxis, **kwargs)) elif main_chart == ChartType.kline: trace_name = "{}_kdata".format(code) trace = go.Candlestick( x=df.index, open=df["open"], close=df["close"], low=df["low"], high=df["high"], name=trace_name, yaxis=yaxis, **kwargs, ) traces.append(trace) elif main_chart in [ ChartType.scatter, ChartType.line, ChartType.area ]: mode = _zvt_chart_type_map_scatter_mode.get(main_chart) for col in df.columns: trace_name = "{}_{}".format(code, col) ydata = df[col].values.tolist() traces.append( go.Scatter(x=df.index, y=ydata, mode=mode, name=trace_name, yaxis=yaxis, **kwargs)) elif main_chart == ChartType.histogram: for col in df.columns: trace_name = "{}_{}".format(code, col) x = df[col].tolist() trace = go.Histogram(x=x, name=trace_name, **kwargs) traces.append(trace) annotation = [ dict( entity_id=entity_id, timestamp=x[-1], value=0, flag=f"{trace_name}:{x[-1]}", ) ] annotation_df = pd.DataFrame.from_records( annotation, index=["entity_id", "timestamp"]) if pd_is_not_null(self.annotation_df): self.annotation_df = pd.concat( [self.annotation_df, annotation_df]) else: self.annotation_df = annotation_df elif main_chart == ChartType.pie: for _, row in df.iterrows(): traces.append( go.Pie(name=entity_id, labels=df.columns.tolist(), values=row.tolist(), **kwargs)) else: assert False # 构造主图指标 if self.factor_data_list: for factor_data in self.factor_data_list: if not factor_data.empty(): factor_df = factor_data.entity_map_df.get(entity_id) factor_df = factor_df.select_dtypes(np.number) if pd_is_not_null(factor_df): for col in factor_df.columns: trace_name = "{}_{}".format(code, col) ydata = factor_df[col].values.tolist() line = go.Scatter(x=factor_df.index, y=ydata, mode="lines", name=trace_name, yaxis=yaxis, **kwargs) traces.append(line) # 构造幅图 if self.has_sub_plot(): for sub_data in self.sub_data_list: sub_df = sub_data.entity_map_df.get(entity_id) if pd_is_not_null(sub_df): sub_df = sub_df.select_dtypes(np.number) for col in sub_df.columns: trace_name = "{}_{}".format(code, col) ydata = sub_df[col].values.tolist() def color(i): if i > 0: return "red" else: return "green" colors = [color(i) for i in ydata] the_sub_chart = None if self.sub_col_chart is not None: the_sub_chart = self.sub_col_chart.get(col) if not the_sub_chart: the_sub_chart = sub_chart if the_sub_chart == ChartType.line: sub_trace = go.Scatter( x=sub_df.index, y=ydata, name=trace_name, yaxis="y2", marker=dict(color=colors)) else: sub_trace = go.Bar(x=sub_df.index, y=ydata, name=trace_name, yaxis="y2", marker=dict(color=colors)) sub_traces.append(sub_trace) return traces, sub_traces
## Describing data according to the Feedback Alexa_train.groupby('feedback').describe() ### Data Visulization ## Distribution of ratings of Alexa ratings = Alexa_train['rating'].value_counts() label_rating = ratings.index size_rating = ratings.values Colors = ['pink', 'lightblue', 'aqua', 'gold', 'crimson'] rating_Piechart = go.Pie(labels=label_rating, values=size_rating, marker=dict(colors=Colors), name='Alexa', hole=0.3) df = [rating_Piechart] layout = go.Layout(title='Distribution of Ratings for Alexa') fig = go.Figure(data=df, layout=layout) #fig=go.Figure(data=[go.Pie(labels=label_rating,values=size_rating,marker=dict(colors=Colors),name='Alexa',hole=0.3)],layout=layout) py.offline.plot(fig, filename='Pie_Chart1.html') ### BAR PLOT #linespace color = plt.cm.copper(np.linspace(0, 1, 15)) Alexa_train['variation'].value_counts().plot.bar(color=color, figsize=(15, 9))
{ 'data': [Q2_Top5Plot_Bronx], 'layout': { 'title': 'Top 5 complaints for the borough of Bronx', 'margin': { 'l': '180' } } }, filename='Q2_Top5_Bronx') # Q3. Proportion of Open, Closed and Pending Complaints ComplaintStatus_Q3 = spark.sql( 'SELECT Status,COUNT(Status) AS Counts FROM TABLE GROUP BY STATUS') Q3_PieComplaintStatus = go.Pie(labels=ComplaintStatus_Q3.toPandas()['Status'], values=ComplaintStatus_Q3.toPandas()['Counts'], textinfo='label+percent') py.plot( { 'data': [Q3_PieComplaintStatus], 'layout': { 'title': 'Proportion of Closed and Open complaints' } }, filename='Q3_ComplaintStatus', image='png') # Q4. Total Complaints over the years Q4_TotalComplaints = spark.sql( 'SELECT COUNT(*) AS `Number of Complaints`,SUBSTRING(`Created Date`,0,4) AS Year FROM TABLE GROUP BY SUBSTRING(`Created Date`,0,4) ORDER BY Year desc' )
def interactive(): response = '' while True: response = input('Enter a command: ') if response.strip() == '': continue if response == 'help': print(help_text) continue elif response == 'exit': print("bye") break elif response[: 24] == 'tv popularity and rating' or response[: 21] == 'tv country and rating' or response[: 22] == 'tv #released per month' or response[: 20] == 'tv ratings and month': try: tuple = process_command(response) except: print("Command not recognized: " + response) continue length_format = [] if not tuple: print("No matched results") continue if response[:24] == 'tv popularity and rating': tuple_print = [('TvName', 'Popularity', 'Rating')] + tuple elif response[:21] == 'tv country and rating': tuple_print = [('Country', 'Rating')] + tuple elif response[:22] == 'tv #released per month': tuple_print = [('Month', 'Count')] + tuple elif response[:20] == 'tv ratings and month': tuple_print = [('Month', 'Avg Rating')] + tuple else: continue # print out results for index in range(len(tuple_print[0])): maxlen = -1 for row1 in tuple_print: if len(str(row1[index])) > maxlen: maxlen = len(str(row1[index])) length_format.append(maxlen) for line_temp in tuple_print: for j in range(len(line_temp)): format_string = "{0:<" + str(length_format[j]) + "s}" print(format_string.format(str(line_temp[j])), end=" ") print("") if response[:24] == 'tv popularity and rating': x_rating = [] y_popularity = [] for line_data in tuple: y_popularity.append(line_data[1]) x_rating.append(line_data[2]) trace = go.Scatter(x=x_rating, y=y_popularity, mode='markers') layout = dict(title='Population v.s. rating', xaxis_title="Rating", yaxis_title="Popularity") data = [trace] fig = go.Figure(data=data) fig = fig.update_layout(layout) fig.write_html('scatter.html', auto_open=True) elif response[:21] == 'tv country and rating': x_bar = [] # rating y_bar = [] # country for line_data in tuple: x_bar.insert(0, line_data[1]) y_bar.insert(0, line_data[0]) trace = go.Bar(x=x_bar, y=y_bar, orientation='h', marker=dict(color='rgba(246, 78, 139, 0.8)', )) layout = dict(title='Barplot of country with Tv rating', xaxis_title="Rating", yaxis_title="Country") data = [trace] fig = go.Figure(data=data) fig = fig.update_layout(layout) fig.write_html('bar.html', auto_open=True) elif response[:22] == 'tv #released per month': values_pie = [] labels_pie = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ] for line_data in tuple: values_pie.append(line_data[1]) trace = go.Pie( labels=labels_pie, values=values_pie, sort=False, ) layout = dict( title='Pie chart of the number of TVs per month', ) data = [trace] fig = go.Figure(data=data) fig = fig.update_layout(layout) fig.write_html('pie.html', auto_open=True) elif response[:20] == 'tv ratings and month': x_line = [] y_line = [] for line_data in tuple: x_line.append(line_data[0]) y_line.append(line_data[1]) trace = go.Scatter(x=x_line, y=y_line, mode='lines+markers', name='lines+markers') layout = dict(title='Line chart of ratings v.s. month in 2018', xaxis_title="Month", yaxis_title="Rating") data = [trace] fig = go.Figure(data=data) fig = fig.update_layout(layout) fig.write_html('line.html', auto_open=True) else: print("Command not recognized: " + response)
Header(), #dcc.Link('', href='/jrc/job_analysis', className="tab"), # Row 3 html.Div([ html.Div([ html.H6(["Distribution of job as per Years of Experience"], className="gs-header gs-table-header padded") ], className="row "), html.Div([ dcc.Graph(id='graph-4', figure={ 'data': [ go.Pie(labels=labels, values=val, name="Years of Experience", hoverinfo='label+value+percent+name') ], 'layout': { 'height': 500, 'clickmode': 'event+select' } }), ], className="row ") ], className="subpage1") ]) #Layout for time series trend for job openings tra = html.Div([
def update_revenue(year, region, state, service): filtered_data = car_data if year != 'All': filtered_data = filtered_data[filtered_data['invoice_year'] == int( year)] if region != 'All': filtered_data = filtered_data[filtered_data['Region'] == region] if state != 'All': filtered_data = filtered_data[filtered_data['State'] == state] if service != 'All': filtered_data = filtered_data[filtered_data['Order Type'] == service] revenue_data = filtered_data class_revenue = pd.DataFrame( revenue_data.groupby([ 'Car_Class' ])['Total Amt Wtd Tax.'].sum()).sort_values(by='Total Amt Wtd Tax.', ascending=False) fig_1 = go.Figure(data=[ go.Pie(labels=class_revenue.index, values=class_revenue['Total Amt Wtd Tax.']) ]) fig_1.update_traces(hoverinfo='label+value', textinfo='percent', textfont_size=20, hole=0.4) fig_1.update_layout(title_text="Distribution of Revenue by Car Class", annotations=[ dict(text=state, x=0.5, y=0.5, font_size=15, showarrow=False) ]) make_count = pd.DataFrame( revenue_data.groupby([ 'Make' ])['Total Amt Wtd Tax.'].sum()).sort_values(by='Total Amt Wtd Tax.', ascending=False).head(15) fig_2 = go.Figure( data=[go.Bar(x=make_count.index, y=make_count['Total Amt Wtd Tax.'])]) fig_2.update_layout(title_text="Revenue by Car Companies", xaxis=dict(title='Car Make', categoryorder='total descending'), yaxis=dict(title='Revenue')) # fig_2 = go.Figure(data=[go.Pie(labels = make_count.index, # values=make_count['Regn No'])]) # fig_2.update_traces(hoverinfo='label+value', textinfo='percent', textfont_size=20, hole = 0.4) # fig_2.update_layout(title_text = "Car Make: {}".format(state), annotations=[dict(text = state, x = 0.5, y = 0.5, font_size=15, showarrow=False)]) model_count = pd.DataFrame( revenue_data.groupby([ 'Model' ])['Total Amt Wtd Tax.'].sum()).sort_values(by='Total Amt Wtd Tax.', ascending=False).head(15) fig_3 = go.Figure(data=[ go.Bar(x=model_count.index, y=model_count['Total Amt Wtd Tax.']) ]) fig_3.update_layout(title_text="Revenue by Car Models", xaxis=dict(title='Car Model', categoryorder='total descending'), yaxis=dict(title='Revenue')) return fig_1, fig_2, fig_3
#pie_data = [ # {"company": "Company X", "market_share": 0.55}, # {"company": "Company Y", "market_share": 0.30}, # {"company": "Company Z", "market_share": 0.15} #] #print("----------------") #print("GENERATING PIE CHART...") #print(pie_data) # TODO: create a pie chart based on the pie_data import plotly import plotly.graph_objs as go colors = ['gold', 'mediumturquoise', 'darkorange'] fig = go.Figure(data=[ go.Pie(labels=['Company X', 'Company Y', 'Company Z'], values=[0.55, 0.30, 0.15]) ]) #layout=(title="Pie Chart"))]) #layout(title="Pie Chart") fig.update_traces(hoverinfo='label+percent', textinfo='value', textfont_size=20, marker=dict(colors=colors, line=dict(color='#000000', width=2))) fig.show() # # CHART 2 (LINE) # #line_data = [
value='Claim Amount'), className='col-3'), html.Div([ ## Graph Pie dcc.Graph( id='contoh-graph-pie', figure={ 'data': [ go.Pie(labels=[ '{}'.format(i) for i in list(dfTsa_plot[ 'Claim Type'].unique()) ], values=[ dfTsa_plot.groupby( 'Claim Type'). mean() ['Claim Amount'][i] for i in list(dfTsa_plot[ 'Claim Type']. unique()) ], sort=False) ], 'layout': { 'title': 'Mean Pie Chart' } }) ]) ]) ],
def update_graph(select_index): if select_index == '1': figure = { 'data': [ go.Scatter( x=d1['日期'].tolist(), y=d1[yi].tolist(), mode='lines', name=city+yi ) for yi in ['最高温度','最低温度','紫外线强度指数'] ], 'layout': [ go.Layout( height=350, hovermode='closest', title='折线图' ) ] } return figure elif select_index == '2': figure = { 'data': [ go.Bar( x=d1['日期'].tolist(), y=d1[yi].tolist(), name=city+yi ) for yi in ['相对湿度','能见度(公里)','风速(公里/小时)']], 'layout': [ go.Layout( height=350, hovermode='closest', title='条形图', ) ] } return figure elif select_index=='3': figure = { 'data': [ go.Pie( labels=quality_level, values=quality_count, name='legend' )], 'layout': [ go.Layout( height=350, hovermode='closest', title='饼状图' ) ] } return figure elif select_index=='4': figure = { 'data': [ go.Scatter( x=df3['Longitude'].tolist(), y=df3['Latitude'].tolist(), text = df3['text'].tolist(), mode='markers', marker={'size': 15}, name='legend' )], 'layout': [ go.Layout( height=350, hovermode='closest', title ='散点图' ) ] } return figure
top5_average_rating = round(top5_rating_sum/top5_num,2) #calculate all average rating all_num=0 all_rating_sum=0 for i in range(0,10): all_num+=all_value_lst[i] for i in range(0,10): all_rating_sum+=float(all_value_lst[i])*float(all_key_lst[i]) all_average_rating = round(all_rating_sum/all_num,2) #save chart to image and render trace1 = go.Pie( labels=top5_key_lst, values=top5_value_lst, domain=dict(x=[0,0.4], y=[0,0.4]), sort=False, hole=0.4 ) trace2 = go.Bar( x=top5_key_lst, y=top5_value_lst, xaxis='x2', yaxis='y2', marker=dict(color="maroon"), showlegend=False ) trace3 = go.Pie( labels=all_key_lst, values=all_value_lst, domain=dict(x=[0,0.4], y=[0.6,1]),
state_average_funding = pd.DataFrame({'Donor State':donor_state_amount_project['Donor State'][-5:][::-1],'Average Funding':val[-5:][::-1]}) sns.barplot(x="Donor State",y="Average Funding",data=state_average_funding) # # <a id='4-6'>4.6 Percentage of donors as teachers</a> # In[ ]: per_teacher_as_donor = donors['Donor Is Teacher'].value_counts().to_frame().reset_index() per_teacher_as_donor = per_teacher_as_donor.rename(columns= {'index': 'Types'}) labels = ['Donor is a Teacher','Donor is not a Teacher'] values = per_teacher_as_donor['Donor Is Teacher'].tolist() colors = ['#96D38C', '#E1396C'] trace = go.Pie(labels=labels, values=values, hoverinfo='label+percent', textinfo='value', textfont=dict(size=20), marker=dict(colors=colors, line=dict(color='#000000', width=2))) py.iplot([trace], filename='styled_pie_chart') # # <a id='4-7'>4.7 Top Donor Checked Out carts</a> # In[ ]: temp = donors_donations['Donor Cart Sequence'].value_counts().head() df = pd.DataFrame({'labels': temp.index,'values': temp.values}) labels = df['labels'].tolist() values = df['values'].tolist() colors = ['#96D38C', '#E1396C','#C0C0C0','#FF0000','#F08080'] trace = go.Pie(labels=labels, values=values,
"""# Participación de los Cuentahabientes Garantizados""" import plotly.graph_objects as go fig = go.Figure() x1 = ['BANPRO', 'BANCENTRO', 'BAC', 'BDF', 'FICOHSA', 'AVANZ', 'ATLANTIDA'] y1 = [33.9, 35.6, 22.5, 4.0, 1.5, 2.5, 0.007] colors_bancos = [ '#66A731', '#006837', '#E3002B', '#0075BF', '#07C0DB', '#F48028', '#A61A11' ] fig.add_trace( go.Pie(labels=x1, values=y1, hole=.4, marker_colors=colors_bancos)) fig.update_layout( barmode='stack', xaxis_type='category', title= '<b></b><b>Participación de los Cuentahabientes Garantizados</b><br><i>Porcentajes</i><br><i>31 de Agosto 2020</i>', paper_bgcolor='rgb(255, 255, 255)', plot_bgcolor='rgb(255, 255, 255)', font=dict(family="Courier New, monospace", size=18, color="#000000"), annotations=[ dict( x=1, #0.5, y=-0.20, #-0.15, showarrow=False, text="Fuente: FOGADE",
us = csv.reader(userfile) next(us, None) countmovies = len(list(mv)) countusers = len(list(us)) moviefile.seek(0) userfile.seek(0) def Cloning(li1): li_copy = list(li1) return li_copy moviefile.seek(0) gencount = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] genre = [ 'Biography', 'Horror', 'Crime', 'Animation', 'Musical', 'Romance', 'Family', 'Comedy', 'Thriller', 'Mystery', 'History', 'Sci-Fi', 'Fantasy', 'Drama', 'Sport', 'War' ] listd = [] for row in mv: listd = (row[8]) for j in range(0, 16): if listd.find(genre[j]) != -1: gencount[j] += 1 trace = go.Pie(labels=genre, values=gencount) py.offline.plot([trace], filename='genre_splitup.html', auto_open=False) print("Generated Genre Splitup")
movies.movie_name, COUNT(cinema_session.ticket_number_fk) FROM cinema_session INNER JOIN movies ON cinema_session.movie_id_fk = movies.movie_id GROUP BY movies.movie_name """) movies = [] movie_tickets_count = [] for row in cursor.fetchall(): movies.append(row[0]) movie_tickets_count.append(row[1]) pie = go.Pie(labels=movies, values=movie_tickets_count) movies_proportion_url = py.plot([pie], filename='movies-proportion') """ create plot 3 """ cursor.execute(""" SELECT cinema_session.buy_date, COUNT(cinema_session.ticket_number_fk) FROM cinema_session GROUP BY cinema_session.buy_date ORDER BY cinema_session.buy_date """) buy_dates = []
title="Fare Distribution", xaxis_title="Passanger ID", yaxis_title="Fare" ) ), config={ 'displayModeBar': False } ), ], className="six columns"), html.Div([ dcc.Graph( id='graph3', figure=go.Figure( data=[go.Pie( labels=barData.json()['labels'], values=barData.json()['values'] )], layout=go.Layout( title="Passanger Class Distribution", ) ), config={ 'displayModeBar': False } ) ], className="six columns") ], className="row") ])
'plot_bgcolor': colors['plot_color'], 'paper_bgcolor': colors['paper_color'], 'title': 'Visitors Count', 'font':{ 'color': colors['text'] } } } ) ]), html.Div([ dcc.Graph( id = 'pie', figure=go.Figure( data = [ go.Pie(labels = data_gen.states, values = data_gen.states_cnt)], layout= go.Layout( title = 'Statewise vistors' ) ) ) ]), html.Div([ dcc.Graph( id = 'page-visits', figure=go.Figure( data = [ go.Bar(x = data_gen.pages, y = data_gen.pg_cnt)], layout= go.Layout( title = 'Statewise vistors' )
sns.scatterplot(x=Combined_data['latitude'], y=Combined_data['longitude']) plt.show() sns.catplot(x='room_type', kind='count', data=Combined_data) fig = plt.gcf() fig.set_size_inches(8, 6) plt.show() import plotly.offline as pyo import plotly.graph_objs as go roomdf = Combined_data.groupby( 'room_type').size() / Combined_data['room_type'].count() * 100 labels = roomdf.index values = roomdf.values # Use `hole` to create a donut-like pie chart fig = go.Figure(data=[go.Pie(labels=labels, values=values, hole=.6)]) plt.show() plt.figure(figsize=(10, 6)) sns.countplot(x='room_type', hue="neighbourhood", data=Combined_data) plt.title("Room types occupied by the neighbourhood") plt.show() #catplot room type and price plt.figure(figsize=(10, 6)) sns.catplot(x="room_type", y="price", data=Combined_data) plt.ioff() fig, axes = plt.subplots(1, 2, figsize=(21, 6)) sns.distplot(Combined_data['minimum_nights'],
# Create the option to display charts that show the stats # for gender representation for the last 120 years if st.sidebar.checkbox("Gender Representation"): male = df[df["Sex"] == "M"]["ID"].agg("count") female = df[df["Sex"] == "F"]["ID"].agg("count") fig1 = px.histogram(df, x="Year", color="Sex", title="Gender Representation 1896-2016") st.plotly_chart(fig1) labels = ["Male Participants", "Female Participants"] values = [male, female] layout = go.Layout(title="Total Ratio Of Participants") fig2 = go.Figure(data=[go.Pie(labels=labels, values=values, hole=0.5)], layout=layout) st.plotly_chart(fig2) # Create the option to display information about the # yearly total of participants if st.sidebar.checkbox("Participants: Yearly Total"): df["Games"] = df["Games"].fillna("0") df = pd.DataFrame(df) games = df["Games"].value_counts() trace = go.Bar( x=games.index, y=games.values, marker=dict(color=games.values, colorscale="Plotly3", showscale=True), )
# EDA percentual_sucess = round(df["state"].value_counts() / len(df["state"]) * 100, 2) print("State Percent in %: ") print(percentual_sucess) # In[15]: state = round(df["state"].value_counts() / len(df["state"]) * 100, 2) labels = list(state.index) values = list(state.values) trace1 = go.Pie(labels=labels, values=values, marker=dict(colors=['red'])) layout = go.Layout(title='State Distribution', legend=dict(orientation="h")) fig = go.Figure(data=[trace1], layout=layout) iplot(fig) # In[16]: # Only consider failed or successful projects # Exclude suspended, cancelled, and other misc states df = df[(df['state'] == "failed") | (df['state'] == "successful")] # In[17]: state = round(df["state"].value_counts() / len(df["state"]) * 100, 2)
##auth = dash_auth.BasicAuth(app,USERNAME_PASSWORD_PAIRS) server = app.server colors = { 'chartbackground': '#ffffff', 'background':'#EEF1F6', 'text': '#000000' } piecolours=['#7BA3B7','#6C8FA0','#5C7A89','#4D6672','#3D525B','#2E3D45','1F292E','0F1417'] graph1 = [ dcc.Graph( id='piechart', figure={ 'data': [go.Pie(labels=labels, values=sizes, marker={'colors': ['#C0D2D8','#425772']}, textinfo='label')], 'layout': go.Layout(legend={'x': 1, 'y': 0.7}, plot_bgcolor = colors['background'], paper_bgcolor = colors['chartbackground'], title='<b>Total Messages Per User</b>') } ), ] graph2 = [ dcc.Graph( id='linegraph', figure={ 'data': [ {'x': data0['date'], 'y': data0['jodi_count'], 'type': 'line', 'name': 'Jodi'}, {'x': data0['date'], 'y': data0['richard_count'], 'type': 'line', 'name': 'Richard'}, ],
def update_pie_chart(sentiment_term): # get data from cache c = conn.cursor() import numpy as np '''df = pd.read_sql( "SELECT COUNT(*)(sentiment) FROM sentiment WHERE sentiment BETWEEN 0.000001 and 1 and country LIKE ? ORDER BY unix DESC LIMIT 1000 ;", conn, params=('%' + sentiment_term + '%',))''' # df = pd.read_sql("SELECT *(sentiment) FROM sentiment WHERE sentiment BETWEEN 0.000001 and 1 ;",conn) df = pd.read_sql( "SELECT COUNT(*)FROM sentiment WHERE sentiment BETWEEN 0.000001 and 1 and country LIKE ? ORDER BY unix DESC LIMIT 1000 ;", conn, params=('%' + sentiment_term + '%',)) df2 = pd.read_sql( "SELECT COUNT(sentiment) FROM sentiment WHERE sentiment BETWEEN -1 and -0.0001 and country LIKE ? ORDER BY unix DESC LIMIT 1000 ;", conn, params=('%' + sentiment_term + '%',)) df3 = pd.read_sql( "SELECT COUNT(sentiment) FROM sentiment WHERE sentiment =0 and country LIKE ? ORDER BY unix DESC LIMIT 1000 ;", conn, params=('%' + sentiment_term + '%',)) # print(df2) '''print(df.dtypes) df_value=df.values x = df_value.astype(float) print('df.dtypes') print('x=',x) ''' df_value = df.values x = df_value.astype(float) x = x.astype(int) df_value2 = df2.values y = df_value2.astype(float) y = y.astype(int) df_value3 = df3.values q = df_value3.astype(float) q = q.astype(int) # print(df) '''print(df2.values) x=df.values y=df.values print(x) print(y) ''' import plotly.graph_objects as go labels =['Positive','Negative','natural'] values = [int(x), int(y),int(q)] # fig = go.Figure(data=[go.Pie(labels=labels, values=values)]) colors = ['#007F25', '#800000'] trace = go.Pie(labels=labels, values=values, hoverinfo='label+percent', textinfo='value', textfont=dict(size=20, color=app_colors['text']), marker=dict(colors=colors, line=dict(color=app_colors['background'], width=2))) return {"data": [trace], 'layout': go.Layout( title='Positive vs Negative sentiment for "{}" (longer-term)'.format(sentiment_term), font={'color': app_colors['text']}, plot_bgcolor=app_colors['background'], paper_bgcolor=app_colors['background'], showlegend=True),}
def write_html_tol(fpath, df_sell, max_huice): if len(df_sell) == 0: return m_data = df_sell[len(df_sell) - 1] datetime_x = [d['datetime'] for d in df_sell] datediff = relativedelta(m_data['datetime'], df_sell[0]['datetime']) datediff = "历经{}年{}个月{}天".format(datediff.years, datediff.months, datediff.days) labels = ["盈利", "亏损", "持平"] trade_num = m_data['ex_buy_count'] trade_avg_ex = m_data['ex_zdf_count'] / trade_num trade_days = len(df_sell) trade_avg_day = m_data['day_sj_zdf_count'] / trade_days trade_tol_yl = m_data['zyk'] trade_ex_sz = m_data['ex_sz_count'] trade_ex_xd = m_data['ex_xd_count'] trade_day_sz = m_data['day_sz'] trade_day_xd = m_data['day_xd'] fig = make_subplots( rows=3, cols=2, row_heights=[0.5, 0.3, 0.2], shared_xaxes=True, vertical_spacing=0.1, specs=[ [{ 'type': 'xy', 'colspan': 2 }, None], [{ 'type': 'xy', 'colspan': 2 }, None], [{ 'type': 'domain' }, { 'type': 'domain' }], ], subplot_titles=[ '收益({:.2f}%)'.format(trade_tol_yl), '每日明细({})'.format(datediff), '次数({}) 平均涨幅 {:.2f}%'.format(trade_num, trade_avg_ex), '天数({}) 平均涨幅 {:.2f}%'.format(trade_days, trade_avg_day), ]) fig.add_trace( go.Scatter(x=datetime_x, y=[d['zyk'] for d in df_sell], mode='lines+markers', name="收益"), 1, 1) fig.add_trace( go.Scatter(x=datetime_x, y=[d['day_sj_zdf_count'] for d in df_sell], mode='markers', name="每日明细"), 2, 1) fig.add_trace( go.Pie(labels=labels, values=[ trade_ex_sz, trade_ex_xd, trade_num - (trade_ex_sz + trade_ex_xd) ], hole=.3, textinfo='label+percent+value', name='交易次数'), 3, 1) fig.add_trace( go.Pie(labels=labels, values=[ trade_day_sz, trade_day_xd, trade_days - (trade_day_sz + trade_day_xd) ], hole=.3, textinfo='label+percent+value', name='交易天数'), 3, 2) fig.update_layout(showlegend=False, height=1000, title_text='最大回测:{} 夏普率:{} 年华收益:{} '.format( max_huice, 0, 0)) fig.update_yaxes(zeroline=True, zerolinewidth=2, zerolinecolor='LightPink') fig.write_html(fpath, full_html=False)
def update_heatmap_confidence(n, current_time, footage, threshold): layout = go.Layout( showlegend=False, paper_bgcolor="rgb(249,249,249)", plot_bgcolor="rgb(249,249,249)", autosize=False, margin=dict(l=10, r=10, b=20, t=20, pad=4), ) if current_time is not None: current_frame = round(current_time * FRAMERATE) if n > 0 and current_frame > 0: # Load variables from the data dictionary video_info_df = data_dict[footage]["video_info_df"] classes_padded = data_dict[footage]["classes_padded"] root_round = data_dict[footage]["root_round"] classes_matrix = data_dict[footage]["classes_matrix"] # Select the subset of the dataset that correspond to the current frame frame_df = video_info_df[video_info_df["frame"] == current_frame] # Select only the frames above the threshold threshold_dec = threshold / 100 frame_df = frame_df[frame_df["score"] > threshold_dec] # Remove duplicate, keep the top result frame_no_dup = frame_df[["class_str", "score"]].drop_duplicates("class_str") frame_no_dup.set_index("class_str", inplace=True) # The list of scores score_list = [] for el in classes_padded: if el in frame_no_dup.index.values: score_list.append(frame_no_dup.loc[el][0]) else: score_list.append(0) # Generate the score matrix, and flip it for visual score_matrix = np.reshape(score_list, (-1, int(root_round))) score_matrix = np.flip(score_matrix, axis=0) # We set the color scale to white if there's nothing in the frame_no_dup if frame_no_dup.shape != (0, 1): colorscale = [[0, "#f9f9f9"], [1, "#fa4f56"]] else: colorscale = [[0, "#f9f9f9"], [1, "#f9f9f9"]] hover_text = [f"{score * 100:.2f}% confidence" for score in score_list] hover_text = np.reshape(hover_text, (-1, int(root_round))) hover_text = np.flip(hover_text, axis=0) # Add linebreak for multi-word annotation classes_matrix = classes_matrix.astype(dtype="|U40") for index, row in enumerate(classes_matrix): row = list(map(lambda x: "<br>".join(x.split()), row)) classes_matrix[index] = row # Set up annotation text annotation = [] for y_cord in range(int(root_round)): for x_cord in range(int(root_round)): annotation_dict = dict( showarrow=False, text=classes_matrix[y_cord][x_cord], xref="x", yref="y", x=x_cord, y=y_cord, ) if score_matrix[y_cord][x_cord] > 0: annotation_dict["font"] = {"color": "#F9F9F9", "size": "11"} else: annotation_dict["font"] = {"color": "#606060", "size": "11"} annotation.append(annotation_dict) # Generate heatmap figure figure = { "data": [ { "colorscale": colorscale, "showscale": False, "hoverinfo": "text", "text": hover_text, "type": "heatmap", "zmin": 0, "zmax": 1, "xgap": 1, "ygap": 1, "z": score_matrix, } ], "layout": { "showlegend": False, "autosize": False, "paper_bgcolor": "rgb(249,249,249)", "plot_bgcolor": "rgb(249,249,249)", "margin": {"l": 10, "r": 10, "b": 20, "t": 20, "pad": 2}, "annotations": annotation, "xaxis": { "showticklabels": False, "showgrid": False, "showline": False, "zeroline": False, "side": "top", "ticks": "", }, "yaxis": { "showticklabels": False, "showgrid": False, "showline": False, "zeroline": False, "side": "left", "ticks": "", }, }, } return figure # Returns empty figure return go.Figure(data=[go.Pie()], layout=layout)
pie_data = [{ "category": "housing", "spend_pct": spend_housing }, { "category": "food", "spend_pct": spend_food }, { "category": "personal", "spend_pct": spend_personal }, { "category": "transportation", "spend_pct": spend_transportation }, { "category": "other", "spend_pct": spend_other }] print("----------------") print("GENERATING PIE CHART...") labels = [pie_data["category"] for pie_data in pie_data] values = [pie_data["spend_pct"] for pie_data in pie_data] trace = go.Pie(labels=labels, values=values) #, title="Spending by Category") layout_pie = go.Layout(title="Spending by Category") plotly.offline.plot({ "data": trace, "layout": layout_pie }, filename="spending_by_category.html", auto_open=True)
plt.show() #Method2 import matplotlib.pyplot as plt labels = ['Cookies', 'Jellybean', 'Milkshake', 'Cheesecake'] sizes = [38.4, 40.6, 20.7, 10.3] colors = ['yellowgreen', 'gold', 'lightskyblue', 'lightcoral'] patches, texts = plt.pie(sizes, colors=colors, shadow=True, startangle=90) plt.legend(patches, labels, loc="best") plt.axis('equal') plt.tight_layout() plt.show() #Method2 import plotly plotly.tools.set_credentials_file(username='******', api_key='0zZ5FLEa1sM0EfqsMK9R') import plotly as py1 import plotly.plotly as py import plotly.graph_objs as go labels = ['Oxygen','Hydrogen','Carbon_Dioxide','Nitrogen'] values = [4500,2500,1053,500] trace = go.Pie(labels=labels, values=values) py.iplot([trace], filename='basic_pie_chart')
def update_charts(goodness, skew, threshold): df = generate_roc_curve_df(goodness, skew) hist_kwargs = dict(opacity=0.75, autobinx=False, xbins=dict(start=-10.0, end=10, size=0.5)) return html.Div([ html.Div([ dcc.Graph(id='classes', figure=dict(data=[ go.Histogram(x=df[df.pos == 1].score, **hist_kwargs), go.Histogram(x=df[df.neg == 1].score, **hist_kwargs) ], layout=go.Layout( barmode='overlay', xaxis=dict(range=[-10, 10]), yaxis=dict(range=[0, 200]), width=400, height=400, autosize=False, legend=dict(orientation="h"), margin=go.Margin(l=40, t=40)))), dcc.Graph(id='rates', figure=dict(data=[ go.Scatter(x=df.score, y=df.tpr), go.Scatter(x=df.score, y=df.fpr), ], layout=go.Layout( xaxis=dict(range=[-10, 10], zeroline=False), yaxis=dict(range=[0, 1]), width=400, height=400, autosize=False, legend=dict(orientation="h"), margin=go.Margin(l=40, t=40)))), ], style={'columnCount': 2}), html.Div([ dcc.Graph(id='roc', figure=dict(data=[go.Scatter(x=df.fpr, y=df.tpr)], layout=go.Layout( xaxis=dict(range=[0, 1]), yaxis=dict(range=[0, 1]), width=400, height=400, autosize=False, legend=dict(orientation="h"), margin=go.Margin(l=40, t=40)))), dcc.Graph( id='confusion', figure=dict(data=[ go.Pie(labels=['tp', 'fp', 'tn', 'fn'], values=df.iloc[threshold][['tp', 'fp', 'tn', 'fn']], sort=False) ], layout=go.Layout(width=400, height=400, autosize=False, legend=dict(orientation="h"), margin=go.Margin(l=40, t=40)))), ], style={'columnCount': 2}) ], style={'width': "600px"})
def plots_actualize(df2): fig_map = go.Figure(data=go.Scattermapbox(lat=df2["latitude"], lon=df2["longitude"], mode="markers", marker=dict(color="#5A6FF9")), layout=go.Layout(autosize=True, margin=go.layout.Margin(l=0, r=0, t=0, b=0), showlegend=False, mapbox=dict( accesstoken=mapbox_access_token, style="dark", center={ 'lat': 39, 'lon': -9.2 }, zoom=8.5, ))) pie_colors = ["#636EFA", "#4296f5", "#42ddf5"] unique_rooms = list(df2.room_type.unique()) if len(unique_rooms) == 1: if unique_rooms[0] == 'Private room': pie_colors = ["#4296f5"] elif unique_rooms[0] == 'Shared room': pie_colors = ["#42ddf5"] fig_pie = go.Figure(data=go.Pie( labels=df2['room_type'].value_counts().index, values=df2['room_type'].value_counts().values, textinfo='text+value+percent', text=df2['room_type'].value_counts().index, hoverinfo='label', showlegend=False, textfont=dict(color="white"), marker=(dict(colors=pie_colors, line=dict(color="white", width=0.5)))), layout=go.Layout( paper_bgcolor='rgba(0,0,0,0)', plot_bgcolor='rgba(0,0,0,0)', margin=go.layout.Margin(l=0, r=0, t=0, b=0), )) fig_bar = go.Figure(data=go.Bar( x=df2['ordinal_rating'].value_counts().values, y=df2['ordinal_rating'].value_counts().index, orientation='h', marker=dict(line=dict(color="white"))), layout=go.Layout( paper_bgcolor='rgba(0,0,0,0)', plot_bgcolor='rgba(0,0,0,0)', margin=go.layout.Margin(l=0, r=0, t=0, b=0), clickmode='event+select', font=dict(color="white"), xaxis_title='Number of Listings', )) fig_hist = go.Figure(data=go.Histogram( x=df2['price'], histnorm="", xbins=dict(size=30, end=800), marker=dict(line=dict(color="white", width=0.25))), layout=go.Layout(margin=go.layout.Margin(l=0, r=0, t=0, b=0), clickmode='event+select', paper_bgcolor='rgba(0,0,0,0)', plot_bgcolor='rgba(0,0,0,0)', xaxis_title='Price (€)', yaxis_title='Absolute frequencies', showlegend=False, font=dict(color="white"))) return (fig_map, fig_pie, fig_bar, fig_hist)
def update_graph(hotel_group_id, hotel_id, hotel__city, start_date, end_date, **kwargs): # get metadata for current user current_user = kwargs['user'] user_id = current_user.pk user_metadata = UserMetadata.objects.get(user_id=user_id) hotel_group_filter = {} if hotel_group_id == None else { "hotel_group_id": hotel_group_id } hotel_filter = {} if hotel_id == None else {"hotel_id": hotel_id} hotel__city_filter = {} if hotel__city == None else { "hotel__city": hotel__city } booking_start_date_filter = {} if start_date == None else { "start_date__gte": dt.strptime(start_date.split(' ')[0], '%Y-%m-%d') } booking_end_date_filter = {} if end_date == None else { "end_date__lte": dt.strptime(end_date.split(' ')[0], '%Y-%m-%d') } # if group or hotel then apply filter if current_user.groups.filter(name='Hotel Group Administrators').exists(): hotel_group_id = user_metadata.hotel_group_id # bookings = Booking.objects.filter(hotel_group_id=hotel_group_id) bookings = Booking.objects.filter(hotel_group_id=hotel_group_id).filter(**hotel__city_filter).filter(**hotel_filter).filter(**booking_start_date_filter)\ .filter(**booking_end_date_filter)\ .values('start_date') \ .annotate(total=Count('hotel_id')) elif current_user.groups.filter(name='Hotel Administrators').exists(): hotel_id = user_metadata.hotel_id bookings = Booking.objects.filter(hotel_id=hotel_id).filter(**booking_start_date_filter).filter(**booking_end_date_filter)\ .values('start_date') \ .annotate(total=Count('hotel_id')) else: bookings = Booking.objects.filter(**hotel_group_filter).filter(**hotel__city_filter).filter(**hotel_filter).filter(**booking_start_date_filter)\ .filter(**booking_end_date_filter)\ .values('start_date') \ .annotate(total=Count('hotel_id')) if len(bookings) == 0: return { "data": [go.Pie(labels=[], values=[], textinfo='label')], "layout": go.Layout({ "annotations": [{ "text": "No matching data found", "showarrow": False }] }) } else: #values=[booking['total'] for booking in list(bookings)] df = pd.DataFrame(list(bookings)) #labels=[booking['start_date'] for booking in list(bookings)] return { "data": [go.Scatter(x=df.start_date, y=df['total'])], "layout": go.Layout( margin=dict(t=20, l=50, r=50, pad=0), autosize=True, width=350, ) }
movies.movie_name, COUNT(watched_movies.review_id_fk) FROM watched_movies INNER JOIN movies ON watched_movies.movie_id_fk = movies.movie_id GROUP BY movies.movie_name """) movies = [] movie_reviews_count = [] for row in cursor.fetchall(): movies.append(row[0]) movie_reviews_count.append(row[1]) pie = go.Pie(labels=movies, values=movie_reviews_count) movies_reviews_proportion_url = py.plot([pie], filename='reviews-count') """ create plot 3 """ cursor.execute(""" SELECT reviews.review_date, COUNT(DISTINCT profiles.profile_id) FROM profiles INNER JOIN watched_movies ON profiles.profile_id = watched_movies.profile_id_fk INNER JOIN reviews ON reviews.review_id = watched_movies.review_id_fk GROUP BY reviews.review_date ORDER BY reviews.review_date """)
df_info = pd.concat(_temp,axis=1).T df_info.index.name = '指标' df_info = df_info.round(decimals=3) import plotly.offline as pyof from plotly import figure_factory as ff table = ff.create_table(df_info,index=True, index_title='指标') pyof.plot(table, filename='产品组合信息表.html') '''画饼图''' import plotly.graph_objs as go labels=df_info.columns[:-1] values=w trace=go.Pie(labels=labels,values=values,text='哈哈') layout = dict(title = '产品组合成分图') fig = dict(data=[trace],layout=layout) pyof.plot(fig,filename='组合成分图.html') '''画产品对比图''' import tushare as ts data_hs300 = ts.get_hist_data('hs300') data_hs300 = data_hs300.rename_axis(lambda x:pd.to_datetime(x)) df_contra = pd.concat([data_hs300.close,df['组合']],axis=1,join='inner') df_contra = df_contra / df_contra.iloc[0,:] df_contra.rename(columns={'close':'沪深300'},inplace=True) import plotly.graph_objs as go