Esempio n. 1
0
    def radarplots(self):
      fig1 = go.Figure()
      
      features = self.data.columns[:3]
      groupings = self.data.groupby('label').mean()
      names = ['group{}'.format(i+1) for i in range(self.num_clusters)]
      
      for f in features: 
        fig1.add_trace(go.Scatterpolar(
        r=groupings[f],
        theta=names,
        fill='toself', 
        name=f
        ))
        
      fig1.show()

      fig2 = go.Figure()
      
      groupings_t = groupings.T
      
      for g in range(self.num_clusters): 
        fig2.add_trace(go.Scatterpolar(
          r=groupings_t.iloc[:, g], 
          theta=features, 
          fill='toself', 
          name='group{}'.format(g)
        ))
        
      fig2.show()
Esempio n. 2
0
def update_output(club1, club2):
    skills = [
        'General', 'Mental', 'Mobility', 'Power', 'Shooting', 'Passing',
        'Defending', 'Goalkeeping', 'Rating'
    ]
    return go.Figure(
        data=[
            go.Scatterpolar(r=df[(df["Club"] == club1)].loc[:, [
                'General', 'Mental', 'Mobility', 'Power', 'Shooting',
                'Passing', 'Defending', 'Goalkeeping', 'Rating'
            ]].median(),
                            theta=skills,
                            fill='toself',
                            name=club1),
            go.Scatterpolar(r=df[(df["Club"] == club2)].loc[:, [
                'General', 'Mental', 'Mobility', 'Power', 'Shooting',
                'Passing', 'Defending', 'Goalkeeping', 'Rating'
            ]].median(),
                            theta=skills,
                            fill='toself',
                            name=club2)
        ],
        layout=go.Layout(
            polar=dict(radialaxis=dict(visible=True, range=[0, 100])),
            showlegend=True,
            title={
                'text': 'Skills Radar',
                'y': 0.95,
                'x': 0.5,
                'xanchor': 'center',
                'yanchor': 'top'
            },
            height=550,
            colorway=['#2BB3B0', '#B277A7']),
    )
Esempio n. 3
0
    def chart_radar(app, status_update):
        MA_status_5, Earth3Dailystatus_2, Earth3Weeklystatus_2, Pice_MA20_above, Pice_MA200_above, MA_status_0, Earth3Dailystatus_0, Earth3Weeklystatus_0, Pice_MA20_below, Pice_MA200_below = get_data.radar_data(
            status_update)
        categories = [
            'MA Status', 'Earth 3 daily', 'Earth3 Weekly', 'MA 20', 'MA 200'
        ]

        fig = go.Figure(data=[
            go.Scatterpolar(r=[
                MA_status_5, Earth3Dailystatus_2, Earth3Weeklystatus_2,
                Pice_MA20_above, Pice_MA200_above
            ],
                            theta=categories,
                            fill='toself',
                            name='Strong stock'),
            go.Scatterpolar(r=[
                MA_status_0, Earth3Dailystatus_0, Earth3Weeklystatus_0,
                Pice_MA20_below, Pice_MA200_below
            ],
                            theta=categories,
                            fill='toself',
                            name='Weak stock')
        ],
                        layout=go.Layout(margin=dict(l=10, r=10, t=30, b=20),
                                         height=180,
                                         autosize=True))
        #fig.update_layout(style{'height':'200px'})
        fig.update_layout(title_text='Radar overview')
        fig.update_layout(showlegend=False)

        return fig
Esempio n. 4
0
def radar_capability_comparison(feature_list, player1_value, player2_value,
                                playername_list):
    player1_value = list(player1_value)
    player1_value.append(player1_value[0])
    player2_value = list(player2_value)
    player2_value.append(player2_value[0])
    feature_list.append(feature_list[0])
    fig = go.Figure()
    fig.add_trace(
        go.Scatterpolar(r=player1_value,
                        theta=feature_list,
                        fill='toself',
                        name=playername_list[0]))
    fig.add_trace(
        go.Scatterpolar(r=player2_value,
                        theta=feature_list,
                        fill='toself',
                        name=playername_list[1]))

    fig.update_layout(template="plotly_dark",
                      polar=dict(radialaxis=dict(
                          range=[-0.1, 1.1], showticklabels=False, ticks='')),
                      font_size=20)

    return fig
def radar_gauge(val,pos,placeholder):
    fig = go.Figure()
    pos = int(int(pos)/2)
    r[pos] = val

    fig.add_trace(go.Scatterpolar(
          r=r,
          theta=theta
    ))

    r2 = [0]*180
    r2[pos] = 1500
    fig.add_trace(go.Scatterpolar(
          r=r2,
          theta=theta
    ))

    fig.update_layout(
      polar=dict(
        radialaxis=dict(
          visible=True,
          range=[0, 1500]
        ),
      ),
      showlegend=False
    )
    placeholder.write(fig)
