Beispiel #1
0
def update_projection_plot(figure, data, RGB_values):
    if figure is None or data is None or RGB_values is None:
        # print('no data')
        raise PreventUpdate

    thetas = np.array(data['thetaVs'])
    arranged_thetas = np.append(np.flip(thetas[thetas < 0]),
                                thetas[thetas >= 0])
    phis = np.array(data['phiVs'])
    RGB_values = np.array(RGB_values)

    figure = go.Figure()

    previous_radius = 0
    for theta in arranged_thetas:
        scale = np.max(np.abs(arranged_thetas))
        radius = 2 * np.sin(np.radians(theta) / 2)
        delta_r = np.abs(scale * (previous_radius - radius) / np.sqrt(2))
        for phi in phis:
            RGB_color = RGB_values[thetas == theta, phis == phi][0]
            # print(RGB_color)
            if theta == 0:
                delta_r = 0
            if theta >= 0:
                figure.add_trace(
                    go.Barpolar(name=str(theta),
                                r=[delta_r],
                                theta=[phi],
                                marker_color='rgb(' + str(RGB_color[0]) + ',' +
                                str(RGB_color[1]) + ',' + str(RGB_color[2]) +
                                ')'))
            elif theta < 0:
                figure.add_trace(
                    go.Barpolar(name=str(theta),
                                r=[delta_r],
                                theta=[180 + phi],
                                marker_color='rgb(' + str(RGB_color[0]) + ',' +
                                str(RGB_color[1]) + ',' + str(RGB_color[2]) +
                                ')'))
        previous_radius = radius

        figure.update_layout(title="BRDF polar representation")

        # if theta < 0:
        #     figure.add_trace(pgo.Barpolar(
        #     r=np.flip(np.array([2*np.cos(np.radians(theta)) for angles in thetas])),
        #     theta=180+phis))
    return figure
Beispiel #2
0
def fig_world_trend2():
    fig = make_subplots(
        rows=2,
        cols=2,
        specs=[[{
            "type": "xy"
        }, {
            "type": "polar"
        }], [{
            "type": "domain"
        }, {
            "type": "scene"
        }]],
    )

    fig.add_trace(go.Bar(y=[2, 3, 1]), row=1, col=1)
    fig.add_trace(go.Barpolar(theta=[0, 45, 90], r=[2, 3, 1]), row=1, col=2)
    fig.add_trace(go.Pie(values=[2, 3, 1]), row=2, col=1)
    fig.add_trace(go.Scatter3d(x=[2, 3, 1],
                               y=[0, 0, 0],
                               z=[0.5, 1, 2],
                               mode="lines"),
                  row=2,
                  col=2)
    fig.update_layout(height=700, showlegend=False)
    # fig.show()
    return fig
Beispiel #3
0
def mainGraph(yearin, selected1):
    newYear = Dyears.get(yearin)
    run_df = df[(df.index > '11/01/{} 00:00'.format(str(years[0]))) & (df.index <= '11/01/{} 00:00'.format(newYear))]
    wind = run_df['wddir'].value_counts().to_frame()
    wind = wind.sort_index(axis=0, level=None, ascending=True, )

    # print(yearin,selected1)
    thedate = run_df.index
    selected = selected1
    fig = go.Figure()
    for i in selected:
        if i == 'BoilerOn':
            # print('y')
            y0 = run_df['{}'.format(i)] // 5
        else:
            # print('N')
            y0 = run_df['{}'.format(i)]
        thename = i
        fig.add_trace(go.Scatter(x=thedate, y=y0, mode='lines', name=discipt.get(i))),

    fig2 = go.Figure()
    fig2.add_trace(go.Barpolar(r=wind.wddir, marker_color='rgb(33,208,57)'))
    fig2.update_layout(title='Wind Speed Distribution', font_size=16, legend_font_size=16,
                       polar_angularaxis_rotation=90, )

    fig3 = go.Figure()
    y03 = run_df['Sitting_Room'].subtract(run_df['temp'], fill_value=1)

    y03[y03 < 0] = 0

    fig3.add_trace(go.Scatter(x=thedate, y=y03, mode='lines', name='Temperature Diffierance', \
                              fill='tozeroy', fillcolor='#FF7E00', line=dict(color='firebrick', width=1)))

    return fig, fig2, fig3
Beispiel #4
0
def get_bar_polar(num_of_events_normal, num_of_events_heavy):
    normal_barpolar = None
    if len(num_of_events_normal) > 0:
        normal_barpolar = go.Barpolar(
            r=list(num_of_events_normal["events"]),
            theta=num_of_events_normal["month_str"],
            name="Number of normal precipitation events",
            marker=dict(color="blue", line_color="black"),
            hoverinfo=["all"],
            opacity=0.75)
    heavy_barpolar = go.Barpolar(r=list(num_of_events_heavy["events"]),
                                 theta=num_of_events_heavy["month_str"],
                                 name="Number of heavy precipitation events",
                                 marker=dict(color="red", line_color="black"),
                                 hoverinfo=["all"],
                                 opacity=0.75)
    return normal_barpolar, heavy_barpolar
    def create_polar_plot(self, long, lat, depth, r_column, theta_column):
        '''
        Method plots and returns a plotly graph object that contains a polar/radial
        plot based on the input coordinates and the graph format pulled from a
        formatting dictionary

        Parameters
        ----------
        long : float
            The longnitude value of the location point

        lat : float
            The latitude value of the location point

        depth : float
            The depth value of the location point

        r_column : str
            A string indicating the data category that will be extracted to form
            the r values in the (r, theta) polar coordinate system via the data
            extraction api.

        theta_column : str
            A string indicating the data category that will be extracted to form
            the theta values in the (r, theta) polar coordinate system via the data
            extraction api. This value MUST be either radians or degrees.

        Returns
        -------
        barpolar_plot : plotly.graph_objects
            A plotly graphing object that can be inserted into a plotly figure.
        '''

        # Extracting data from the ingestion engine:
        r = self.get_node_data(long, lat, depth, r_column)
        theta = self.get_node_data(long, lat, depth, theta_column)

        # Attempting to convert the theta to degree values of they are in radians:
        try:
            theta = theta.apply(lambda x: math.degree(x))
        except:
            pass

        # Initalizing the barpolar plot based on formatting dict:
        barpolar_plot = go.Barpolar(
            r=r[self.timeseries_format[r_column]['df_column']],
            theta=theta[self.timeseries_format[theta_column]['df_column']],
            width=7.0,
            opacity=0.8,
            marker=dict(color=r[self.timeseries_format[r_column]['df_column']],
                        colorscale="Viridis",
                        colorbar=dict(
                            title=self.timeseries_format[r_column]['units'])))

        return barpolar_plot
