def create_radar(): fig01 = px.line_polar(df_SavingsOverview, r='Consumer', theta='Product', line_close=True) fig01.update_traces(fill='toself', line=dict(color='blue'), name='Consumer', showlegend=True) fig02 = px.line_polar(df_SavingsOverview, r='Neighbourhood', theta='Product', line_close=True) fig02.update_traces(fill='toself', line=dict(color='green'), name='Neighbourhood', showlegend=True) fig03 = px.line_polar(df_SavingsOverview, r='City', theta='Product', line_close=True) fig03.update_traces(fill='toself', line=dict(color='#ff8200'), name='City', showlegend=True) fig01.add_trace(fig02.data[0]) fig01.add_trace(fig03.data[0]) graphJSON = json.dumps(fig01, cls=plotly.utils.PlotlyJSONEncoder) return graphJSON
def radar_updater(value_var3): df6 = consultas.df_radar values = df6.loc[value_var3].drop(['cluster']).values.flatten().tolist() df7 = pd.DataFrame(dict(r=values, theta=consultas.categories)) fig_radar = px.line_polar(df7, r='r', theta='theta', line_close=True).update_traces(fill='toself') return fig_radar
def daywise_messages(data): def dayofweek(i): l = [ "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" ] return l[i] day_df = pd.DataFrame(data["Message"]) day_df['day_of_date'] = data['Date'].dt.weekday day_df['day_of_date'] = day_df["day_of_date"].apply(dayofweek) day_df["MessageCount"] = 1 day = day_df.groupby("day_of_date").sum() day.reset_index(inplace=True) fig = px.line_polar(day, r='MessageCount', theta='day_of_date', line_close=True) fig.update_traces(fill='toself') fig.update_layout(polar=dict(radialaxis=dict( visible=True, range=[0, int(math.ceil(day['MessageCount'].max().item()) + 100)])), showlegend=True, margin=dict( l=5, r=5, )) return fig
def day_wise_count(df): """ Parameters ---------- data : Dataframe This function generates a line polar plot of day count. Returns ------- None. """ days = [ "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" ] day_df = pd.DataFrame(df["Message"]) day_df['day_of_date'] = df['Date'].dt.weekday day_df['day_of_date'] = day_df["day_of_date"].apply(lambda d: days[d]) day_df["messagecount"] = 1 day = day_df.groupby("day_of_date").sum() day.reset_index(inplace=True) fig = px.line_polar(day, r='messagecount', theta='day_of_date', line_close=True) fig.update_traces(fill='toself') fig.update_layout(polar=dict(radialaxis=dict(visible=True, )), showlegend=True) return fig
def Measurement_page(): raw_data = np.genfromtxt("dipole_pattern.csv", delimiter=',') theta = np.arange(0, 361, 1) today = datetime.today() fig = px.line_polar(r=raw_data, theta=theta, start_angle=0) graphJSON = json.dumps(fig, cls=plotly.utils.PlotlyJSONEncoder) return render_template("Measurement.html", day=today, graphJSON=graphJSON)
def get_radar_chart_clusters(self): algos = self.core_algo() algos.fit(self.X) clusters = pd.DataFrame(self.X, columns=self.df.columns[1:]) clusters['label'] = algos.labels_ # clusters[self.df.columns[0]] = self.df.iloc[:, 0] polar = clusters.groupby("label").mean().reset_index() polar = pd.melt(polar, id_vars=["label"]) polar.loc[:, :].to_csv('df_polar.txt', sep=';', index=False, header=True) fig = px.line_polar(polar, r="value", theta="variable", color="label", line_close=True, height=700, width=1500) fig.show() self.df['c'] = algos.labels_ self.df.loc[:, :].to_csv('df_oe.txt', sep=';', index=False, header=True)
def display_output(nclicks, input_query): results = sp.search(q=input_query, limit=1) name = results["tracks"]["items"][0]["name"] artists = [t["name"] for t in results["tracks"]["items"][0]["artists"]] tids = results["tracks"]["items"][0]["uri"] features = sp.audio_features(tids)[0] vals = [ results["tracks"]["items"][0]["popularity"], features["danceability"]*100, features["energy"]*100, features["speechiness"]*100, features["acousticness"]*100, features["instrumentalness"]*100, features["liveness"]*100, features["valence"]*100, ] df = pd.DataFrame(dict(r=vals,theta=colnames)) fig = px.line_polar(df, r='r', theta='theta', line_close=True, range_r=[0,100]) fig.update_layout(title=f"{name} ({' & '.join(artists)})", font=dict( family="Courier New, monospace", size=15, color="#7f7f7f" ), ) return fig
def update_figure(dpc_value, a, dpp_value, b): # Hämta listor för (deaths per condition) med intressant data pre_conditions, deaths_per_condition = aggregate_death_per_condition( DPC_FILE, dpc_value) # Konvertera listorna för (deaths per condition) till en dataframe df_dpc = lists_to_dataframe(pre_conditions, deaths_per_condition, "Pre-conditions", "Deaths per condition") # Med den skapade data framen skapa sedan figurerna dpc_bar_figure = px.bar(df_dpc, x="Pre-conditions", y="Deaths per condition") dpc_pie_figure = px.pie(df_dpc, names="Pre-conditions", values="Deaths per condition") # Hämta listor för (deaths per period) med intressant data och skapa en data frame med dem periods, deaths_per_period = aggregate_deaths_per_period( DPP_FILE, dpp_value) # Konvertera listorna för (deaths per period) till en dataframe df_dpp = lists_to_dataframe(periods, deaths_per_period, "Periods", "Deaths per period") # Med den skapade data framen skapas sedan figurerna dpp_bar_figure = px.bar(df_dpp, x="Periods", y="Deaths per period") dpp_radar_figure = px.line_polar(df_dpp, r="Deaths per period", theta="Periods", line_close=True) # Returnera skapade figurerna return dpc_bar_figure, dpc_pie_figure, dpp_bar_figure, dpp_radar_figure
def audio_features_viz(access_token, time_range: RANGE): top_tracks_df = get_top_tracks(access_token=access_token, time_range=time_range.value) feature_cols = ['acousticness', 'danceability', 'energy', 'instrumentalness', 'liveness', 'loudness', 'speechiness', 'tempo', 'valence'] audio_features_df = get_track_audio_features(access_token=access_token, track_df=top_tracks_df)[feature_cols + ['id', 'name']] scaler = StandardScaler() audio_features_df[feature_cols] = scaler.fit_transform(audio_features_df[feature_cols]) audio_features_df_melted = audio_features_df.melt(id_vars=['id', 'name']) figure = px.line_polar(data_frame=audio_features_df_melted, r='value', theta='variable', color='name', line_close=True, template=PLOTLY_TEMPLATE, labels=dict(zip(feature_cols, map(str.title, feature_cols))) ) figure.update_layout(legend=dict( orientation="h", yanchor="bottom", y=1.1, xanchor="right", x=1 )) figure.update_traces(fill='toself') graph = dcc.Graph(id='audio-features-chart', figure=figure) graph_card = dbc.Card( children=[ dbc.CardHeader(children=[html.H4("Top Track Audio Features")]), graph ] ) return graph_card
def dayofweek(messages_df, format): plotly.io.orca.config.executable = 'C:/Users/joaov/anaconda3/orca_app/orca.exe' plotly.io.orca.config.save() day_df = pd.DataFrame(messages_df["Message"]) day_df['day_of_date'] = messages_df['Date'].dt.weekday day_df['day_of_date'] = day_df["day_of_date"].apply(list_of_days) day_df["messagecount"] = 1 day = day_df.groupby("day_of_date").sum() day.reset_index(inplace=True) if (format == 'json'): return day.to_json(orient="records") fig = px.line_polar(day, r='messagecount', theta='day_of_date', line_close=True) fig.update_traces(fill='toself') fig.update_layout( polar=dict(radialaxis=dict(visible=True, range=[0, 8000])), showlegend=True) fig.show() fig.write_image("dayofweek.png") path = './dayofweek.png' return path
def aspects_radar_plot(self, aspects: list, _testing=False): """ plot the sentiment score radar chart for designated aspects :param aspects: a list of aspects :return: """ try: len(self.aspects_opinions_df) except AttributeError: self.aspect_opinon_for_all_comments() sentiment_scores = [self.sentiment_for_one_aspect(i) for i in aspects] aspects_sentiments = pd.DataFrame( dict(r=sentiment_scores, theta=aspects)) fig = px.line_polar( aspects_sentiments, r='r', theta='theta', line_close=True, title='Sentiment scores of the most common aspects') if not _testing: fig.show() else: return 'plot finished'
def model1(): model = pickle.load(open('model.pkl', 'rb')) int_features = [int(x) for x in request.form.values()] final_features = [np.array(int_features)] prediction = model.predict(final_features) output = round(prediction[0], 2) df = pd.DataFrame( dict(r=int_features[1:], theta=[ 'Phong độ', 'Tiềm năng', 'Tốc độ', 'Dứt điểm', 'Tì đè', 'Sút chính xác', 'Đánh đầu', 'Tăng tốc', 'Thăng bằng', 'Lực sút' ])) myplot = plot(px.line_polar(df, r='r', theta='theta', line_close=True), output_type='div') if (output < 0): return render_template( 'predictprice.html', prediction_text='Giá trị cầu thủ quá nhỏ để định giá') else: return render_template( 'predictprice.html', div_placeholder=Markup(myplot), prediction_text='Giá trị của cầu thủ là: {} euro'.format(output))
def get_radar_fig(radar_pd): r""" Get radar figure of linguistic classifications. """ fig = px.line_polar(radar_pd, r='r', theta='theta', line_close=True) fig.update_traces(fill='toself') return fig
def make_figure(Radius): return px.line_polar( nei_stats, r = Radius, theta = 'neighborhood', color = 'room_type', line_close = True, title = 'Price statistics per neighborhood for each room type' )
def calc_avg_texts_per_hour(): f = open(file_name, "r", encoding='utf-8') # create a new dictionary with the format: times = {0:0, 1:0, 2:0, ... } # where the key is the number of hours in 24 hour time and the value is the number of occurences times = {n: 0 for n in range(24)} m_times = {n: 0 for n in range(24)} n_times = {n: 0 for n in range(24)} # for each text in our chat history for text in f: # grab the date-time string dtstr = text[0:text.find("-") - 1] # if it matches the expected format (m/d/y, t:tt AM/PM) if (re.match("\d{1,2}\/\d{1,2}\/\d{2}, \d{1,2}:\d{2} [AP]M", dtstr)): # parse it into a datetime object time = datetime.datetime.strptime(dtstr, "%m/%d/%y, %I:%M %p").time().hour # add to our overall total times[time] += 1 # add to our subtotals for each party text = text[text.find("-") + 2:len(text) - 1] if (len(text) > 0): if (text[0] == "M"): m_times[time] += 1 elif (text[0] == "N"): n_times[time] += 1 # restructure data for the mixed_df (showing both parties on the radar chart) data = {'r': [], 'theta': [], 'person': []} for time in m_times: data['r'].append(m_times[time]) data['theta'].append(str(time) + ":00") data['person'].append("M") for time in n_times: data['r'].append(n_times[time]) data['theta'].append(str(time) + ":00") data['person'].append("N") total_df = pd.DataFrame( dict(r=[times[x] for x in times], theta=[str(x) + ":00" for x in range(24)])) mixed_df = pd.DataFrame.from_dict(data) # swap out mixed_df for total_df to see the combined texts radar chart fig = px.line_polar(mixed_df, r='r', theta='theta', color='person', line_close=True) fig.write_image("whatsappimages/hourlytextsboth.svg") f.close()
def update_figure(selected_test, selected_dpto, selected_gender, selected_stratum, selected_inst_type, selected_area, selected_tuition, selected_method, selected_level): # Select models comuni_punt_model = pro_comuni_punt_model if selected_test == "SaberPro" else tyt_comuni_punt_model compet_punt_model = pro_compet_punt_model if selected_test == "SaberPro" else tyt_compet_punt_model lectur_punt_model = pro_lectur_punt_model if selected_test == "SaberPro" else tyt_lectur_punt_model razona_punt_model = pro_razona_punt_model if selected_test == "SaberPro" else tyt_razona_punt_model ingles_punt_model = pro_ingles_punt_model if selected_test == "SaberPro" else tyt_ingles_punt_model # Scale difference scale = 1 if selected_test == "SaberPro" else (2 / 3) scale_limit = [0, 300] if selected_test == "SaberPro" else [0, 200] # Get feature cat coded vector feature_vector = get_feature_vector(selected_dpto, selected_gender, selected_stratum, selected_inst_type, selected_area, selected_tuition, selected_method, selected_level) comuni_punt = round( comuni_punt_model.predict([feature_vector])[0] * scale, 0) compet_punt = round( compet_punt_model.predict([feature_vector])[0] * scale, 0) lectur_punt = round( lectur_punt_model.predict([feature_vector])[0] * scale, 0) razona_punt = round( razona_punt_model.predict([feature_vector])[0] * scale, 0) ingles_punt = round( ingles_punt_model.predict([feature_vector])[0] * scale, 0) polar_df = pd.DataFrame( dict(punt=[ comuni_punt, compet_punt, lectur_punt, razona_punt, ingles_punt ], module=available_module)) polar_df['module_name'] = polar_df['module'].map(presentation_module) fig = px.line_polar(polar_df, r='punt', theta='module_name', line_close=True, labels={ 'punt': 'Score', 'module_name': 'Module' }, text='punt') fig.update_traces(textposition='top right') fig.update_layout(polar=dict( radialaxis=dict(range=scale_limit, showticklabels=True, dtick=100))) return fig
def update_spider_graph(champ_name, n_clicks): df_total_per_champ_1 = df_total_per_champ.copy() df_per_champ_1 = df_per_champ.copy() if champ_name in lst_champ_names: df_total_per_champ_1 = df_total_per_champ_1.loc[ df_total_per_champ_1['Champion'] == champ_name] df_per_champ_1 = df_per_champ_1.loc[df_per_champ_1['Champion'] == champ_name] else: df_total_per_champ_1 = df_total_per_champ_1.loc[ df_total_per_champ_1['Champion'] == 'all'] df_per_champ_1 = df_per_champ_1.loc[df_per_champ_1['Champion'] == 'all'] if df_per_champ_1.empty: fig = px.line_polar() else: df_total_per_champ_1 = df_total_per_champ_1.drop( columns=['Champion', 'Number of Games']) df_per_champ_1 = df_per_champ_1.drop( columns=['Champion', 'Number of Games']) lst_div = [ a / b for ( a, b) in zip(df_per_champ_1.iloc[0], df_total_per_champ_1.iloc[0]) ] lst_final = [{ 'r': value1, 'theta': value2 } for (value1, value2) in zip(lst_div, df_per_champ_1.columns)] df_final = pd.DataFrame.from_dict(lst_final) axis_min = np.min(np.array((0.5, np.min(lst_div)))) axis_max = np.max(np.array((1.3, np.max(lst_div)))) fig = px.line_polar(df_final, r='r', theta='theta', line_close=True) fig.update_layout(polar=dict(radialaxis_range=[axis_min, axis_max])) # fig.update_traces(fill='toself') return fig
def Radar(): print("A variacao de potencia e de", var_potencia, "%") df = pd.DataFrame( dict(r=[var_potencia, var_graus, 1], theta=[ 'Varição de Potencia (%)', 'Variação dos Graus (g)', 'Balanceameto' ])) fig = px.line_polar(df, r='r', theta='theta', line_close=True) fig.show()
def plot_cluster_polar_figure(df: pd.DataFrame, plot_type: str, n_cols: int = 3) -> go.Figure: """ Plot polar graph for cluster description :param df: original features with a cluster label named cluster :param plot_type: single or join graph :param n_cols: number of subplots per row used only in single plot type :return: figure object """ # Separate cluster label from train data to normalize features # MinMax scaler transform features to a scale from 0 to 1 train_features = df.drop(['cluster'], axis=1) normalized_features = MinMaxScaler().fit_transform(train_features) normalized_df = pd.DataFrame(normalized_features, columns=train_features.columns) normalized_df['cluster'] = df['cluster'] # Get mean of each normalized feature grouped_df = normalized_df.groupby(['cluster']).mean().reset_index() # Create diferent graphs depending on type plot if plot_type == 'join': # Create melt dataframe mean_df = grouped_df.melt(id_vars='cluster', var_name='audio_feature', value_name='mean') fig = px.line_polar(mean_df, r="mean", theta="audio_feature", color="cluster", line_close=True, title='Cluster Composition') fig.update_traces(fill='toself') elif plot_type == 'single': # Define number of columns and rows clusters = list(df['cluster'].unique()) clusters.sort() rows = math.ceil(len(clusters) / n_cols) # Define figure fig = make_subplots(rows=rows, cols=n_cols, specs=[[{'type': 'polar'}] * n_cols] * rows) for i, cluster_name in enumerate(clusters): fig.add_trace( go.Scatterpolar( name=cluster_name, r=grouped_df[grouped_df['cluster'] == cluster_name].drop('cluster', axis=1).values[0], theta=list(train_features.columns), ), i // n_cols + 1, i % n_cols + 1) fig.update_traces(fill='toself') fig.update_layout(showlegend=True) else: raise Exception('Plot type supporting by now : single and join') return fig
def radar_chart(): df = pd.DataFrame(dict( r=[random.randint(0,22), random.randint(0,22), random.randint(0,22), random.randint(0,22), random.randint(0,22)], theta=['processing cost','mechanical properties','chemical stability', 'thermal stability', 'device integration'])) fig = px.line_polar(df, r='r', theta='theta', line_close=True) placeholder.write(fig)
def update_radar(metropolitan, district): candidates = df_votes_cand_dist[(df_votes_cand_dist['sum'] > 0.1) & (df_votes_cand_dist.province==metropolitan) & (df_votes_cand_dist.district==district)].candidate dff = df_votes_cand_town[(df_votes_cand_town.province==metropolitan) & (df_votes_cand_town.district==district)] dff = dff[dff.party.isin(['더불어민주당', '미래통합당', '무소속', '정의당']) & dff.candidate.isin(candidates)] fig = px.line_polar(dff, r='sum', range_r=(0,1), theta='town', color='party', color_discrete_map=color_map, template='plotly_white', line_close=True) fig.update_layout(legend=dict(xanchor='left', yanchor='top', x=0.97, y=0.03)) fig.update_layout(title=dict(text='Vote rate in {} by town'.format(district.capitalize()), x=0.47, y=0.97)) fig.update_layout(paper_bgcolor='rgba(0,0,0,0)', plot_bgcolor='rgba(0,0,0,0)') return fig
def radar_plot(selected_value): dff = df_tracks[df_tracks["category"] == selected_value] dff = dff.loc[:, [ 'danceability', 'energy', 'speechiness', 'acousticness', 'instrumentalness', 'liveness' ]] dff = dff.describe().loc['mean'].reset_index() dff["mean"] = dff["mean"].apply(lambda x: round(x, 3)) fig = px.line_polar(dff, r='mean', theta='index', line_close=True, template="plotly_dark") fig.update_traces(fill='toself') fig.update_layout(paper_bgcolor='rgba(0, 0, 0, 0)') return dbc.Row([ dbc.Col( dcc.Loading(id="loading_icon", children=[html.Div([dcc.Graph(figure=fig)])])), # dbc.Col(html.Div([ # dt.DataTable(id='table-container-4', # columns=[{"name": i, "id": i} for i in dff], # data=list(dff.to_dict("index").values()), # style_as_list_view=True, # style_data_conditional=[ # { # 'if': {'row_index': 'odd'}, # 'backgroundColor': 'rgb(248, 248, 248)' # } # ], # style_cell={ # 'textAlign': 'left', # 'padding': '5px', # 'color': "#303030"}, # style_header={ # 'backgroundColor': 'rgb(230, 230, 230)', # 'fontWeight': 'bold' # } # ) # ]) # ) dbc.Col( html.Div([ dbc.Table.from_dataframe(dff, striped=True, bordered=True, hover=True) ])) ])
def RadarPlot_PlotLY(statsList, labels): #DS # Generate Radar plot for data using PlotLY module #DE #IS import pandas as pd import plotly.express as px #IE for stats in statsList: df = pd.DataFrame(dict(r=stats, theta=labels)) fig = px.line_polar(df, r='r', theta='theta', line_close=True) fig.show()
def plot_features(): df, name, artists = get_features() fig = px.line_polar(df, r='r', theta='theta', line_close=True) fig.update_layout(title=f"{name} ({' & '.join(artists)})", font=dict( family="Courier New, monospace", size=15, color="#7f7f7f" ), ) return fig
def sp500_plot(): df = pd.DataFrame( dict(r=[1, 5, 2, 2, 3], theta=[ 'processing cost', 'mechanical properties', 'chemical stability', 'thermal stability', 'device integration' ])) fig = pe.line_polar(df, r='r', theta='theta', line_close=True) fig.show() print('hi')
def make_graph(self): df = pd.DataFrame( dict(r=list(self.scores.values()), theta=list(self.scores.keys()))) fig = px.line_polar(df, r='r', theta='theta', line_close=True) fig.update_traces(fill='toself') figfile = io.BytesIO() fig.write_image(figfile, format='png') figfile.seek(0) # rewind to beginning of file figbuffer = b''.join(figfile) figdata_png = base64.b64encode(figbuffer) print("im in the graph_maker") return figdata_png.decode('utf8')
def activity(self, custom=False, start='', end=''): # Heatmap plot if custom == True: # filter_df = self.df[(self.df.month == month) & (self.df.year == year)] filter_df = self.df[ (self.df.datetime >= datetime.strptime(start, '%d-%m-%Y')) & (self.df.datetime <= datetime.strptime(end, '%d-%m-%Y') )].reset_index(drop=True) time_df = filter_df.groupby(['bin' ])['message'].count().reset_index() group = filter_df.groupby(['day', 'bin']) # total = filter_df.groupby(['date', 'user'])['message'].count().reset_index() else: group = self.df.groupby(['day', 'bin']) time_df = self.df.groupby(['bin'])['message'].count().reset_index() # total = self.df.groupby(['date', 'user'])['message'].count().reset_index() group = group.size().unstack() group = group.reindex( ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']) group = group.fillna(0) group.columns.name = 'Time' fig = px.imshow( group.to_numpy(), labels=dict(x="Time of day", y="Day of week", color="Number of message"), x=[f'{i} h' for i in range(0, 24)], y=['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'], color_continuous_scale='Bluyl', title='ACTIVITY BY TIME OF THE DAY') # width=1200, height=500 fig.update_xaxes(side="top") fig.update_layout(hovermode="x") fig.show() # Polar plor time_df['bin'] = [str(i) + ' h' for i in range(24)] fig2 = px.line_polar(time_df, r='message', theta='bin', line_close=True, title='ACTIVITY BY TIME') # width=500, height=500 fig2.update_traces(fill='toself') fig2.update_layout(polar=dict(radialaxis=dict(visible=True), ), showlegend=False) fig2.show()
def grafico_aranha(cluster,cor): valores = np.array(df4.iloc[cluster,:]) nomes = np.array(df4.columns) st.header('Cluster {}'.format(cluster)) fig = px.line_polar(df4, r = valores, theta = nomes, line_close = True, range_r = (0,10), color_discrete_sequence = cor ) fig.update_traces(fill='toself') st.plotly_chart(fig, use_container_width=True)
def grafico_radar(menciones): """Método para graficar el promedio de mensiones de un usuario.""" categorias = list(menciones.keys()) promedios = list(menciones.values()) df = pd.DataFrame(dict(r=promedios, theta=categorias)) fig = px.line_polar(df, r='r', theta='theta', line_close=True, range_r=[0, 100]) plot_div = plot(fig, output_type='div', config={'displayModeBar': False}) return plot_div
def update_graph(_country): count = df.index.size i = 0 countryIndex = 0 while (i < count): if(df.iloc[i][0] == _country): countryIndex = i i = i + 1 data = pd.DataFrame(dict( r = [df.iloc[countryIndex][2],df.iloc[countryIndex][3],df.iloc[countryIndex][4], df.iloc[countryIndex][5],df.iloc[countryIndex][6],df.iloc[countryIndex][7] ,df.iloc[countryIndex][8], df.iloc[countryIndex][9]], theta = ['Aroma','Flavor','Aftertaste','Acidity', 'Body','Balance','Uniformity','Sweetness'])) fig2 = px.line_polar(data ,r = 'r', theta = 'theta', range_r = [0,10], line_close = True, color_discrete_sequence = px.colors.sequential.solar) return fig2