Esempio n. 6
0
def show_results(scores, estimators_names, metric_names):
    mean_accuracy = scores[0].mean(1)
    mean_precision = scores[1].mean(1)
    mean_recall = scores[2].mean(1)
    mean_f1 = scores[3].mean(1)
    mean_roc = scores[4].mean(1)

    plot_tree_results = [estimators_names[0], mean_accuracy[0], mean_precision[0], mean_recall[0], mean_f1[0],
                         mean_roc[0]]
    plot_svm = [estimators_names[1], mean_accuracy[1], mean_precision[1], mean_recall[1], mean_f1[1], mean_roc[1]]
    plot_knn = [estimators_names[2], mean_accuracy[2], mean_precision[2], mean_recall[2], mean_f1[2], mean_roc[2]]
    plot_nb = [estimators_names[3], mean_accuracy[3], mean_precision[3], mean_recall[3], mean_f1[3], mean_roc[3]]
    plot_lr = [estimators_names[4], mean_accuracy[4], mean_precision[4], mean_recall[4], mean_f1[4], mean_roc[4]]
    plots = [plot_tree_results, plot_svm, plot_knn, plot_nb, plot_lr]
    print(tabulate(plots, metric_names))

    # -----------------------------------------------------------------------------------------------------------------
    # Wyświetlanie wykresu
    plot_names = [*metric_names, metric_names[0]]
    fig = go.Figure(data=[go.Scatterpolar(r=plot_tree_results, theta=plot_names, name='Drzewo decyzyjne'),
                          go.Scatterpolar(r=plot_svm, theta=plot_names, name='SVM'),
                          go.Scatterpolar(r=plot_knn, theta=plot_names, name='kNN'),
                          go.Scatterpolar(r=plot_nb, theta=plot_names, name='Naiwny Bayes'),
                          go.Scatterpolar(r=plot_lr, theta=plot_names, name='Regresja Logistyczna')],
                    layout=go.Layout(title=go.layout.Title(text='Wyniki'),
                                     polar={'radialaxis': {'visible': True}},
                                     showlegend=True))
    pyo.plot(fig)
Esempio n. 7
0
def plot_radar(champ_list, result_1, result_2):
    # plot the radar plot for the given data
    categories = [
        'Hp', 'Mp', 'Move Speed', 'Armor', 'Attack Range', 'Attack Damage',
        'Attack Speed'
    ]

    fig = go.Figure()

    fig.add_trace(
        go.Scatterpolar(r=[
            result_1[4], result_1[5], result_1[6], result_1[7], result_1[8],
            result_1[9], result_1[10]
        ],
                        theta=categories,
                        fill='toself',
                        name=champ_list[0]))
    fig.add_trace(
        go.Scatterpolar(r=[
            result_2[4], result_2[5], result_2[6], result_2[7], result_2[8],
            result_2[9], result_2[10]
        ],
                        theta=categories,
                        fill='toself',
                        name=champ_list[1]))

    fig.update_layout(
        polar=dict(radialaxis=dict(visible=True, range=[0, 700])),
        showlegend=False)

    fig.show()
Esempio n. 8
0
    def _add_trace(self, fig, mode, group, color, imag=False):
        """
        Adds adequate trace to figure

        :param fig: [go.Figure]
        :param mode: [int] mode (1, 2, ...)
        :param comp: [str] 'real' or 'imag'
        :param group: [int] group (1, 2, )
        :param color: [str] line color in css standards
        """

        r_r = self.df.loc[(self.df['mode'] == mode) & (self.df['group'] == group)].strength_real.to_list()[0]
        r_i = self.df.loc[(self.df['mode'] == mode) & (self.df['group'] == group)].strength_imag.to_list()[0]

        verbalise = 'Mode {}'.format(mode) + ' Group {}'.format(group) if not self.analysis else ''

        fig.add_trace(go.Scatterpolar(
            r=self._close(r_r), theta=self._close(self.networks), mode="lines",
            legendgroup=verbalise, showlegend=True, name=verbalise, subplot="polar1",
            line=dict(color=color, dash='dash' if group != 1 else None)
        ), row=1, col=1)

        if imag:
            fig.add_trace(go.Scatterpolar(
                r=self._close(r_i), theta=self._close(self.networks), mode="lines",
                legendgroup=verbalise, showlegend=False, name=verbalise, subplot="polar2",
                line=dict(color=color, dash='dash' if group != 1 else None),
            ), row=1, col=2)