Beispiel #6
0
def swatches_cyclical(template=None):
    """
    Parameters
    ----------
    template : str or dict or plotly.graph_objects.layout.Template instance
        The figure template name or definition.

    Returns
    -------
    fig : graph_objects.Figure containing the displayed image
        A `Figure` object. This figure demonstrates the color scales and
        sequences in this module, as polar bar charts.
    """
    import plotly.graph_objects as go
    from plotly.subplots import make_subplots
    from plotly.express._core import apply_default_cascade

    args = dict(template=template)
    apply_default_cascade(args)

    rows = 2
    cols = 4
    scales = ["Twilight", "IceFire", "Edge", "Phase", "HSV", "mrybm", "mygbm"]
    fig = make_subplots(
        rows=rows,
        cols=cols,
        subplot_titles=scales,
        specs=[[{
            "type": "polar"
        }] * cols] * rows,
    )

    for i, scale in enumerate(scales):
        fig.add_trace(
            go.Barpolar(
                r=[1] * int(360 / 5),
                theta=list(range(0, 360, 5)),
                marker_color=list(range(0, 360, 5)),
                marker_cmin=0,
                marker_cmax=360,
                marker_colorscale=scale,
                name=scale,
            ),
            row=int(i / cols) + 1,
            col=i % cols + 1,
        )
    fig.update_traces(width=5.2,
                      marker_line_width=0,
                      base=0.5,
                      showlegend=False)
    fig.update_polars(angularaxis_visible=False, radialaxis_visible=False)
    fig.update_layout(title="plotly.colors.cyclical",
                      template=args["template"])
    return fig
Beispiel #7
0
def main(df):
    # Change arguments based off customizations
    num_data = select_data_on_timesplit(df, DATATYPE, TIMESPLIT)

    num_splits = len(num_data)
    increments = [(x + 1) * (360 / num_splits) for x in range(num_splits)]

    fig = go.Figure(
        go.Barpolar(r=num_data,
                    theta=increments,
                    marker_color=px.colors.sequential.deep))

    fig.update_layout(title="Total {} on Each Day of All Years".format(
        DATATYPE.lower().capitalize()), )

    fig.show()
Beispiel #8
0
def rose_plot(ax, angles, bins=16, log_scale=None, offset=0, lab_unit="degrees",
              start_zero=False, weights=None, plotter='plt', **param_dict):
    """
    Plot polar histogram of angles on ax. ax must have been created using
    subplot_kw=dict(projection='polar'). Angles are expected in radians.
    """
    # Wrap angles to [-pi, pi)
    angles = (angles + np.pi) % (2 * np.pi) - np.pi
    binsj = bins
    # Set bins symetrically around zero
    if start_zero:
        # To have a bin edge at zero use an even number of bins
        # if bins % 2:
        #     bins += 1
        binsj = np.linspace(-np.pi, np.pi + 0.01, num=bins + 1)
    
    # Bin data and record counts
    count, bin = np.histogram(angles, bins=binsj, weights=weights)
    # Compute width of each bin
    widths = np.diff(bin)
    
    # By default plot density (frequency potentially misleading)
    if log_scale is None or log_scale is True:
        while 0 in count:
            count[np.where(np.array(count) == 0)[0][0]] = 1
        radius = np.log10(count)
    else:
        radius = count

    if plotter =='plotly':
        return go.Barpolar(theta=bin[:-1]*180/np.pi + 180/bins, r=radius, width=360/bins, showlegend=False)
        
        
        
    elif plotter == 'plt':
        # Plot data on ax
        ax.bar(bin[:-1], radius, zorder=1, align='edge', width=widths, edgecolor='C0', fill=True, linewidth=0.1)
        
        # Set the direction of the zero angle
        ax.set_theta_offset(offset)
        ax.set_yticks([min(radius), min(radius)], minor=True)
        ax.set_yticklabels([])
    
        if lab_unit == "radians":
            label = ['$0$', r'$\pi/4$', r'$\pi/2$', r'$3\pi/4$',
                     r'$\pi$', r'$5\pi/4$', r'$3\pi/2$', r'$7\pi/4$']
            ax.set_xticklabels(label)
Beispiel #9
0
def plot_pie_chart_px(df,by='pop'):
    tot_pop = df.query('city == "All"')['pop']
    df = df.query('city != "All"')
    radius = df['ratio']
    # theta goes from 0 to 360-1
    width = np.array(df['pop'] / float(tot_pop) * 360)
    theta = np.cumsum(np.concatenate((width,[0])))[:-1] - width/2
    labels = np.array(df['city'])
    labels = ['{}<br>{:.3f}%'.format(x,y) for x,y in zip(labels,radius)]
    fig = go.Figure(go.Barpolar(
        r=radius,
        theta=theta,
        width=width,
        marker_color=3*["#E4FF87", '#709BFF', '#709BFF', '#FFAA70', '#FFAA70', '#FFDF70', '#B6FFB4'],
        marker_line_color="black",
        marker_line_width=1,
        opacity=0.8
        ))
    """layout=go.Layout(annotations=[
        go.layout.Annotation(
            text='Some<br>multi-line<br>text',
            align='left',
            showarrow=False,
            xref='paper',
            yref='paper',
            x=1.1,
            y=0.8,
            bordercolor='black',
            borderwidth=1
        )
    ]))"""
    r = np.linspace(0,1,10)
    fig.update_layout(
        title="Confirmed cases (% per city), March 27th",
        template=None,
        polar_angularaxis = dict(tickvals=theta,
                             ticktext=labels),
        polar_radialaxis = dict(tickvals=r,
                             ticktext=['{:1.2f}%'.format(x) for x in r])
    )
    fig.show()
Beispiel #10
0
def get_country_features_barchart(df, country='GBR'):
    features = get_audio_features()
    chart_df = df[df['iso3'] == country]
    series = chart_df[[f for f in features]].mean() / df[['country', *[f for f in features]]].groupby(
        'country').mean().max()
    fig = dict(
        data=[
            go.Barpolar(
                r=[series.loc[f] for f in features],
                theta=[v[0] for v in features.values()],
                width=1,
                marker_color=[v[1] for v in features.values()],
            ),
        ],
        layout={
            **default_graph_layout(),
            'margin': dict(l=90, r=90),
            'title': 'Audio Feature Profile',
        }
    )
    return fig
Beispiel #11
0
def plot_distr_over_circle(cluster_dict, max_radius=5):
    '''
    Plots the distribution of notes pairs over the circle of fifths
    for every obtained cluster
    Parameters:
        - cluster_dict: dictionary
          An output of get_note_pairs_per_cluster function
        - max_radius: float or int
          The maximum radius of the output circle. 
          One may adjust it to get a more artistic visualization 
    '''
    num_clusters = len(cluster_dict)
    cluster_dict_copy = cluster_dict.copy()
    cluster_dict_copy = clear_cluster_dict(cluster_dict_copy)
    cluster_dict_copy = rename_keys(cluster_dict_copy)
    cluster_dict_copy = normalize(cluster_dict_copy)
    radius_values = prepare_radius(cluster_dict_copy)

    bar_polar_plots = []
    for i in range(num_clusters):
        bar_polar_plots.append(go.Barpolar(
                                              r=radius_values[i],
                                              name='cluster '+str(i),
                                              theta=circle_of_fifths,
                                              width=np.ones(12),
                                              marker_color=i,
                                              marker_line_width=1,
                                              opacity=0.7
                                          ))

    fig = go.Figure(bar_polar_plots)
    fig.update_layout(width=600, height=600)
    fig.update_layout(
                      template=None,
                      polar = dict(
                          radialaxis = dict(range=[0, max_radius], showticklabels=False, ticks='',  showgrid=False),
                          angularaxis = dict(showticklabels=True, ticks='outside', direction = "clockwise",  rotation=0, showgrid=False),
                          barmode="overlay"),
                      width=600, height=600)
    fig.show()