Esempio n. 9
0
def exibirGraficoCopiado():
    categories = [
        'processing cost', 'mechanical properties', 'chemical stability',
        'thermal stability', 'device integration'
    ]
    fig = go.Figure()

    fig.add_trace(
        go.Scatterpolar(
            r=[8, 6, 5, 3, 4],
            theta=categories,
            fill='toself',  # tonext
            name='Atividades 2017'))

    fig.add_trace(
        go.Scatterpolar(r=[1, 5, 2, 2, 3],
                        theta=categories,
                        fill='toself',
                        name='Atividades 2018'))
    fig.add_trace(
        go.Scatterpolar(
            r=[4, 3, 2.5, 1, 2],
            theta=categories,
            fill='toself',  #tonext
            name='Atividades 2019'))

    fig.update_layout(polar=dict(radialaxis=dict(visible=True, range=[0, 5])),
                      showlegend=True)
    fig.show()
Esempio n. 10
0
def get_radar(playername):
    x = df[(df['PLAYER NAME'] == playername) & (df['SEASON'] == 2019)]
    y = df[(df['PLAYER NAME'] == playername) & (df['SEASON'] == 2018)]
    cy = x[['sg_ott_pctle', 'sg_app_pctle', 'sg_atg_pctle',
            'sg_putt_pctle']].values.tolist()[0]
    py = y[['sg_ott_pctle', 'sg_app_pctle', 'sg_atg_pctle',
            'sg_putt_pctle']].values.tolist()[0]
    categories = ['Off The Tee', 'Approach', 'ATG', 'Putting']

    fig = go.Figure()

    fig.add_trace(
        go.Scatterpolar(r=cy, theta=categories, fill='toself', name='2019'))
    fig.add_trace(
        go.Scatterpolar(r=py, theta=categories, fill='toself', name='2018'))

    fig.update_layout(polar=dict(radialaxis=dict(visible=True, range=[0,
                                                                      100]), ),
                      showlegend=True)
    fig.update_layout(
        title='<b>2019 Strokes Gained Data</b><br> Percentile Rank </br>',
        title_x=0.5,
        width=500,
        margin={
            "t": 30,
            "b": 0,
            "l": 30,
            "r": 0
        })
    return dcc.Graph(figure=fig, style={"height": "100%", "width": "100%"})
Esempio n. 11
0
def plot_combine():
    goodput_harm_by_localVideo = pd.read_csv('/Users/rukshani/Documents/DATASET/draft/data-processed/harm/goodput-harm-iperf-localVideo.csv',sep=',', 
                    names=["cca_combo", "harm", "percent", "cca_1", "cca_2", "network"])

    goodput_harm_by_youtube = pd.read_csv('/Users/rukshani/Documents/DATASET/draft/data-processed/harm/goodput-harm-iperf-webVideo.csv',sep=',', 
                    names=["cca_combo", "harm", "percent", "cca_1", "cca_2", "network"])

    iperf_local_youtube_combi = [goodput_harm_by_localVideo, goodput_harm_by_youtube]
    new_df = pd.concat(iperf_local_youtube_combi)
    new_df = new_df.reset_index()

    three_g = new_df.query("network == '3G'")
    homelink = new_df.query("network == 'Homelink'")


    fig = go.Figure()
    fig.add_trace(go.Scatterpolar(
        r = three_g['harm'],
        theta = three_g['cca_combo'],
        mode = 'lines',
        connectgaps=True,
        name = '3G',
        fill='toself'
    ))

    fig.add_trace(go.Scatterpolar(
        r = homelink['harm'],
        theta = homelink['cca_combo'],
        mode = 'lines',
        connectgaps=True,
        name = 'Homelink',
        fill='toself'
    ))

    fig.update_layout(
    polar=dict(
        radialaxis=dict(
        visible=True
        ),
    ),
    showlegend=True,
    font=dict(
        # family="Courier New, monospace",
        # size=11,
        color="black"
    )
    )

    

    fig.update_layout(legend=dict(
    orientation="h",
    yanchor="bottom",
    # y=1.07,
    xanchor="right",
    x=0.1,
    font_color="black"
))
    fig.show()
Esempio n. 12
0
def features_radarchart(features, clusters=None, htmlfile=None):
    """Show radar chart for the provided features.

    Arg:
        features (dframe): neuron features
        clusterinfo (dframe): 
    Returns:
        heatmap showing the features

    Note: should call on non-pca features but should restrict to most important features.
    """
    fig = go.Figure()
    
    if clusters is None:
        categories = list(features.columns)
        
        for index, row in features.iterrows():
            fig.add_trace(go.Scatterpolar(
                r=row.values,
                theta=categories,
                fill='toself',
                text=index,
                name=index
            ))
    else:
        clusters = clusters.set_index('bodyid')

        featuresx = pd.concat([features, clusters], axis=1)
        featuresx = featuresx.sort_values(by=['type'])
        
        categories = list(featuresx.columns)
        categories.remove('type')
        
        for index, row in featuresx.iterrows():
            fig.add_trace(go.Scatterpolar(
                r=row.values,
                theta=categories,
                fill='toself',
                text=index,
                name=row['type']
            ))
    
    fig.update_traces(
        hoverinfo='text')
    fig.update_layout(
        width = 900, 
        height = 800,
    polar=dict(
        radialaxis=dict(visible=True)
        ),
    showlegend=True
    )
    
    if htmlfile is not None:
        plotly.offline.plot(fig, filename=htmlfile)
    fig.show()
Esempio n. 13
0
def execute_player_comparison(player_a, player_b, gw_id):
    if not player_a:
        msg = html.P("Please select first player")
        return msg
    if not player_b:
        msg = html.P("Please select second player")
        return msg
    if not gw_id:
        msg = html.P("Please select gameweek in left layout")
        return msg
    #
    df_leads = load_leads(gw_id)

    # normalization
    pot_div = 12
    point_div = 6
    retrun_div = 0.8

    df_leads["LGBM Potential"] = df_leads["LGBM Potential"] / pot_div
    df_leads["Fast Potential"] = df_leads["Fast Potential"] / pot_div
    df_leads["LGBM Point"] = df_leads["LGBM Point"] / point_div
    df_leads["Fast Point"] = df_leads["Fast Point"] / point_div
    df_leads["LGBM Return"] = df_leads["LGBM Return"] / 0.8
    df_leads["Fast Return"] = df_leads["Fast Return"] / 0.4
    df_leads["Net"] = df_leads["Net"] / 0.4
    df_leads["Cost"] = df_leads["cost"] / 10.0

    df_a = df_leads[df_leads["name"] == player_a].copy()
    df_b = df_leads[df_leads["name"] == player_b].copy()
    keep_cols = [
        "LGBM Point", "LGBM Potential", "LGBM Return", "Fast Point",
        "Fast Potential", "Fast Return", "Cost"
    ]
    df_a = df_a[keep_cols].copy().T.reset_index()
    df_a.columns = ["theta", "r"]

    df_b = df_b[keep_cols].copy().T.reset_index()
    df_b.columns = ["theta", "r"]

    # pdb.set_trace()
    fig = go.Figure()
    fig.add_trace(
        go.Scatterpolar(r=df_a['r'].values,
                        theta=df_a["theta"].values,
                        fill='toself',
                        name=player_a))
    fig.add_trace(
        go.Scatterpolar(r=df_b['r'].values,
                        theta=df_b["theta"].values,
                        fill='toself',
                        name=player_b))
    fig.update_layout(polar=dict(radialaxis=dict(visible=False)),
                      showlegend=True)
    # fig = px.line_polar(df_a, r='r', theta='theta', line_close=True)
    graph = dcc.Graph(figure=fig)
    return graph
Esempio n. 14
0
def rader_fig(company_type_name_m , company_type_name_f):
    
    if company_type_name_m == "Pvt Ltd":
        the_range = [0,2500]
    else:
        the_range = [0,250]
    
        
    # education names
    rader_measure = df_copy["education_level"].value_counts().index.tolist()
    rader_measure.append(rader_measure[0])
    
    #male
    rader_values_m = df_copy[(df_copy["target"] == 1.0)&(df_copy["gender"] == "Male")&(df_copy["company_type"] == company_type_name_m)]\
    ["education_level"].value_counts().values.tolist()
    rader_values_m.append(rader_values_m[0])
    
    #female
    rader_values_f = df_copy[(df_copy["target"] == 1.0)&(df_copy["gender"] == "Female")&(df_copy["company_type"] == company_type_name_f)]\
    ["education_level"].value_counts().values.tolist()
    rader_values_f.append(rader_values_f[0])
    
    fig = go.Figure()
    fig.add_trace(go.Scatterpolar(
        r=rader_values_m,
        theta=rader_measure,
        fill='toself',
        name= f"Male "+company_type_name_m,
        marker_color=["#125d98"],
        
        ))
    

    fig.add_trace(go.Scatterpolar(
        r=rader_values_f,
        theta=rader_measure,
        fill='toself',
        name= f"Female "+company_type_name_f,
        marker_color=["#f5a962"]
        
        ))
    
    return fig.update_layout(
        polar=dict(
        radialaxis=dict(
        visible=True,
        range= the_range,
        color=colors['text'],
        )),
        showlegend= True,
        plot_bgcolor=colors['background'],
        paper_bgcolor=colors['background'],
        font_color=colors['text']
    )