Beispiel #12
0
def plot_cylinder(analysis, metadata, args):

    counter = int(args["cylinder_num"]) - 1

    fig = go.Figure()
    x, graph = get_pressure_angular(
        analysis["cylinders"][str(counter)]['compression_pressure']["value"],
        analysis["cylinders"][str(counter)]['firing_pressure']["value"],
        analysis["cylinders"][str(counter)]["injection_timing"]["value"])
    fig.add_trace(go.Barpolar(theta=x, r=graph))

    fig.update_layout(
        margin=dict(l=0, r=0, t=0, b=0),
        paper_bgcolor="LightSteelBlue",
        polar=dict(angularaxis=dict(rotation=params["firing_order"][str(
            len(list(analysis["cylinders"].keys())))].index(
                int(args["cylinder_num"])) * 45,
                                    direction="clockwise")))
    fig.write_html("plots/" + args["type"] + " - " +
                   str(args["cylinder_num"]) + ".html")
    return "plots/" + args["type"] + " - " + str(
        args["cylinder_num"]) + ".html"
def show_barpolar(dic: dict):
    w_dic, original_dic = get_w(dic)
    weight_sum = sum(original_dic.values())
    fig = go.Figure(data=go.Barpolar(
        hovertext=[
            '{:.6f}%'.format(x / weight_sum * 100)
            for x in list(original_dic.values())
        ],
        hoverinfo="text",
        theta=list(w_dic.keys()),
        r=list(w_dic.values()),
    ), )

    return {
        'data': fig.data,
        'layout': {
            'title': {
                'text': 'Fund Type',
                'font': {
                    'size': 20
                }
            }
        }
    }
Beispiel #14
0
def plotly_template(template_specs):
    """
    Define the template for plotly

    Parameters
    ----------
    template_specs : dict
        dictionary contain specific figure settings
    
    Returns
    -------
    fig_template : plotly.graph_objs.layout._template.Template
        Template for plotly figure
    """
    import plotly.graph_objects as go
    fig_template = go.layout.Template()

    # Violin plots
    fig_template.data.violin = [
        go.Violin(
            box_visible=False,
            points=False,
            opacity=1,
            line_color="rgba(0, 0, 0, 1)",
            line_width=template_specs['plot_width'],
            width=0.8,
            marker_symbol='x',
            marker_opacity=0.5,
            hoveron='violins',
            meanline_visible=True,
            meanline_color="rgba(0, 0, 0, 1)",
            meanline_width=template_specs['plot_width'],
            showlegend=False,
        )
    ]

    fig_template.data.barpolar = [
        go.Barpolar(marker_line_color="rgba(0,0,0,1)",
                    marker_line_width=template_specs['plot_width'],
                    showlegend=False,
                    thetaunit='radians')
    ]

    # Pie plots
    fig_template.data.pie = [
        go.Pie(
            showlegend=False,
            textposition=["inside", "none"],
            marker_line_color=['rgba(0,0,0,1)', 'rgba(255,255,255,0)'],
            marker_line_width=[template_specs['plot_width'], 0],
            rotation=0,
            direction="clockwise",
            hole=0.4,
            sort=False,
        )
    ]

    # Layout
    fig_template.layout = (
        go.Layout(  # general
            font_family=template_specs['font'],
            font_size=template_specs['axes_font_size'],
            plot_bgcolor=template_specs['bg_col'],

            # x axis
            xaxis_visible=True,
            xaxis_linewidth=template_specs['axes_width'],
            xaxis_color=template_specs['axes_color'],
            xaxis_showgrid=False,
            xaxis_ticks="outside",
            xaxis_ticklen=0,
            xaxis_tickwidth=template_specs['axes_width'],
            xaxis_title_font_family=template_specs['font'],
            xaxis_title_font_size=template_specs['title_font_size'],
            xaxis_tickfont_family=template_specs['font'],
            xaxis_tickfont_size=template_specs['axes_font_size'],
            xaxis_zeroline=False,
            xaxis_zerolinecolor=template_specs['axes_color'],
            xaxis_zerolinewidth=template_specs['axes_width'],
            xaxis_range=[0, 1],
            xaxis_hoverformat='.1f',

            # y axis
            yaxis_visible=False,
            yaxis_linewidth=0,
            yaxis_color=template_specs['axes_color'],
            yaxis_showgrid=False,
            yaxis_ticks="outside",
            yaxis_ticklen=0,
            yaxis_tickwidth=template_specs['axes_width'],
            yaxis_tickfont_family=template_specs['font'],
            yaxis_tickfont_size=template_specs['axes_font_size'],
            yaxis_title_font_family=template_specs['font'],
            yaxis_title_font_size=template_specs['title_font_size'],
            yaxis_zeroline=False,
            yaxis_zerolinecolor=template_specs['axes_color'],
            yaxis_zerolinewidth=template_specs['axes_width'],
            yaxis_hoverformat='.1f',

            # bar polar
            polar_radialaxis_visible=False,
            polar_radialaxis_showticklabels=False,
            polar_radialaxis_ticks='',
            polar_angularaxis_visible=False,
            polar_angularaxis_showticklabels=False,
            polar_angularaxis_ticks=''))

    # Annotations
    fig_template.layout.annotationdefaults = go.layout.Annotation(
        font_color=template_specs['axes_color'],
        font_family=template_specs['font'],
        font_size=template_specs['title_font_size'])

    return fig_template
aoc=list(dfs['All other causes'][:12].values)
for i in range(len(aoc)):
    aoc[i]=math.sqrt(aoc[i]*(1000/12))/(asa[i]*math.pi)
wi=list(dfs['Wounds & injuries'][:12].values)
for i in range(len(wi)):
    wi[i]=math.sqrt(wi[i]*(1000/12))/(asa[i]*math.pi)
zd=list(dfs['Zymotic diseases'][:12].values)
for i in range(len(zd)):
    zd[i]=math.sqrt(zd[i]*(1000/12))/(asa[i]*math.pi)


fig = go.Figure()

fig.add_trace(go.Barpolar(
    r=aoc,
    name='All other causes',
    marker_color='rgb(102, 102, 102)'
    ))


fig.add_trace(go.Barpolar(
    r=wi,
    name='Wounds & injuries',
    marker_color='rgb(210, 121, 121)'
))