Esempio n. 15
0
def visualize_as_radar():
    data_org=explore.dice_exp.org_instance
    data_cf=explore.dice_exp.final_cfs_df_sparse
    outcome_name=explore.outcome_name
    vertical_stack = pd.concat([data_org, data_cf], axis=0)

    #have output be 0/1
    new_output=[]
    for i in vertical_stack[outcome_name].values:
        new_output.append(round(i))
    vertical_stack[outcome_name]=new_output


    labelencoder = LabelEncoder()

    vertical_stack1 = vertical_stack.copy()
    columns=list(vertical_stack1.columns)

    for i in columns:
        if i not in explore.cont_feat:
            vertical_stack1[i]=labelencoder.fit_transform(vertical_stack1[i])

    normalized_vertical_stack1=(vertical_stack1-vertical_stack1.min())/(vertical_stack1.max()-vertical_stack1.min())

    visualize_as_radar.normalized_data=normalized_vertical_stack1
    columns_touse=[]
    for i in columns:
        columns_touse.append(i)
    columns_touse.append(columns[0])
    #print(columns_touse)


    fig = make_subplots(rows=2, cols=3, specs=[[{'type': 'polar'}]*3]*2)
    col=[2,3,1,2,3]
    row=[1,1,2,2,2]

    fig.add_trace(go.Scatterpolar(
          name = "original instance",
          r = list(normalized_vertical_stack1.iloc[0]),
          theta = columns_touse,
        ), 1, 1)

    for i in range(normalized_vertical_stack1.shape[0]-1):
        fig.add_trace(go.Scatterpolar(
          name = "counterfactual",
          r = list(normalized_vertical_stack1.iloc[i+1]),
          theta = columns_touse,
        ), row[i], col[i])

    fig.update_traces(fill='toself')


    fig.show()
Esempio n. 16
0
def properties_radar():
	source_subreddit = request.args.get('source-subreddit')
	target_subreddit = request.args.get('target-subreddit')
	data = BodyModel.get_instance().get_properties_radar(source_subreddit, target_subreddit)
	data_avg = BodyModel.get_instance().get_properties_radar_average()

	data_close_line = data.append(data.head(1))
	data_avg_close_line = data_avg.append(data_avg.head(1))

	fig = go.Figure(layout=go.Layout(height=PLOT_HEIGHT, width=PLOT_WIDTH))

	fig.add_trace(go.Scatterpolar(
		r=data_close_line.values,
		theta=data_close_line.index,
		line_color=PRIMARY_COLOR,
		showlegend=False, 
		name="Selection"
	))

	fig.add_trace(go.Scatterpolar(
		r=data_avg_close_line.values,
		theta=data_avg_close_line.index,
		line_color=SECONDARY_COLOR,
		name='Avg. of all subreddits'
	))

	fig.update_layout(
		polar =
			{"radialaxis": {
				"visible":True,
				"range":[0, 0.25]
				}
		},
		dragmode=False,
		showlegend=True,
		legend={
			"orientation":"h",
			"yanchor":"bottom",
			"y":-0.2,
			"xanchor":"right",
			"x":1.2
		},
		font={"size": 8},
		margin={"b": 0, "l": 20, "r": 0, "t": 0},
		paper_bgcolor=PLOT_BACKGROUND_COLOR,
		template=TEMPLATE
	)

	fig.update_polars(radialaxis_tickformat="0.1%", radialaxis_tickvals=[0, 0.05, 0.10, 0.15, 0.20])

	return json.dumps(fig, cls=utils.PlotlyJSONEncoder)
Esempio n. 17
0
def update_graph(country_drop):


    #country_color = [{
    #    country_drop: '#002366' 
   # } ]
    fig = go.Figure()

    for country in countries:
        #color = country_color.get(country, 'lightslategrey')
        col = ["purple", "red", "rosybrown",
            "royalblue", "rebeccapurple", "saddlebrown", "salmon"]
        color = random.choice(col) if country in country_drop else 'lightslategrey'
        highlight = color != 'lightslategrey' 
        data_filtered = final[final.country == country]
        plot_data = data_filtered
        axis = plot_data.variable.tolist()
        axis.append(axis[0])
        value = plot_data.value.tolist()
        value.append(value[0])
        fig.add_trace(
            go.Scatterpolar(
                r=value, 
                theta=axis,
                showlegend=highlight, 
                name=country, 
                hoverinfo='name+r',
                mode='lines',
                line_color=color,
                opacity=0.8 if highlight else 0.2,
                line_width=2.6 if highlight else 0.5 
            )
        )

    title = 'Comparison between countries in each indicator.'             '<br><span style="font-size:10px"><i>'             'Values range from 0 to 1</span></i>'

    fig.update_layout(
        title_text = title,
        title_font_color = '#333333',
        title_font_size = 14,    
        polar_bgcolor='white',
        polar_radialaxis_visible=True,
        polar_radialaxis_showticklabels=True,
        polar_radialaxis_tickfont_color='darkgrey',
        polar_angularaxis_color='grey',
        polar_angularaxis_showline=False,
        polar_radialaxis_showline=False,
        polar_radialaxis_layer='below traces',
        polar_radialaxis_gridcolor='#F2F2F2',
        polar_radialaxis_range=(0,1),
        polar_radialaxis_tickvals=[25, 50],
        polar_radialaxis_tickmode='array',

        legend_font_color = 'grey', # We don't want to draw attention to the legend 
        legend_itemclick = 'toggleothers', # Change the default behaviour, when click select only that trace
        legend_itemdoubleclick = 'toggle', # Change the default behaviour, when double click ommit that trace
        width = 1000, # chart size 
        height = 600 # chart size
    )
    return fig