fig.add_trace(go.Barpolar(
    r=zd,
    name='Zymotic diseases',
    marker_color='rgb(173, 216, 230)'
Beispiel #16
0
def get_plotly_SxL(col_test, data):

    s = int(col_test[1])
    l = int(col_test[-1])

    df_forecasting = rolling_rf_data_pre(data, col=col_test)
    f = forescast_feature_pre(data, df_forecasting, col=col_test)
    t, model, pred = forecast_rf(df_forecasting, f)

    #fig = go.Figure()

    fig = make_subplots(
        rows=1,
        cols=2,
        subplot_titles=(
            " ", "Colors in the Same <br> Saturation X Lightness Palette"),
        specs=[[{
            'type': 'xy'
        }, {
            'type': 'polar'
        }]],
        column_widths=[0.75, 0.25])

    time = list(t)
    time.append(pd.to_datetime("2020-06-30"))
    forecast = list(100 * model)
    forecast.append(pred[0] * 100)

    fig.add_trace(go.Scatter(x=time,
                             y=forecast,
                             mode='lines',
                             name='model & forecast',
                             line=dict(color="#80bf40", dash='dot', width=3)),
                  row=1,
                  col=1)
    fig.add_trace(go.Scatter(x=t,
                             y=100 * df_forecasting[col_test],
                             mode='lines',
                             name='data',
                             line=dict(color="#409fbf", width=3)),
                  row=1,
                  col=1)

    title = 'Saturation = ' + str(satuation[s]) + ', Lightness = ' + str(
        satuation[l])

    fig.update_layout(
        title=title,
        title_x=0.,
        width=1050,
        height=650,
        xaxis_title="time",
        yaxis_title="% popularity",
        font=dict(family="Courier New, monospace", size=17, color="#7f7f7f"),
        xaxis=dict(
            range=[pd.to_datetime("2016-06-30"),
                   pd.to_datetime("2020-06-30")],
            rangeselector=dict(buttons=list([
                dict(count=6,
                     label="last 6 months",
                     step="month",
                     stepmode="backward"),
                dict(count=1,
                     label="last year",
                     step="year",
                     stepmode="backward"),
                dict(step="all")
            ])),
            rangeslider=dict(visible=True),
            type="date"),
        legend=dict(
            x=0,
            y=0.99,
            traceorder='normal',
            font=dict(size=12, ),
        ),
    )

    hexcode = []
    for h in hue_value:
        color = np.asarray((hsl2rgb([(h + 10) / 360, satuation_value[s] / 100,
                                     lightness_value[l] / 100])))
        color = color * 255
        color = color.astype('int')
        #print(color)
        hexcode.append(rgb2hex(color))

    fig.add_trace(go.Barpolar(r=[2] * 6,
                              theta=hue_value,
                              width=[60] * 6,
                              marker_color=hexcode,
                              showlegend=False,
                              hoverinfo='none'),
                  row=1,
                  col=2)

    fig.update_layout(
        template=None,
        polar=dict(
            radialaxis=dict(showticklabels=False,
                            ticks='',
                            showgrid=False,
                            showline=False),
            angularaxis=dict(showticklabels=False,
                             ticks='',
                             showgrid=False,
                             showline=False,
                             rotation=90),
        ),
    )

    return fig
Beispiel #17
0
import plotly.graph_objects as go

fig = go.Figure()

fig.add_trace(
    go.Barpolar(r=[77.5, 72.5, 70.0, 45.0, 22.5, 42.5, 40.0, 62.5],
                name='11-14 m/s',
                marker_color='rgb(106,81,163)'))
fig.add_trace(
    go.Barpolar(r=[57.5, 50.0, 45.0, 35.0, 20.0, 22.5, 37.5, 55.0],
                name='8-11 m/s',
                marker_color='rgb(158,154,200)'))
fig.add_trace(
    go.Barpolar(r=[40.0, 30.0, 30.0, 35.0, 7.5, 7.5, 32.5, 40.0],
                name='5-8 m/s',
                marker_color='rgb(203,201,226)'))
fig.add_trace(
    go.Barpolar(r=[20.0, 7.5, 15.0, 22.5, 2.5, 2.5, 12.5, 22.5],
                name='< 5 m/s',
                marker_color='rgb(242,240,247)'))

fig.update_traces(
    text=['North', 'N-E', 'East', 'S-E', 'South', 'S-W', 'West', 'N-W'])
fig.update_layout(
    title='Wind Speed Distribution in Laurel, NE',
    font_size=16,
    legend_font_size=16,
    polar_radialaxis_ticksuffix='%',
    polar_angularaxis_rotation=90,
)
fig.show()
if (sys.argv[1] == 'all'):
    choice = abs_nr
    color = 'rgba(0,128,0,1.0)'

if (sys.argv[1] == 'cloud'):
    choice = cloud_pr
    color = 'rgba(0,0,255,1.0)'

if (sys.argv[1] == 'track'):
    choice = track_pr
    color = 'rgba(255,0,0,1.0)'

if (sys.argv[1] != 'together'):

    fig.add_trace(go.Barpolar(theta=directions, r=choice, marker_color=color))
else:

    for i in range(len(clouds_normalized)):
        cloud = []
        track = []
        if (clouds_normalized[i] > tracks_normalized[i]):
            for j in range(len(clouds_normalized)):
                if (j == i):
                    track.append(tracks_normalized[i])
                    cloud.append(clouds_normalized[i] - tracks_normalized[i])
                else:
                    cloud.append(0)
                    track.append(0)
            fig.add_trace(
                go.Barpolar(theta=directions,
def createGraph(df, selected_var, category, dates):
    graph_var = []
    for element in selected_var:
        if element in VAR_CATEGORIES[category]:
            graph_var.append(str(element))

    fig = go.Figure()

    if category == "wind direction":

        n_bins = 12
        graph_df = pd.DataFrame()

        for wind_dir_var in graph_var:
            for wind_speed_var in VAR_CATEGORIES["wind speed"]:
                if (wind_dir_var[2:] in wind_speed_var) or (wind_dir_var[:2]
                                                            in wind_speed_var):

                    # #Creación de un dataframe que contiene los datos
                    # #de velocidad de viento asociado a su dirección
                    aux_df = db_functions.createDataFrameFromQuery(
                        df, [wind_speed_var], dates)
                    graph_df[wind_speed_var] = aux_df[wind_speed_var].copy()
                    graph_df[wind_dir_var] = df[wind_dir_var].copy()

                    if UNITS[wind_dir_var] == '(rad)':
                        for i in range(1, len(graph_df[wind_dir_var])):
                            graph_df[wind_dir_var][i] = graph_df[wind_dir_var][
                                i] * (360 / 2 * math.pi)

                    # #Agrupación de los datos de velocidad de viento
                    # #en bins en función de la dirección
                    bins = pd.cut(graph_df[wind_dir_var],
                                  list(np.linspace(0, 360, n_bins + 1)))
                    # #Cálculo de la frecuencia relativa y
                    # #velocidad media del viento en función de la dirección
                    plot_df = graph_df.groupby(bins)[wind_speed_var].agg(
                        ['count', 'mean'])
                    plot_df['count'] /= plot_df['count'].sum()

                    # #Representación de una magnitud ficticia representativa
                    # #con
                    # #fórmula=velocidad media en la dir*frecuencia en la dir
                    plot_df['y_trace'] = plot_df['count'] * plot_df['mean']

                    # ------

            fig.add_trace(
                go.Barpolar(
                    r=plot_df['y_trace'],
                    name=MAGNITUDE_SYMBOLS[wind_dir_var],
                    #mode='markers'
                ))

        fig.update_layout(
            title="IES - UPM: " + category.capitalize(),
            #polar_radialaxis_range=[0, plot_df['y_trace']],
            showlegend=True)

    else:
        for y_trace in graph_var:

            fig.add_trace(
                go.Scatter(x=df.index,
                           y=df[y_trace],
                           name=MAGNITUDE_SYMBOLS[y_trace],
                           mode='lines'))

        fig.update_layout(title="IES - UPM: " + category.capitalize(),
                          xaxis_title=MAGNITUDE_LABELS['measure_utc_dt'],
                          showlegend=True)

    return fig
Beispiel #20
0
                                     if x in df5_list else 'gray')
color = df4['color'].values.tolist()

layout = go.Layout(yaxis=dict(type='category'),
                   plot_bgcolor='white',
                   autosize=False,
                   width=1000,
                   height=2000)
fig = go.Figure(data=[go.Bar(x=y, y=x, marker_color=color, orientation='h')],
                layout=layout)
pio.plot(fig, filename=outputB)

fig = go.Figure()
fig.add_trace(
    go.Barpolar(
        r=df4['Total'],
        theta=360 * df4.index.values / len(df4['Total']),
        width=360 / len(df4['Total']),
        marker_color=color,
        opacity=0.8,
        base=100,
    ))

fig.update_layout(template=None,
                  polar=dict(radialaxis=dict(showticklabels=False, ticks=''),
                             angularaxis=dict(showticklabels=False,
                                              ticks='',
                                              rotation=90,
                                              direction="clockwise")))
pio.plot(fig, filename=outputC)
        else:
            marker_line_color = [
                "#d11141" if x == row['pred'] else "white" for x in ids
            ]

        # """Add the polar area chart to the canvas"""

        fig.add_trace(go.Barpolar(
            r=[i + 0.2 for i in r],
            offset=0,
            name='Current Prediction',
            theta=[76 + 72 * x for x in range(5)],
            width=[60],
            marker_color=marker_color,
            selectedpoints='',
            hovertext=[i for i in zip(ids, r)],
            text=[
                "Dial tone", "Hold music", "Human", "Message During Hold",
                "Initial Recorded Message"
            ],
            marker_line_color=marker_line_color,
            marker_line_width=[3 if x == row['pred'] else 0 for x in ids],
            opacity=1,
            showlegend=True),
                      row=1,
                      col=1)
        options = [
            "<b>Dial Tone</b>", "<b>Hold</b>", "<b>Human</b>",
            "<b>Message During Hold</b>", "<b>Initial Recorded Message</b>"
        ]
        #Add the table showing the probabilities assigned to each classification
Beispiel #22
0
def plotla2(databd, instalacao, RTC, datai, dataf, cols_selection,
            togglebuttons, disagreetext, index, foco):

    correlations = {'iA/pA': 'NA', 'iB/pB': 'NA', 'iC/pC': 'NA'}
    info_text = '<br>'
    html = "templates/"  #hc
    proj = "P&D Light"
    cols = colunas[cols_selection]
    togglebuttons.append(
        widgets.ToggleButtons(name='a',
                              options=['Concordo ', 'Discordo '],
                              description='',
                              disabled=False,
                              button_style='primary',
                              tooltips=[
                                  'Caso deveria ser levantado pelo GAUSS',
                                  'Caso não deveria ser levantado pelo GAUSS'
                              ],
                              icons=['thumbs-up', 'thumbs-down']))
    disagreetext.append(
        widgets.Text(value='',
                     placeholder='Motivo discordancia',
                     description='',
                     disabled=False))

    descr = "Instalacao " + instalacao
    fig = make_subplots(rows=3,
                        cols=1,
                        specs=[[{
                            "secondary_y": True
                        }], [{
                            "secondary_y": True
                        }], [{
                            "secondary_y": True
                        }]])

    if cols_selection == 'potencias':
        #ajuste da correlação para evitar NAN quando todos os valores são zerados
        correlations = {'iA/pA': 0, 'iB/pB': 0, 'iC/pC': 0}
        for i in ['A', 'B', 'C']:
            if (not np.isnan(databd['I' + i].corr(databd['P' + i]))):
                correlations['i' + i + '/p' + i] = databd['I' + i].corr(
                    databd['P' + i])

        databd = calcula_potencia_corrente(RTC, databd, cols_selection)
        fig.add_trace(go.Scatter(x=databd.index,
                                 y=databd['IA'],
                                 name='iA',
                                 line=dict(width=1)),
                      row=1,
                      col=1,
                      secondary_y=True)
        fig.add_trace(go.Scatter(x=databd.index, y=databd['PA'], name='pA'),
                      row=1,
                      col=1,
                      secondary_y=False)
        fig.add_trace(go.Scatter(x=databd.index,
                                 y=databd['IB'],
                                 name='iB',
                                 line=dict(width=1)),
                      row=2,
                      col=1,
                      secondary_y=True)
        fig.add_trace(go.Scatter(x=databd.index, y=databd['PB'], name='pB'),
                      row=2,
                      col=1,
                      secondary_y=False)
        fig.add_trace(go.Scatter(x=databd.index,
                                 y=databd['IC'],
                                 name='iC',
                                 line=dict(width=1)),
                      row=3,
                      col=1,
                      secondary_y=True)
        fig.add_trace(go.Scatter(x=databd.index, y=databd['PC'], name='pC'),
                      row=3,
                      col=1,
                      secondary_y=False)
        fig.update_yaxes(title_text="Potencia", secondary_y=False)
        fig.update_yaxes(title_text="Corrente", secondary_y=True)

    if cols_selection == 'angulos':
        fig.add_trace(
            go.Barpolar(name="avA",
                        r=[max(databd['VA'])] * len(databd['AVA']),
                        theta=databd['AVA'],
                        width=[1] * len(databd['AVA']),
                        marker_color=['blue'] * len(databd['AVA']),
                        marker_line_color='blue',
                        marker_line_width=2,
                        opacity=0.8))
        fig.add_trace(
            go.Barpolar(name="avB",
                        r=[max(databd['VB'])] * len(databd['AVB']),
                        theta=databd['AVB'],
                        width=[1] * len(databd['AVB']),
                        marker_color=['green'] * len(databd['AVB']),
                        marker_line_color='green',
                        marker_line_width=2,
                        opacity=0.8))
        fig.add_trace(
            go.Barpolar(name="avC",
                        r=[max(databd['VC'])] * len(databd['AVC']),
                        theta=databd['AVC'],
                        width=[1] * len(databd['AVC']),
                        marker_color=['red'] * len(databd['AVC']),
                        marker_line_color='red',
                        marker_line_width=2,
                        opacity=0.8))
        fig.update_layout(polar=dict(
            radialaxis_angle=90,
            radialaxis=dict(range=[
                0,
                max(max(databd['VA']), max(databd['VB']), max(databd['VC']))
            ],
                            showticklabels=True),
            angularaxis=dict(direction="counterclockwise", dtick=10)))
    if cols_selection == 'correntes':
        fig.add_trace(go.Scatter(x=databd.index, y=databd['IA'], name='iA'),
                      row=1,
                      col=1,
                      secondary_y=True)
        fig.add_trace(go.Scatter(x=databd.index, y=databd['VA'], name='vA'),
                      row=1,
                      col=1,
                      secondary_y=False)
        fig.add_trace(go.Scatter(x=databd.index, y=databd['IB'], name='iB'),
                      row=2,
                      col=1,
                      secondary_y=True)
        fig.add_trace(go.Scatter(x=databd.index, y=databd['VB'], name='vB'),
                      row=2,
                      col=1,
                      secondary_y=False)
        fig.add_trace(go.Scatter(x=databd.index, y=databd['IC'], name='iC'),
                      row=3,
                      col=1,
                      secondary_y=True)
        fig.add_trace(go.Scatter(x=databd.index, y=databd['VC'], name='vC'),
                      row=3,
                      col=1,
                      secondary_y=False)
        fig.update_yaxes(range=[-5, 150], secondary_y=False)
        fig.update_yaxes(title_text="Tensão", secondary_y=False)
        fig.update_yaxes(title_text="Corrente", secondary_y=True)

    if cols_selection == 'tensoes':
        fig = make_subplots(rows=3,
                            cols=1,
                            specs=[[{
                                "secondary_y": True
                            }], [{
                                "secondary_y": True
                            }], [{
                                "secondary_y": True
                            }]])
        fig.add_trace(go.Scatter(x=databd.index, y=databd['VA'], name='vA'),
                      row=1,
                      col=1,
                      secondary_y=True)
        fig.add_trace(go.Scatter(x=databd.index, y=databd['VAB'], name='vAB'),
                      row=1,
                      col=1,
                      secondary_y=False)
        fig.add_trace(go.Scatter(x=databd.index, y=databd['VB'], name='vB'),
                      row=2,
                      col=1,
                      secondary_y=True)
        fig.add_trace(go.Scatter(x=databd.index, y=databd['VBC'], name='vBC'),
                      row=2,
                      col=1,
                      secondary_y=False)
        fig.add_trace(go.Scatter(x=databd.index, y=databd['VC'], name='vC'),
                      row=3,
                      col=1,
                      secondary_y=True)
        fig.add_trace(go.Scatter(x=databd.index, y=databd['VAC'], name='vAC'),
                      row=3,
                      col=1,
                      secondary_y=False)
        fig.update_yaxes(title_text="Fase e Neutro", secondary_y=True)
        fig.update_yaxes(title_text="Entre Fases", secondary_y=False)
    fig.update_layout(title=go.layout.Title(
        text=
        f'<b>{instalacao} - {translate[cols_selection]}</b><br><b>{datai} a {dataf}</b><br><b>Sequência: {str(databd["FREQ"].unique()[0])}</b>',
        xref="paper",
        font=dict(family='Courier New, monospace', size=14),
        x=0))

    html_file = os.path.join(html, instalacao + '_' + cols_selection + ".html")
    fig.update_layout(dict1={'font': {'size': 10}})
    fig.update_layout(legend_orientation="h")
    fig.write_html(html_file, auto_open=False)
    build_page(html_file,
               colunas,
               cols_selection,
               databd,
               correlations=correlations)

    return togglebuttons, disagreetext
        track_over = track
        new_track_over = track_over - common
        r_common.append(common)
        r_cloud_over.append(cloud_over)
        r_track_over.append(new_track_over)
    else:
        common = track
        track_over = 0
        cloud_over = 0
        r_common.append(common)
        r_cloud_over.append(cloud_over)
        r_track_over.append(track_over)

fig.add_trace(
    go.Barpolar(theta=directions,
                r=r_common,
                name='Clouds and tracks overlapping',
                marker_color='rgba(255,0,255,0.5)'))

fig.add_trace(
    go.Barpolar(theta=directions,
                r=r_cloud_over,
                name='Only cloud',
                marker_color='rgba(0,0,255,0.5)'))

fig.add_trace(
    go.Barpolar(theta=directions,
                r=r_track_over,
                name='Track',
                marker_color='rgba(255,0,0,0.5)'))

fig.update_layout(font_size=36,
Beispiel #24
0
def youtube(n_clicks, value):
    show = playlist_serv(str(value), 30)

    df = pd.DataFrame(show)
    df1 = df[['title', 'views', 'likes', 'dislikes']]
    df1['views'] = df1.views.astype(int)
    df1['likes'] = df1.likes.astype(int)
    df1['dislikes'] = df1.dislikes.astype(int)
    df1['react'] = df1['likes'] + df1['dislikes']
    df1['ratio'] = df1['likes'] / df1['dislikes']
    df1['like_ratio'] = df1['likes'] / df1['react']

    vid = df1
    v_vid = vid.sort_values(['views'], ascending=False)
    l_vid = vid.sort_values(['likes'], ascending=False)
    d_vid = vid.sort_values(['dislikes'], ascending=False)
    r_vid = vid.sort_values(['react'], ascending=False)
    rt_vid = vid.sort_values(['ratio'], ascending=False)
    lr_vid = vid.sort_values(['like_ratio'], ascending=False)

    bubbles = (rt_vid['ratio'] / rt_vid['ratio'].max()) * 90
    shape_line = [
        do.layout.Shape(type='line',
                        x0=l_vid['title'][i],
                        y0=0,
                        x1=l_vid['title'][i],
                        y1=l_vid['likes'][i],
                        line_color='#3484F0') for i in range(len(l_vid))
    ]
    margins = do.layout.Margin(l=50, r=50, b=70, t=60)

    view = do.Figure(data=[
        do.Bar(x=v_vid['title'],
               y=v_vid['views'],
               hoverinfo='y',
               marker={'color': '#05719D'},
               width=.4)
    ],
                     layout=do.Layout(title=do.layout.Title(text='Video Views',
                                                            x=0.5),
                                      margin=margins,
                                      plot_bgcolor='#ffffff'))

    like = do.Figure(data=[
        do.Scatter(x=l_vid['title'],
                   y=l_vid['likes'],
                   hoverinfo='y',
                   mode='markers',
                   marker={
                       'color': '#3484F0',
                       'size': 15
                   })
    ],
                     layout=do.Layout(title=do.layout.Title(text='Likes',
                                                            x=0.5),
                                      shapes=shape_line,
                                      xaxis={'showgrid': False},
                                      margin=margins,
                                      plot_bgcolor='#ffffff'))

    dislike = do.Figure(data=[
        do.Bar(x=d_vid['title'],
               y=d_vid['dislikes'],
               hoverinfo='y',
               marker={'color': '#757575'},
               width=.4)
    ],
                        layout=do.Layout(title=do.layout.Title(text='Dislikes',
                                                               x=0.5),
                                         margin=margins,
                                         plot_bgcolor='#ffffff'))

    react = do.Figure(data=[
        do.Bar(x=r_vid['title'],
               y=r_vid['dislikes'],
               hoverinfo='y+name',
               marker={'color': '#757575'},
               width=.4,
               name='Dislikes'),
        do.Bar(x=r_vid['title'],
               y=r_vid['likes'],
               hoverinfo='y+name',
               marker={'color': '#3484F0'},
               width=.4,
               name='Likes')
    ],
                      layout=do.Layout(title=do.layout.Title(
                          text='Reaction Count (Likes + Dislikes)', x=0.5),
                                       barmode='stack',
                                       showlegend=False,
                                       margin=margins,
                                       plot_bgcolor='#ffffff'))

    react_ratio = do.Figure(data=[
        do.Scatter(x=rt_vid['likes'],
                   y=rt_vid['dislikes'],
                   text=rt_vid['title'],
                   mode='markers',
                   marker={
                       'color': '#D291BC',
                       'size': [i for i in bubbles],
                       'opacity': 0.4
                   })
    ],
                            layout=do.Layout(title=do.layout.Title(
                                text='Reaction Ratio (Likes / Dislikes)',
                                x=0.5),
                                             xaxis={'showgrid': False},
                                             yaxis={'showgrid': False},
                                             margin=margins,
                                             plot_bgcolor='#ffffff'))

    like_ratio = do.Figure(data=[
        do.Barpolar(r=lr_vid['like_ratio'],
                    theta=list(range(0, 360,
                                     360 // len(lr_vid['like_ratio']))),
                    width=[360 / len(lr_vid['like_ratio'])] *
                    len(lr_vid['like_ratio']),
                    hoverinfo='r+text',
                    text=lr_vid['title'],
                    marker={
                        'color': lr_vid['like_ratio'],
                        'colorscale': 'Viridis'
                    })
    ],
                           layout=do.Layout(title=do.layout.Title(
                               text='Like Ratio (Likes / Reaction Count)',
                               x=0.5),
                                            margin=margins,
                                            polar={
                                                'radialaxis': {
                                                    'showticklabels': False
                                                },
                                                'angularaxis': {
                                                    'showticklabels': False
                                                }
                                            },
                                            plot_bgcolor='#ffffff'))

    return view, like, dislike, react, react_ratio, like_ratio
Beispiel #25
0
def update_radar(city):
    # creating a subset dataframe
    df = data[[
        "City",
        "Cost of Living Index",
        "Purchasing Power Index",
        "Safety Index",
        "Health Care Index",
        "Pollution Index",
    ]]

    # categories
    cat = df.columns[1:].tolist()

    select_df = df[df["City"] == city]

    Row_list = []
    r = []
    # Iterate over each row
    for index, rows in select_df.iterrows():
        for i in range(len(cat)):
            # Create list for the current
            r.append(rows[cat[i]])

            # append the list to the final list
        Row_list.append(r)
        Row_list = list(np.concatenate(Row_list).flat)

    fig = go.Figure()

    fig.add_trace(
        go.Barpolar(
            r=Row_list,
            theta=cat,
            name="",
            marker_color=["rgb(243,203,70)"] * 6,
            marker_line_color="white",
            hoverinfo=["theta"] * 9,
            opacity=0.7,
            base=0,
        ))

    fig.add_trace(
        go.Barpolar(
            r=df.mean(axis=0).tolist(),
            theta=cat,
            name="",
            marker_color=["#d1d1cf"] * 6,
            marker_line_color="white",
            hoverinfo=["theta"] * 9,
            opacity=0.7,
            base=0,
        ))

    fig.update_layout(
        title="",
        font_size=12,
        polar=dict(
            bgcolor="rgba(0,0,0,0)",
            angularaxis=dict(linewidth=3, showline=False, showticklabels=True),
            radialaxis=dict(
                showline=False,
                showticklabels=False,
                linewidth=2,
                gridcolor="white",
                gridwidth=2,
            ),
        ),
    )

    return fig
Beispiel #26
0
        binned_wind[i, j] = foo.shape[0]

wind_inst_freq = binned_wind / np.sum(binned_wind)
wind_inst_freq = wind_inst_freq.ravel()


grp = df.groupby(["drct", "sped"]).size()\
        .reset_index(name="frequency")

import plotly.graph_objects as go

fig = go.Figure()

for i in slices_sped:
    fig.add_trace(
        go.Barpolar(r=[77.5, 72.5, 70.0, 45.0, 22.5, 42.5, 40.0, 62.5],
                    name=i))

binned_wind[0]
fig.add_trace(
    go.Barpolar(r=[77.5, 72.5, 70.0, 45.0, 22.5, 42.5, 40.0, 62.5],
                name='11-14 m/s',
                marker_color='rgb(106,81,163)'))
fig.add_trace(
    go.Barpolar(r=[57.5, 50.0, 45.0, 35.0, 20.0, 22.5, 37.5, 55.0],
                name='8-11 m/s',
                marker_color='rgb(158,154,200)'))
fig.add_trace(
    go.Barpolar(r=[40.0, 30.0, 30.0, 35.0, 7.5, 7.5, 32.5, 40.0],
                name='5-8 m/s',
                marker_color='rgb(203,201,226)'))
fig.add_trace(
Beispiel #27
0
def visualize_audio_similarities(df, cs_username, cs_api_key,
                                 similar_song_ids):
    songs = []
    artists = []

    for i in similar_song_ids[::-3]:
        artists.append(i)

    artist_cleaned = []

    for i in artists:
        res = str(i)[1:-1]
        artist_cleaned.append(res)

    for i in similar_song_ids[1::3]:
        songs.append(i)
    """
    """
    vals = [36, 72, 108, 144, 180, 216, 252, 288, 324, 360]
    theta = [23, 59, 95, 131, 167, 203, 239, 275, 311, 347]
    k = 4
    k2 = 8
    k3 = 12
    k4 = 16
    k5 = 20
    k6 = 24
    theta2 = [x + k for x in theta]
    theta3 = [x + k2 for x in theta]
    theta4 = [x + k3 for x in theta]
    theta5 = [x + k4 for x in theta]
    theta6 = [x + k5 for x in theta]
    theta7 = [x + k6 for x in theta]
    width = 7
    fig = go.Figure()
    fig.add_trace(
        go.Barpolar(
            r=df.iloc[0],
            theta=theta2,
            width=width,
            marker_color='red',
            marker_line_color="black",
            marker_line_width=2,
            opacity=0.9,
            name='Searched Song',
            hovertext=df.iloc[12],
            hoverinfo="text",
        ))

    fig.add_trace(
        go.Barpolar(
            r=df.iloc[2],
            theta=theta3,
            width=width,
            marker_color='gray',
            marker_line_color="black",
            marker_line_width=2,
            opacity=0.9,
            name=(f"{songs[0]} by {artist_cleaned[0]}"),
            hovertext=df.iloc[7],
            hoverinfo="text",
        ))

    fig.add_trace(
        go.Barpolar(
            r=df.iloc[3],
            theta=theta4,
            width=width,
            marker_color='violet',
            marker_line_color="black",
            marker_line_width=2,
            opacity=0.9,
            name=(f"{songs[1]} by {artist_cleaned[1]}"),
            hovertext=df.iloc[8],
            hoverinfo="text",
        ))

    fig.add_trace(
        go.Barpolar(
            r=df.iloc[4],
            theta=theta5,
            width=width,
            marker_color='purple',
            marker_line_color="black",
            marker_line_width=2,
            opacity=0.9,
            name=(f"{songs[2]} by {artist_cleaned[2]}"),
            hovertext=df.iloc[9],
            hoverinfo="text",
        ))

    fig.add_trace(
        go.Barpolar(
            r=df.iloc[5],
            theta=theta6,
            width=width,
            marker_color='blue',
            marker_line_color="black",
            marker_line_width=2,
            opacity=0.9,
            name=(f"{songs[3]} by {artist_cleaned[3]}"),
            hovertext=df.iloc[10],
            hoverinfo="text",
        ))

    fig.add_trace(
        go.Barpolar(
            r=df.iloc[6],
            theta=theta7,
            width=width,
            marker_color='orange',
            marker_line_color="black",
            marker_line_width=2,
            opacity=0.9,
            name=(f"{songs[4]} by {artist_cleaned[4]}"),
            hovertext=df.iloc[11],
            hoverinfo="text",
        ))

    fig.update_layout(
        template='none',
        width=800,
        height=800,
        hoverlabel=dict(
            namelength=-1,
            bgcolor="white",
            bordercolor='black',
            font_size=16,
            font_family="Rockwell",
        ),
        polar=dict(
            radialaxis=dict(
                range=[df[0:7].values.min(), df[0:7].values.max() + .1],
                showticklabels=False,
                ticks=''),
            angularaxis=dict(showticklabels=True,
                             tickmode='array',
                             tickvals=vals,
                             ticktext=df.columns,
                             ticks=''),
        ),
        title={
            'text': "<b>Comparing Audio Features</b>",
            'y': 0.95,
            'x': 0.51,
            'xanchor': 'center',
            'yanchor': 'top',
            'font': {
                'size': 20
            }
        },
        legend={
            'y': -0.33,
            'x': 0.49,
            'xanchor': 'center',
            'yanchor': 'bottom'
        },
    )

    chart_studio.tools.set_credentials_file(username=cs_username,
                                            api_key=cs_api_key)
    embed_var = py.plot(fig,
                        filename='pleasedonotbreakkk',
                        auto_open=True,
                        fileopt='new')
    return embed_var
Beispiel #28
0
mask = np.array(Image.open("images/kenyanFlag.jpg"))
image_colors = ImageColorGenerator(mask)

df = pd.read_csv("liveChatData.csv")
## Top 50 Most active users
top = df.Author.value_counts().head(20).to_frame().reset_index()
top.columns = ["Author", "Count"]

fig = go.Figure()
fig = fig.add_trace(
    go.Barpolar(theta=top.Author,
                r=top.Count,
                width=5,
                marker=dict(
                    color=top.Count,
                    colorscale="magma",
                ),
                marker_line_color="grey",
                marker_line_width=2,
                opacity=0.8))

app = dash.Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP])

server = app.server

app.layout = html.Div([
    dbc.Row([
        dbc.Col([
            html.Div([
                html.H1(children="YouTube Live Chat Analysis",
                        style={'text-align': 'center'})
Beispiel #29
0
def plot_pressure_theta_cylindrical(fluid_flow_object,
                                    z=0,
                                    from_numerical=True,
                                    fig=None,
                                    **kwargs):
    """Plot cylindrical pressure graphic in the theta direction.

    This function assembles cylindrical graphical visualization of the fluid pressure
    in the theta direction for a given axial position (z).

    Parameters
    ----------
    fluid_flow_object: a FluidFlow object
    z: int, optional
        The distance along z-axis to be considered.
    from_numerical: bool, optional
        If True, takes the numerically calculated pressure matrix as entry.
        If False, takes the analytically calculated one instead.
        If condition cannot be satisfied (matrix not calculated), it will take the one
        that is available and raise a warning.
    fig : Plotly graph_objects.Figure()
        The figure object with the plot.
    kwargs : optional
        Additional key word arguments can be passed to change the plot layout only
        (e.g. width=1000, height=800, ...).
        *See Plotly Python Figure Reference for more information.

    Returns
    -------
    fig : Plotly graph_objects.Figure()
        The figure object with the plot.

    Examples
    --------
    >>> from ross.fluid_flow.fluid_flow import fluid_flow_example
    >>> my_fluid_flow = fluid_flow_example()
    >>> my_fluid_flow.calculate_pressure_matrix_numerical() # doctest: +ELLIPSIS
    array([[...
    >>> fig = plot_pressure_theta_cylindrical(my_fluid_flow, z=int(my_fluid_flow.nz/2))
    >>> # to show the plots you can use:
    >>> # fig.show()
    """
    if (not fluid_flow_object.numerical_pressure_matrix_available
            and not fluid_flow_object.analytical_pressure_matrix_available):
        raise ValueError(
            "Must calculate the pressure matrix. "
            "Try calling calculate_pressure_matrix_numerical() or calculate_pressure_matrix_analytical() first."
        )
    if from_numerical:
        if fluid_flow_object.numerical_pressure_matrix_available:
            p_mat = fluid_flow_object.p_mat_numerical
        else:
            p_mat = fluid_flow_object.p_mat_analytical
    else:
        if fluid_flow_object.analytical_pressure_matrix_available:
            p_mat = fluid_flow_object.p_mat_analytical
        else:
            p_mat = fluid_flow_object.p_mat_numerical

    r = np.linspace(fluid_flow_object.radius_rotor,
                    fluid_flow_object.radius_stator)
    theta = np.linspace(0.0, 2.0 * np.pi + fluid_flow_object.dtheta / 2,
                        fluid_flow_object.ntheta)
    theta *= 180 / np.pi

    pressure_along_theta = p_mat[z, :]
    min_pressure = np.amin(pressure_along_theta)

    r_matrix, theta_matrix = np.meshgrid(r, theta)
    z_matrix = np.zeros((theta.size, r.size))

    for i in range(0, theta.size):
        inner_radius = np.sqrt(
            fluid_flow_object.xri[z][i] * fluid_flow_object.xri[z][i] +
            fluid_flow_object.yri[z][i] * fluid_flow_object.yri[z][i])

        for j in range(r.size):
            if r_matrix[i][j] < inner_radius:
                continue
            z_matrix[i][j] = pressure_along_theta[i] - min_pressure + 0.01

    if fig is None:
        fig = go.Figure()
    fig.add_trace(
        go.Barpolar(
            r=r_matrix.ravel(),
            theta=theta_matrix.ravel(),
            customdata=z_matrix.ravel(),
            marker=dict(
                color=z_matrix.ravel(),
                colorscale="Viridis",
                cmin=np.amin(z_matrix),
                cmax=np.amax(z_matrix),
                colorbar=dict(title=dict(text="<b>Pressure</b>", side="top")),
            ),
            thetaunit="degrees",
            name="Pressure",
            showlegend=False,
            hovertemplate=("<b>Raddi: %{r:.4e}</b><br>" +
                           "<b>θ: %{theta:.2f}</b><br>" +
                           "<b>Pressure: %{customdata:.4e}</b>"),
        ))
    fig.update_layout(
        polar=dict(
            hole=0.5,
            bargap=0.0,
            angularaxis=dict(rotation=-90 -
                             fluid_flow_object.attitude_angle * 180 / np.pi),
        ),
        **kwargs,
    )
    return fig
Beispiel #30
0
import plotly.graph_objects as go
import plotly.express as px

df = px.data.wind()  # 三维数据,风向,强度,频率

fig = go.Figure()

fig.add_trace(go.Barpolar())

# 频率对应半径,角度对应风向,颜色对应强度
fig = px.bar_polar(df,
                   r='frequency',
                   theta='direction',
                   color='strength',
                   template='plotly_dark',
                   color_discrete_sequence=px.colors.sequential.Plasma_r)
fig.show()