Esempio n. 18
0
    def compare_countries(value, data):
        """
        This callback updates scatter polar graph based on filter's selected options.
        :param value: selected countries
        :return: Scatter polar graph
        """
        if data is None:
            raise PreventUpdate

        df = pd.DataFrame.from_dict(data)
        categories = list(df.columns)

        fig = go.Figure()

        filter_df = df[df.index.isin(value)]

        for index, row in filter_df.iterrows():
            fig.add_trace(
                go.Scatterpolar(r=row.values.flatten().tolist(),
                                theta=categories,
                                fill='toself',
                                name=index))

        fig.update_layout(
            polar=dict(radialaxis=dict(visible=True, range=[0, 1])),
            showlegend=True,
            width=700,
            height=700)
        return fig
def update_figure(selected_hours):
    filter_df = test[test.epoch == selected_hours]
    traces = []
    for channel in filter_df.Channel.unique():
        Channel_df = filter_df[filter_df['Channel'] == channel]
        traces.append(go.Scatterpolar(
            r=Channel_df['r'],
            theta=Channel_df['theta'],
            text=Channel_df['Channel'],
            mode='markers',
            opacity=0.7,
            marker={
                'size': 25,
                'color': Channel_df['color'],
                'line': {'width': 0.5, 'color': Channel_df['color']},
            },
            subplot= 'polar',
            name= channel,
            
        ))
    return {
        'data': traces,
        'layout': go.Layout(
            polar={'angularaxis': {'rotation': 90}}, 
            margin=dict(t=20, r=0, b=100, l=70))
    }
Esempio n. 20
0
    def get_test_radar_chart(self):
        exp_results = self.read_file()

        min_loss = np.inf
        best_run = None
        for min_r in range(len(exp_results)):
            if 'loss' in exp_results[
                    min_r] and exp_results[min_r]['loss'] < min_loss:
                min_loss = exp_results[min_r]['loss']
                best_run = min_r

        test_fair = exp_results[best_run]['test_fair']
        test_acc = exp_results[best_run]['test_acc']
        test_robust = exp_results[best_run]['test_robust']
        test_number_features = exp_results[best_run]['cv_number_features']

        categories = ['Accuracy', 'Fairness', 'Simplicity', 'Safety']

        fig = go.Figure()

        fig.add_trace(
            go.Scatterpolar(r=[
                test_acc, test_fair, 1.0 - test_number_features, test_robust
            ],
                            theta=categories,
                            fill='toself',
                            name='Best Result on Test'))

        fig.update_layout(
            title='Best Result on Test',
            polar=dict(radialaxis=dict(visible=True, range=[0, 1])),
            showlegend=False)

        return fig
Esempio n. 21
0
def plot_pattern(incident_angles, pattern, fig=None, log_scale_min=-50):
    """
        Plots the radiation pattern on a polar plot using the plotly library
        
        Parameters:
        ----------
            :param pattern       : Radiation pattern to plot. The first column should be the incident angles while the second 
                                   should be the directivity values in dBi
            :param fig           : Plotly compatible figure object, if not specified a new object will be created [default:None]
            :param log_scale_min : Radiation pattern values that are less than this threshold will be truncated
            
            :type pattern      : 2D numpy array
            :type fig          : Plotly compatible figure object
            :type log_scale_min: float
       
        Return values:
       -----------------

            :return fig : Figure object
            :rype   fig : Plotly compatible figure object
    """    # Remove extreme low values
    pattern = [
        log_scale_min if pattern_i < log_scale_min else pattern_i
        for pattern_i in pattern
    ]

    if fig is None:
        fig = go.Figure()

    fig.add_trace(go.Scatterpolar(r=pattern, theta=incident_angles))
    fig.update_layout(title_text="Radiation pattern")
    plot(fig)

    return fig
Esempio n. 22
0
def create_advanced_star_plot(pokemon_name):
    # gets the pokemon's row
    data_sample = dataset.loc[dataset['Name'] == pokemon_name]

    stats = ['HP', 'Attack', 'Defense', 'SP Attack', 'SP Defense', 'Speed']
    stat_vals = [
        data_sample['HP'].values[0], data_sample['Attack'].values[0],
        data_sample['Sp_Atk'].values[0], data_sample['Sp_Def'].values[0],
        data_sample['Speed'].values[0]
    ]

    # creates the actual figure with the pokemon's stats
    star_fig = go.Figure(data=go.Scatterpolar(
        r=stat_vals, theta=stats, fill='toself', name='Pokemon Stats'))

    star_plot_title = str(pokemon_name) + '\'s Stats Star Plot'
    star_fig.update_layout(polar=dict(radialaxis=dict(visible=True,
                                                      range=[0, 255]), ),
                           showlegend=False,
                           title={
                               'text': star_plot_title,
                               'y': 0.95,
                               'x': 0.5,
                               'xanchor': 'center',
                               'yanchor': 'top'
                           },
                           margin=dict(l=55, r=55, t=55, b=55))

    return star_fig
def draw_polar(vis, exclude=None):
    telescope, names, ids, xpos, ypos, stations = getPlotantsAntennaInfo(
        vis, False, exclude, False)

    # code from pipeline summary.py
    # PlotAntsChart draw_polarlog_ant_map_in_subplot
    if 'VLA' in telescope:
        # For (E)VLA, set a fixed local center position that has been
        # tuned to work well for its array configurations (CAS-7479).
        xcenter, ycenter = -32, 0
        # rmin_min, rmin_max = 12.5, 350
    else:
        # For non-(E)VLA, take the median of antenna offsets as the
        # center for the plot.
        xcenter = np.median(xpos)
        ycenter = np.median(ypos)
        # rmin_min, rmin_max = 3, 350

    r = ((xpos - xcenter)**2 + (ypos - ycenter)**2)**0.5
    theta = np.arctan2(xpos - xcenter, ypos - ycenter) * 180.0 / 3.14
    data = go.Scatterpolar(r=r, theta=theta)
    fig = go.Figure(data)
    # Set options common to all traces with fig.update_traces
    fig.update_traces(mode='markers', marker_line_width=2, marker_size=10)
    fig.update_layout(title=telescope,
                      xaxis=dict(title_text="X (m)"),
                      yaxis=dict(title_text="Y (m)"),
                      yaxis_zeroline=False,
                      xaxis_zeroline=False,
                      autosize=False,
                      width=500,
                      height=500)
    return fig
Esempio n. 24
0
def update_golden_angles(max_angle_value, total_number_of_angles):
    fig = go.Figure()

    list_angles = retrieve_list_of_golden_angles(total_number_of_angles,
                                                 max_angle=max_angle_value)
    data = pd.DataFrame(list_angles, columns=['angles'])

    fig.add_trace(go.Scatterpolar(theta=data['angles'], mode='markers+lines'))
    fig.layout.xaxis.title = "Iteration number"
    fig.layout.paper_bgcolor = '#E5ECF6'

    table = dt.DataTable(
        columns=([{
            'id': 'angles',
            'name': 'Angles (degrees)',
            'type': 'numeric',
            'editable': False
        }]),
        data=data.to_dict('records'),
        export_format='csv',
        style_header={
            'backgroundColor': 'rgb(30, 30, 30)',
            'color': 'white'
        },
        style_cell={'textAlign': 'left'},
        style_table={'maxWidth': '30%'},
    )

    return fig, table
Esempio n. 25
0
    def country_radar():
        categories = [
            'Neuroticism', 'Openness', 'Extraversion', 'Agreeableness',
            'Conscientiousness', 'Neuroticism'
        ]

        fig = go.Figure()

        for i in user_select:
            fig.add_trace(
                go.Scatterpolar(r=[
                    df[df.Country == i].groupby('Country')
                    ['neu'].mean().to_list()[0], df[df.Country == i].groupby(
                        'Country')['ope'].mean().to_list()[0],
                    df[df.Country == i].groupby('Country')
                    ['ext'].mean().to_list()[0], df[df.Country == i].groupby(
                        'Country')['agr'].mean().to_list()[0],
                    df[df.Country == i].groupby('Country')
                    ['con'].mean().to_list()[0], df[df.Country == i].groupby(
                        'Country')['neu'].mean().to_list()[0]
                ],
                                theta=categories,
                                fill='toself',
                                name=i))

        fig.update_layout(
            polar=dict(radialaxis=dict(visible=True, range=[0, 6])),
            showlegend=True)

        # fig.show()
        return fig
Esempio n. 26
0
    def update_graph(playlists):
        """
        callback function for radar graph for playlists
        :param playlists: list of playlists
        :type playlists: String or List of Strings
        :return: Figure containing radar graph for audio features in playlists
        :rtype: plotly.graph_objs
        """
        if isinstance(playlists, str):
            playlists = [playlists]
        df = pd.read_csv(f'.csv_caches/{get_my_id()}/audio_feature_kmean.csv').drop(['Unnamed: 0'], axis=1)
        fig = go.Figure()
        for playlist in playlists:
            playlist_df = df[df['playlist_name'] == playlist]
            categories = ['danceability', 'energy', 'key', 'loudness', 'mode',
                          'speechiness', 'acousticness', 'instrumentalness', 'liveness',
                          'valence', 'tempo']
            for col in playlist_df.columns:
                if col in categories:
                    scaler.fit(playlist_df.loc[:, [col]])
                    playlist_df.loc[:, col] = scaler.transform(playlist_df.loc[:, col].values.reshape(-1, 1)).ravel()
            feature_val_playlist = playlist_df[categories].mean(0)

            legend_str = '<br>'.join(textwrap.wrap(playlist, width=12))
            fig.add_trace(go.Scatterpolar(
                r=feature_val_playlist,
                theta=categories,
                fill='toself',
                name=f'{legend_str}'
            ))
        return fig
def radarChart(id, name, screen_name, location, df, df2):

    ls = [0] * len(df.columns)
    ind = 0
    for i in df.columns:
        if id in df[i].values:
            print(f"This ID:{id} is present in {i}")
            ls[ind] += 1
        ind += 1
    print(ls)
    fig = go.Figure(data=go.Scatterpolar(
        r=ls,
        theta=df2.iloc[0].values,
        fill='toself',
        name=name,
    ))

    fig.update_layout(
        polar=dict(radialaxis=dict(visible=True), ),
        showlegend=False,
        title=go.layout.Title(
            text=
            f"Tagging for {name}(@{screen_name}) - ID: {id} - Location:{location}"
        ))
    fig.show()
Esempio n. 28
0
    def draw(self):
        """
        Generate Radar Chart visualization
        """
        label_name, numerical_column = self._check_requirements()

        if label_name is not None and numerical_column is not None:
            categories = numerical_column
            data_label = self.dataframe[label_name]
            data_numeric = self.dataframe[numerical_column]

            list_number = []

            fig = go.Figure()

            for i in range(len(data_numeric)):
                idx_data_numeric = (list(data_numeric.iloc[i]))
                fig.add_trace(
                    go.Scatterpolar(r=idx_data_numeric,
                                    theta=categories,
                                    fill='toself',
                                    name=data_label[i]))
                list_number.append(idx_data_numeric)

            fig.update_layout(polar=dict(
                radialaxis=dict(visible=True, range=[0, max(list_number)])),
                              showlegend=False)

            fig.show()
Esempio n. 29
0
def updateRadarGraph(names):
    categories = ['Attack', 'Defense', 'Sp_Atk', 'Sp_Def', 'Speed']

    fig = go.Figure()
    '''
    with open('names.csv') as csvfile:
        readCSV = csv.reader(csvfile, delimiter=',')
        for row in readCSV:
            names = row
    '''
    num = len(names)

    for i in range(num):
        option_df = df[(df.Name == names[i])]
        option_value = []
        for j in range(5):
            option_value.append(int(option_df.iloc[0][categories[j]]))

        fig.add_trace(
            go.Scatterpolar(r=option_value,
                            theta=categories,
                            fill='toself',
                            name=names[i]))

    fig.update_layout(
        polar=dict(radialaxis=dict(visible=True, range=[0, 200])),
        showlegend=True,
        paper_bgcolor='#ffffff',
        plot_bgcolor='#ffffff')

    return fig
Esempio n. 30
0
def make_radar_chart(norm_df, n_clusters):
    fig = go.Figure()
    cmap = cm.get_cmap('tab20b')
    angles = list(norm_df.columns[5:])
    angles.append(angles[0])

    layoutdict = dict(radialaxis=dict(visible=True, range=[0, 1]))
    maxes = dict()

    for i in range(n_clusters):
        subset = norm_df[norm_df['cluster'] == i]
        data = [np.mean(subset[col]) for col in angles[:-1]]
        maxes[i] = data.index(max(data))
        data.append(data[0])
        fig.add_trace(
            go.Scatterpolar(
                r=data,
                theta=angles,
                # fill='toself',
                # fillcolor = 'rgba' + str(cmap(i/n_clusters)),
                mode='lines',
                line_color='rgba' + str(cmap(i / n_clusters)),
                name="Cluster " + str(i)))

    fig.update_layout(polar=layoutdict, showlegend=True)
    fig.update_traces()
    return fig, maxes