Пример #1
0
def graph2():
    trace1 = go.Barpolar(
        r=[77.5, 72.5, 70.0, 45.0, 22.5, 42.5, 40.0, 62.5],
        text=['North', 'N-E', 'East', 'S-E', 'South', 'S-W', 'West', 'N-W'],
        name='11-14 m/s',
        marker=dict(color='rgb(106,81,163)'))
    trace2 = go.Barpolar(
        r=[
            57.49999999999999, 50.0, 45.0, 35.0, 20.0, 22.5, 37.5,
            55.00000000000001
        ],
        text=['North', 'N-E', 'East', 'S-E', 'South', 'S-W', 'West', 'N-W'],
        name='8-11 m/s',
        marker=dict(color='rgb(158,154,200)'))
    trace3 = go.Barpolar(
        r=[40.0, 30.0, 30.0, 35.0, 7.5, 7.5, 32.5, 40.0],
        text=['North', 'N-E', 'East', 'S-E', 'South', 'S-W', 'West', 'N-W'],
        name='5-8 m/s',
        marker=dict(color='rgb(203,201,226)'))
    trace4 = go.Barpolar(
        r=[20.0, 7.5, 15.0, 22.5, 2.5, 2.5, 12.5, 22.5],
        text=['North', 'N-E', 'East', 'S-E', 'South', 'S-W', 'West', 'N-W'],
        name='< 5 m/s',
        marker=dict(color='rgb(242,240,247)'))
    data = [trace1, trace2, trace3, trace4]
    layout = go.Layout(
        title='Wind Speed Distribution in Laurel, NE',
        font=dict(size=16),
        legend=dict(font=dict(size=16)),
        radialaxis=dict(ticksuffix='%'),
        orientation=270,
    )
    figure = go.Figure(data=data, layout=layout)

    return figure
def update_figure(age, sex, chest_pain_type, resting_blood_pressure,
                  cholesterol, fasting_blood_sugar, rest_ecg,
                  max_heart_rate_achieved, exercise_induced_angina,
                  st_depression, st_slope, num_major_vessels, thalassemia):

    #	M = mm.MyModel()
    results = M.predict([
        age, sex, chest_pain_type, resting_blood_pressure, cholesterol,
        fasting_blood_sugar, rest_ecg, max_heart_rate_achieved,
        exercise_induced_angina, st_depression, st_slope, num_major_vessels,
        thalassemia
    ])

    nmlize = lambda x: x * 1000 if x < 1 else (x * 100 if x < 10 else x)

    your_data = [
        nmlize(e) for e in [
            age, chest_pain_type, resting_blood_pressure, cholesterol,
            fasting_blood_sugar, rest_ecg, max_heart_rate_achieved,
            exercise_induced_angina, st_depression, st_slope,
            num_major_vessels, thalassemia
        ]
    ]

    filter_tags = [e for e in df.columns if e not in ['sex', 'target']]

    new_df = df[(df['sex'] == 1.0)] if sex else df[(df['sex'] == 0.0)]

    avg = go.Barpolar(
        r=[df[tag].astype('float64').mean() for tag in filter_tags],
        text=filter_tags,
        name='Male\'s average' if sex else 'Female\'s average',
        marker=dict(color='rgb(106,81,163)'))
    yours = go.Barpolar(r=your_data,
                        text=filter_tags,
                        name='Your figure',
                        marker=dict(color='rgb(158,154,200)'))

    data = [avg, yours]
    layout = go.Layout(
        title='Your figure compairing with Male\' average'
        if sex else 'Your fingure compairing with Female\'s average',
        font=dict(size=16),
        legend=dict(font=dict(size=16)),
        radialaxis=dict(ticksuffix='%'),
        width=800,
        height=800,
        orientation=270)
    fig = go.Figure(data=data, layout=layout)

    prob = f'{int(100 * results[1])} percent possibility'
    res = '\t\tYou have heart disease.' if results[
        0] else '\t\tYou do not have heart disease.'

    return fig, res, prob
def highest_participants():
    participants = data.groupby(by=['Year', 'Sport']).size().groupby(
        level=0).nlargest(5).droplevel(0).to_frame().reset_index()
    years = ['Year ' + str(yr) for yr in participants['Year'].unique()]

    participants = participants.groupby(by='Year')

    colors = ['#004D40', '#00897B', '#4DB6AC', '#B2DFDB', '#E0F2F1']

    fig = go.Figure([
        go.Barpolar(r=participants.nth(i)[0],
                    name='',
                    text=participants.nth(i)['Sport'],
                    marker_color=colors[i],
                    theta=years) for i in range(4, -1, -1)
    ],
                    go.Layout(height=1000,
                              title='Top 5 popular sports in Olympic History',
                              polar_bgcolor='#212121',
                              paper_bgcolor='#212121',
                              font_size=15,
                              font_color='#FFFFFF',
                              polar=dict(radialaxis=dict(visible=False))))

    plt.plot(fig, filename='../plots/highest_participants.html')
Пример #4
0
def get_db_scatter_figure(df, db_scatter_x, db_scatter_y, db_scatter_c):

    if db_scatter_y == 'Cumulative exceedance':
        if 'Distance' in db_scatter_x:
            ranges = np.linspace(0, df[db_scatter_x].max(), 300)
            yvals = df.groupby(pd.cut(
                df[db_scatter_x], ranges)).count()['EarthquakeId'].cumsum()
        elif db_scatter_x == 'Number of records per event':
            ranges = np.linspace(0, df['EarthquakeId'].value_counts().max(),
                                 300)
            yvals = yvals = [(df['EarthquakeId'].value_counts() > val).sum()
                             for val in ranges]
        elif db_scatter_x == 'Number of records per station':
            ranges = np.linspace(0, df['StationID'].value_counts().max(), 300)
            yvals = yvals = [(df['StationID'].value_counts() > val).sum()
                             for val in ranges]
        fig = go.Figure(go.Scatter(x=ranges, y=yvals, mode='lines'))
        fig.update_layout(xaxis_title=db_scatter_x, yaxis_title=db_scatter_y)
    elif db_scatter_y == 'Count':
        if db_scatter_x == 'BackAzimuth':
            vals, centers = np.histogram(df[db_scatter_x])
            fig = go.Figure(go.Barpolar(r=vals, theta=centers))
            fig.update_layout(polar=dict(
                angularaxis=dict(rotation=90, direction='clockwise')))
        else:
            fig = px.histogram(df, x=db_scatter_x)
    else:
        fig = px.scatter(df,
                         x=db_scatter_x,
                         y=db_scatter_y,
                         color=db_scatter_c)
        fig.update_traces(
            marker=dict(size=10, line=dict(width=1, color='DarkSlateGrey')))
    return fig
Пример #5
0
def fan_chart(year, month):
    col = str(year)+'-'+str(month)
    y, m =year, month
    if ((year-2015)*12 + month - 7) < 0 or ((year-2015)*12 + month - 7) > max_time:
        y, m = 2015, 7
        col='2015-7'
    data2 = data.pivot_table(index='color_code', values = col, aggfunc=['sum','count'])
    data2.columns = data2.columns.droplevel(1)
    data2 = data2.reset_index()
    
    data2['avg']= data2['sum'] / data2['count']
    data2['proportion'] = data2['sum'] / data2['sum'].sum() * 360
    data2['color'] = ["rgb(0,112,189)","rgb(196,140,49)","rgb(0,134,89)","rgb(248,182,28)","rgb(227,44,0)","rgb(253,219,0)"]
    data2['name'] = route
    data2['theta'] = [ data2.iloc[:i+1,4].sum() - data2['proportion'][i]/2 for i in range(len(data2))]
    barpolar_plots = [go.Barpolar(r= [data2['avg'][i]], 
                                  width= data2['proportion'][i], 
                                  name = data2['name'][i], 
                                  marker_color = data2['color'][i], 
                                  theta=[data2['theta'][i]],
                                    hovertemplate = "載客量: %{r:.0f}人/站<br>占比: "+'{:.2f}%'.format(data2['proportion'][i]/3.6),
                                    opacity=0.85
                                    )
                      for i in range(len(data2))]
    
    layout = go.Layout(title =  str(y) + '年' + str(m) + "月 各線單站平均載客人數 和 占全系統流量比例",
                       title_font_size = 18,
                       margin = { 'b': 90, 'r': 30, 't': 60},
                       legend = {'x':0.9,'y':0.8},
                       polar = {'angularaxis':{'ticks':'', 'showticklabels':False, 'gridcolor':'#ddd'},
                                'radialaxis':{'gridcolor':'#ccc'}}
                       )
    return {'data': barpolar_plots, 'layout': layout}
Пример #6
0
def draw_barpolar(plot_data):
    fig = go.Figure()
    fig.add_trace(
        go.Barpolar(r=plot_data['r'],
                    width=plot_data['width'],
                    theta=plot_data['theta'],
                    marker=dict(color=plot_data['color'])))
    return fig
Пример #7
0
def createWindrose(year, values, color_z, color_w, color_o, width_received):
    trace1 = go.Barpolar(r=values[ZYMOTIC],
                         theta=year,
                         name=ZYMOTIC,
                         marker=dict(color=color_z,
                                     line=dict(width=width_received)))
    trace2 = go.Barpolar(r=values[WOUNDS],
                         theta=year,
                         name=WOUNDS,
                         marker=dict(color=color_w,
                                     line=dict(width=width_received)))
    trace3 = go.Barpolar(r=values[OTHERS],
                         theta=year,
                         name=OTHERS,
                         marker=dict(color=color_o,
                                     line=dict(width=width_received)))
    data = [trace3, trace2, trace1]
    return data
def update_radarplot(value):
    # value will be the zone
    df = xl.loc[xl["Zona"] == value]
    print(df)
    brs = [
        "pescoço", "ombro_d", "ombro_e", "cotovelo_d", "cotovelo_e", "mao_d",
        "mao_e", "toracica", "lombar"
    ]

    int_sup3, int_level1, int_level2, int_level3 = getIntensityBasedPain(df)
    print(int_sup3)
    r_level1 = [len(int_level1[tag]) for tag in brs]
    r_level2 = [len(int_level2[tag]) for tag in brs]
    r_level3 = [len(int_level3[tag]) for tag in brs]

    trace1 = go.Barpolar(r=r_level1,
                         text=brs,
                         name='[1-4]',
                         marker=dict(color='green'))
    trace2 = go.Barpolar(r=r_level2,
                         text=brs,
                         name='[5-6]',
                         marker=dict(color='yellow'))
    trace3 = go.Barpolar(r=r_level3,
                         text=brs,
                         name='[7-10]',
                         marker=dict(color='red'))
    layout = go.Layout(title='Frequency of pain for each body region',
                       font=dict(size=16),
                       legend=dict(font=dict(size=16)),
                       radialaxis=dict(ticksuffix='%'),
                       orientation=270)
    data = [trace1, trace2, trace3]
    fig = go.Figure(data=data, layout=layout)
    # r = np.array(SelectorGraph["zone"][value]["arr7"]["freq"]["y"])
    # theta = np.array(SelectorGraph["zone"][value]["arr7"]["freq"]["x"])
    # nr = np.delete(r, np.where(theta == "total")[0])
    # ntheta = np.delete(theta, np.where(theta == "total")[0])
    # graph = createRadar(nr, ntheta, value)
    # return {
    #     'data': graph
    # }
    return fig
Пример #9
0
def windrose(df):
    traces = []
    for lim, legend, color in zip(windlims, windlegends, windcolors):
        mini, maxi = lim
        r = [
            get_count(df[(df.windspeed < maxi) & (df.windspeed >= mini)], i)
            for i in range(8)
        ]
        traces.append(
            go.Barpolar(r=r, text=names, name=legend,
                        marker=dict(color=color)))
    layoutwind = go.Layout(polar={'angularaxis': {'rotation': 90}})
    return go.Figure(data=traces, layout=layoutwind)
Пример #10
0
def draw_barpolar(plot_data):
    fig = go.Figure()
    fig.add_trace(
        go.Barpolar(r=plot_data['r'],
                    width=plot_data['width'],
                    theta=plot_data['theta'],
                    marker=dict(color=plot_data['color'])))
    fig.update_layout(showlegend=False,
                      polar=dict(bgcolor="white",
                                 angularaxis=dict(visible=False, ),
                                 radialaxis=dict(visible=False)),
                      paper_bgcolor="white",
                      plot_bgcolor='white')
    return fig
Пример #11
0
def figCompassRose(df):
    '''
	df = [77.5, 72.5, 70.0, 45.0, 22.5, 42.5, 40.0, 62.5]
        fig = px.bar_polar(df, r="frequency", theta="direction",
              color="strength", template="plotly_dark",
              color_discrete_sequence= px.colors.sequential.Plasma_r)
        '''
    #print("df =", df)
    fig = go.Figure()
    fig.add_trace(
        go.Barpolar(r=df[5],
                    name='> ' + returnNumberConverted(11) + " " + WUnits(),
                    marker_color='rgb(40,0,163)'))
    fig.add_trace(
        go.Barpolar(r=df[4],
                    name=returnNumberConverted(8.5) + '-' +
                    returnNumberConverted(11) + " " + WUnits(),
                    marker_color='rgb(80,0,163)'))

    fig.add_trace(
        go.Barpolar(r=df[3],
                    name=returnNumberConverted(4.4) + '-' +
                    returnNumberConverted(8.5) + " " + WUnits(),
                    marker_color='rgb(120,0,163)'))
    fig.add_trace(
        go.Barpolar(r=df[2],
                    name=returnNumberConverted(2.2) + '-' +
                    returnNumberConverted(4.4) + " " + WUnits(),
                    marker_color='rgb(160,0,163)'))
    fig.add_trace(
        go.Barpolar(r=df[1],
                    name=returnNumberConverted(1.0) + '-' +
                    returnNumberConverted(2.3) + " " + WUnits(),
                    marker_color='rgb(200,0,163)'))
    fig.add_trace(
        go.Barpolar(r=df[0],
                    name=returnNumberConverted(0.0) + '-' +
                    returnNumberConverted(1) + " " + WUnits(),
                    marker_color='rgb(240,0,163)'))

    fig.update_traces(
        text=['North', 'N-E', 'East', 'S-E', 'South', 'S-W', 'West', 'N-W'])
    fig.update_layout(
        title='Wind Speed Distribution Past Week',
        #font_size=16,
        legend_font_size=16,
        #polar_radialaxis_ticksuffix='%',
        #polar_angularaxis_rotation=90,
        font=dict(size=16),
        polar=dict(
            radialaxis=dict(ticksuffix="%", angle=45, tickfont=dict(size=12)),
            angularaxis=dict(direction="clockwise", tickfont=dict(size=14)),
        ),
        #color_discrete_sequence= go.colors.sequential.Plasma_r,
        template='plotly_dark',
    )
    return fig
Пример #12
0
def get_rose_traces(d, traces, units, showlegend=False, lines=False):
    """
    Get all traces for a wind rose, given the data chunk.
    Month is used to tie the subplot to the formatting
    chunks in the multiple-subplot graph.
    """

    # Directly mutate the `traces` array.
    for sr, sr_info in luts.speed_ranges.items():
        if units in ["kts", "m/s"]:
            name = f"{luts.speed_units[units][sr]} {units}"
        else:
            name = sr + " mph"
        dcr = d.loc[(d["speed_range"] == sr)]
        r_list = dcr["frequency"].tolist()
        theta_list = list(pd.to_numeric(dcr["direction_class"]) * 10)
        props = dict(
            r=r_list,
            theta=theta_list,
            name=name,
            hovertemplate=
            "%{r} %{fullData.name} winds from %{theta}<extra></extra>",
            marker_color=sr_info["color"],
            showlegend=showlegend,
            legendgroup="legend",
        )
        if lines:
            props["mode"] = "lines"
            # append first item of each to close the lines
            props["r"].append(r_list[0])
            props["theta"].append(theta_list[0])
            props[
                "hovertemplate"] = "%{r:.2f}% change in %{fullData.name}<br>winds from %{theta}<extra></extra>"
            traces.append(go.Scatterpolar(props))
        else:
            traces.append(go.Barpolar(props))

    # Compute the maximum extent of any particular
    # petal on the wind rose.
    max_petal = d.groupby(["direction_class"]).sum().max()

    return max_petal
Пример #13
0
def create_polar_bar_chart(country_selections, polar_chart_time):
    dff = clean.country_limit_zero_remove(df, country_selections)
    num_data = polar_bar_chart.select_data_on_timesplit(
        dff, "DURATION", polar_chart_time)
    num_splits = len(num_data)
    increments = [(x + 1) * (360 / num_splits) for x in range(num_splits)]
    time_int = polar_chart_time.lower().capitalize()

    return ({
        'data': [
            go.Barpolar(
                r=num_data,
                theta=increments,
                text=[time_int + " " + str((x + 1)) for x in range(365)],
                hovertemplate='%{r:.2f} GB' + ', %{text}',
                marker_color=px.colors.sequential.deep,
            )
        ],
        'layout':
        go.Layout(title="Total Gigabytes of Data Used on Each {} of All Years".
                  format(time_int),
                  autosize=True)
    })
Пример #14
0
def update_polarc_gauge(json_data, n):
    # plotting with static value

    r_rand = np.random.uniform(2, 4)
    theta_rand = np.random.randint(0, 120)
    data = [
        go.Barpolar(r=[
            r_rand,
        ],
                    theta=[
                        theta_rand,
                    ],
                    width=[
                        30,
                    ],
                    marker_color=[
                        color_list[0],
                    ],
                    marker_line_color="black",
                    marker_line_width=2,
                    opacity=0.8)
    ]

    layout = go.Layout(font=dict(size=10, color=txt_color),
                       plot_bgcolor=bg_color,
                       paper_bgcolor=bg_color,
                       margin=dict(l=5, r=5, t=20, b=10),
                       polar=dict(
                           bgcolor='#9e9e9e',
                           radialaxis=dict(range=[0, 5]),
                       ),
                       radialaxis=dict(range=[0, 5], ))

    fig = go.Figure(data=data, layout=layout)
    return np.random.randint(70, 100), np.random.randint(
        40, 70), np.random.randint(80, 120), fig
# balance by balance_status
negative = df["balance"].loc[df["balance_status"] ==
                             "negative"].values.tolist()
low = df["balance"].loc[df["balance_status"] == "low"].values.tolist()
middle = df["balance"].loc[df["balance_status"] == "middle"].values.tolist()
high = df["balance"].loc[df["balance_status"] == "high"].values.tolist()

# Get the average by occupation in each balance category
job_balance = df.groupby(['job', 'balance_status'])['balance'].mean()

trace1 = go.Barpolar(r=[
    -199.0, -392.0, -209.0, -247.0, -233.0, -270.0, -271.0, 0, -276.0, -134.5
],
                     text=[
                         "blue-collar", "entrepreneur", "housemaid",
                         "management", "retired", "self-employed", "services",
                         "student", "technician", "unemployed"
                     ],
                     name='Negative Balance',
                     marker=dict(color='rgb(246, 46, 46)'))
trace2 = go.Barpolar(
    r=[319.5, 283.0, 212.0, 313.0, 409.0, 274.5, 308.5, 253.0, 316.0, 330.0],
    text=[
        "blue-collar", "entrepreneur", "housemaid", "management", "retired",
        "self-employed", "services", "student", "technician", "unemployed"
    ],
    name='Low Balance',
    marker=dict(color='rgb(246, 97, 46)'))
trace3 = go.Barpolar(r=[
    2128.5, 2686.0, 2290.0, 2366.0, 2579.0, 2293.5, 2005.5, 2488.0, 2362.0,
    1976.0
Пример #16
0
def create_polar(row):
    """
    Function to create the polar-bar chart_box

    Arguments:
        row: Selected row
    Returns:
        Figure object
    """
    #row=0
    fig = make_subplots(rows=1,cols=2,shared_yaxes= True,
                        specs=[[{'type': 'polar'}]*2],
                        subplot_titles=("Selected Record","Represented Class"))

    sample_df1 = df.iloc[row:row+1]
    sample_df2 = df_norm.iloc[row:row+1]
    target_class = sample_df1['target'].values[0]
    #print(target_class,target_options[target_class]['label'])
    filtered_df = df[df['target']==target_class]
    filtered_df2 = df_norm[df_norm['target']==target_class]
    category_avg = filtered_df2.mean(axis=0).tolist()
    category_avg = [ round(elem, 2) for elem in category_avg ]

    print(filtered_df)
    print(category_avg)
    [fig.add_trace(go.Barpolar(
                    r=list(sample_df2.loc[:,'sepal length':'petal width'].values)[0],
                    theta=[45,135,225,270],
                    #width=[15,15,15,15],
                    marker_color=["#E4FF87", '#70DDFF', '#709BFF', '#FFAA70'],
                    marker_line_color="black",
                    marker_line_width=2,
                    text = list(sample_df2.loc[:,'sepal length':'petal width'].columns),
                    hoverinfo = "text",
                    opacity=0.8
        ),row=1,col=1)]

    [fig.add_trace(go.Barpolar(

                    r=category_avg[0:4],
                    theta=[45,135,225,270],
                    #width=[15,15,15,15],
                    marker_color=["#E4FF87", '#70DDFF', '#709BFF', '#FFAA70'],
                    marker_line_color="black",
                    marker_line_width=2,
                    text = list(sample_df2.loc[:,'sepal length':'petal width'].columns),
                    hoverinfo = "text",
                    #hovertext = "text",
                    opacity=0.8
        ),row=1,col=2)]
    title = "Comparison of Record \""+str(row)+"\" Vs \"" + target_options[target_class]['label']+ "\" Average"
    fig.update_layout(title=title,
    template=None,
    paper_bgcolor='rgba(233,233,233,0)',
    plot_bgcolor='rgba(255,233,0,0)',
    height = 500,

    polar = dict(
    radialaxis = dict(range=[0, 7], showticklabels=False, ticks=''),
    angularaxis = dict(showticklabels=True, ticks=''),
    angularaxis_categoryarray = ["d", "a", "c", "b"]),

    polar2 = dict(
    radialaxis = dict(range=[0, 7], showticklabels=False, ticks=''),
    angularaxis = dict(showticklabels=True, ticks='')),
    showlegend=False
    )


    return fig
Пример #17
0
import plotly.graph_objs as go
from backend import server

app = dash.Dash(__name__,
                server=server,
                external_stylesheets=[dbc.themes.BOOTSTRAP],
                url_base_pathname='/app1/')
df = pd.read_csv('https://gist.githubusercontent.com/chriddyp/' +
                 '5d1ea79569ed194d432e56108a04d188/raw/' +
                 'a9f9e8076b837d541398e999dcbac2b2826a81f8/' +
                 'gdp-life-exp-2007.csv')

trace1 = go.Barpolar(
    r=[77.5, 72.5, 70.0, 45.0, 22.5, 42.5, 40.0, 62.5],
    # theta=theta,
    # width=width,
    text=['North', 'N-E', 'East', 'S-E', 'South', 'S-W', 'West', 'N-W'],
    name='11-14 m/s',
    marker=dict(color='rgb(106,81,163)'))
trace2 = go.Barpolar(
    r=[
        57.49999999999999, 50.0, 45.0, 35.0, 20.0, 22.5, 37.5,
        55.00000000000001
    ],
    text=['North', 'N-E', 'East', 'S-E', 'South', 'S-W', 'West', 'N-W'],
    name='8-11 m/s',
    marker=dict(color='rgb(158,154,200)'))
trace3 = go.Barpolar(
    r=[40.0, 30.0, 30.0, 35.0, 7.5, 7.5, 32.5, 40.0],
    text=['North', 'N-E', 'East', 'S-E', 'South', 'S-W', 'West', 'N-W'],
    name='5-8 m/s',
Пример #18
0
def update_rose_sxs(rose_dict, units):
    """
    Create side-by-side (sxs) plot of wind roses from different decades
    """
    # initialize figure (display blank fig even if insufficient data)
    # t = top margin in % of figure.
    subplot_spec = dict(type="polar", t=0.02)
    subplot_args = {
        "rows": 1,
        "cols": 2,
        "horizontal_spacing": 0.01,
        "specs": [[subplot_spec, subplot_spec]],
        "subplot_titles": ["", ""],
    }

    # defults for displaying figure regardless of data availability
    polar_props = dict(
        bgcolor="#fff",
        angularaxis=dict(
            tickmode="array",
            tickvals=[0, 45, 90, 135, 180, 225, 270, 315],
            ticktext=["N", "NE", "E", "SE", "S", "SW", "W", "NW"],
            tickfont=dict(color="#444", size=14),
            showticksuffix="last",
            showline=False,  # no boundary circles
            color="#888",  # set most colors to #888
            gridcolor="#efefef",
            rotation=90,  # align compass to north
            direction="clockwise",  # degrees go clockwise
        ),
        radialaxis=dict(
            color="#888",
            gridcolor="#efefef",
            tickangle=0,
            range=[0, 5],
            tick0=1,
            showticklabels=False,
            ticksuffix="%",
            showticksuffix="last",
            showline=False,  # hide the dark axis line
            tickfont=dict(color="#444"),
        ),
    )

    station_name = luts.map_data.loc[rose_dict["sid"]]["real_name"]

    rose_layout = {
        "title":
        dict(
            text="Historical wind comparison, " + station_name,
            font=dict(family="Open Sans", size=18),
            x=0.5,
        ),
        "margin":
        dict(l=0, t=100, r=0, b=20),
        "font":
        dict(family="Open Sans", size=14),
        "legend": {
            "orientation": "h",
            "x": -0.05,
            "y": 1
        },
        "height":
        650,
        "paper_bgcolor":
        luts.background_color,
        "plot_bgcolor":
        luts.background_color,
        # We need to explicitly define the rotations
        # we need for each named subplot.
        "polar1": {
            **polar_props,
            **{
                "hole": 0.1
            }
        },
        "polar2": {
            **polar_props,
            **{
                "hole": 0.1
            }
        },
    }

    if "trace_dict" in rose_dict:
        # this handles case of insufficient data for station
        # trace_dict only present if insufficient data for comparison
        empty_trace = go.Barpolar(rose_dict["trace_dict"])

        return make_empty_sxs_rose(empty_trace, subplot_args, rose_layout,
                                   rose_dict)

    subplot_args["subplot_titles"] = rose_dict["target_decades"]
    fig = make_subplots(**subplot_args)

    data_list = [pd.DataFrame(df_dict) for df_dict in rose_dict["data_list"]]
    max_axes = pd.DataFrame()
    for df, show_legend, i in zip(data_list, [True, False], [1, 2]):
        traces = []
        max_axes = max_axes.append(get_rose_traces(df, traces, units,
                                                   show_legend),
                                   ignore_index=True)
        _ = [fig.add_trace(trace, row=1, col=i) for trace in traces]

    # Determine maximum r-axis and r-step.
    # Adding one and using floor(/2.5) was the
    # result of experimenting with values that yielded
    # about 3 steps in most cases, with a little headroom
    # for the r-axis outer ring.
    rmax = max_axes["frequency"].max() + 1
    polar_props["radialaxis"]["range"][1] = rmax
    polar_props["radialaxis"]["dtick"] = math.floor(rmax / 2.5)
    polar_props["radialaxis"]["showticklabels"] = True

    # Apply formatting to subplot titles,
    # which are actually annotations.
    for i in fig["layout"]["annotations"]:
        i["y"] = i["y"] + 0.05
        i["font"] = dict(size=14, color="#444")
        i["text"] = "<b>" + i["text"] + "</b>"

    station_calms = pd.DataFrame(rose_dict["calms_dict"])
    rose_layout["polar1"]["hole"] = station_calms.iloc[0]["percent"]
    rose_layout["polar2"]["hole"] = station_calms.iloc[1]["percent"]

    # Get calms as annotations, then merge
    # them into the subgraph title annotations
    fig["layout"]["annotations"] = fig["layout"][
        "annotations"] + get_rose_calm_sxs_annotations(
            fig["layout"]["annotations"], station_calms)

    fig.update_layout(**rose_layout)

    return fig
Пример #19
0
def mohs():
    mohs_choice = request.form['mohs']
    if mohs_choice == 'soft':
        soft_gem_lst = get_soft_gem()
        xvals = [gem[0] for gem in soft_gem_lst]
        yvals = [gem[1] for gem in soft_gem_lst]

        fig = go.Figure(go.Bar(x=xvals, y=yvals, width=0.5))
        fig.update_traces(marker_color=["#ff9900","#ca431d","#ca431d",\
                         "#ca431d","#8b104e","#8b104e","#8b104e","#8b104e",\
                         "#520556","#520556","#520556","#520556","#520556",\
                         "#330336","#330336"])
        fig.update_yaxes(range=[0, 10])
        fig.update_layout(title="Top 15 Softest Gemstones")
        div = fig.to_html(full_html=False)
        #soft polar
        fig2 = go.Figure(go.Barpolar(
            r=[gem[1] for gem in soft_gem_lst],
            text=[gem[0] for gem in soft_gem_lst],
            #theta=[65, 15, 210, 110, 312.5, 180, 270],
            width=[10,10,10,10,10,10,10,10,10,10,10,10,10,10,10],
            ids=[gem[0] for gem in soft_gem_lst],
            marker_color=["#ff9900","#ca431d","#ca431d","#ca431d","#8b104e",\
                          "#8b104e","#8b104e","#8b104e","#520556","#520556",\
                          "#520556","#520556","#520556","#330336","#330336"],
            #marker_line_color="#30475e",
            #marker_line_width=2,
            opacity=0.95
        ))
        fig2.update_layout(
            template=None,
            title='Top 15 Softest Gemstones',
            font_size=16,
            polar=dict(radialaxis=dict(range=[0, 10],
                                       showticklabels=False,
                                       ticks=''),
                       #angularaxis = dict(showticklabels=False, ticks=''),
                       ))
        div2 = fig2.to_html(full_html=False)
        return render_template("mohs.html", plot_div1=div, plot_div2=div2)
    if mohs_choice == 'hard':
        hard_gem_lst = get_hard_gem()
        xvals = [gem[0] for gem in hard_gem_lst]
        yvals = [gem[1] for gem in hard_gem_lst]

        fig = go.Figure(go.Bar(x=xvals, y=yvals, width=0.5))
        fig.update_traces(marker_color=["#f67280","#c06c84","#c06c84",\
                          "#c06c84","#6c5b7b","#6c5b7b","#6c5b7b","#6c5b7b",\
                          "#6c5b7b","#355c7d","#355c7d","#355c7d","#213a4f",\
                          "#213a4f","#213a4f","#213a4f"])
        fig.update_layout(title="Top 15 Hardest Gemstones")
        div = fig.to_html(full_html=False)

        fig2 = go.Figure(go.Barpolar(
            r=[gem[1] for gem in hard_gem_lst],
            text=[gem[0] for gem in hard_gem_lst],
            #theta=[65, 15, 210, 110, 312.5, 180, 270],
            width=[10,10,10,10,10,10,10,10,10,10,10,10,10,10,10],
            ids=[gem[0] for gem in hard_gem_lst],
            marker_color=["#f67280","#c06c84","#c06c84","#c06c84","#6c5b7b",\
                           "#6c5b7b","#6c5b7b","#6c5b7b","#6c5b7b","#6c5b7b",\
                           "#355c7d","#355c7d","#355c7d","#213a4f","#213a4f","#213a4f"],
            #marker_line_color="#30475e",
            #marker_line_width=2,
            opacity=0.95
        ))
        fig2.update_layout(
            template=None,
            title='Top 15 Hardest Gemstones',
            font_size=16,
            polar=dict(radialaxis=dict(range=[0, 10],
                                       showticklabels=False,
                                       ticks=''),
                       #angularaxis = dict(showticklabels=False, ticks=''),
                       ))
        div2 = fig2.to_html(full_html=False)
        return render_template("mohs.html", plot_div1=div, plot_div2=div2)
    else:
        command = f'''SELECT Name, Mohs
                   FROM Gems AS b
                   ORDER BY Mohs ASC
                    '''
        mohs_lst = connection(command)
        fig = go.Figure(
            data=go.Scatter(x=[gem[0] for gem in mohs_lst],
                            y=[gem[1] for gem in mohs_lst],
                            mode='markers',
                            marker=dict(size=[gem[1] * 10 for gem in mohs_lst],
                                        color=[gem[1] for gem in mohs_lst])))
        div = fig.to_html(full_html=False)
        div2 = 'Comparison of the Mohs Hardness of All Gemstones'
        return render_template("mohs.html", plot_div1=div, plot_div2=div2)
Пример #20
0
    def processAlgorithm(self, parameters, context, feedback):

        try:
            import pandas as pd
            import numpy as np
            import plotly.graph_objs as go
            import chart_studio.plotly as py
        except Exception:
            feedback.reportError(QCoreApplication.translate('Error','%s'%(e)))
            feedback.reportError(QCoreApplication.translate('Error',' '))
            feedback.reportError(QCoreApplication.translate('Error','Error loading modules - please install the necessary dependencies'))
            return {}

        FN = self.parameterAsLayer(parameters, self.FN, context)
        WF = self.parameterAsString(parameters, self.Weight, context)
        G = self.parameterAsString(parameters, self.Group, context)
        bins = parameters[self.Bins]
        SR = parameters[self.SR]
        P = parameters[self.P]
        R = parameters[self.R]

        feedback.pushInfo(QCoreApplication.translate('RoseDiagram','Reading Data'))

        data = {}

        features = FN.selectedFeatures()
        total = FN.selectedFeatureCount()
        if len(features) == 0:
            features = FN.getFeatures()
            total = FN.featureCount()

        total = 100.0/total
        for enum,feature in enumerate(features):
            if total > 0:
                feedback.setProgress(int(enum*total))
            if G:
                ID = feature[G]
            else:
                ID = 0
            if WF:
                W = feature[WF]
                if type(W) == int or type(W) == float:
                    pass
                else:
                    feedback.reportError(QCoreApplication.translate('Error','Weight field contains non numeric values - check for null values'))
                    return {}
            else:
                W = 1

            geom = feature.geometry()
            v = geom.length()
            if QgsWkbTypes.isSingleType(geom.wkbType()):
                geom = [geom.asPolyline()]
            else:
                geom = geom.asMultiPolyline()

            if len(geom) == 0:
                feedback.reportError(QCoreApplication.translate('Error','Warning - skipping null geometry linestring.'))
                continue

            x,y = 0,0
            for part in geom:
                startx = None
                for point in part:
                    if startx == None:
                        startx,starty = point
                        continue
                    endx,endy=point

                    dx = endx - startx
                    dy =  endy - starty

                    l = math.sqrt((dx**2)+(dy**2))
                    angle = math.degrees(math.atan2(dy,dx))
                    x += math.cos(math.radians(angle)) * l
                    y += math.sin(math.radians(angle)) * l

                    startx,starty = endx,endy

           # mean = 90 - np.around(math.degrees(math.atan2(y, x)), decimals=4)
           # if mean > 180:
           #     mean -= 180
           # elif mean < 0:
           #     mean += 180

            mean = np.around(math.degrees(math.atan2(y, x)), decimals=4) #Simplified angle calculation
            mean = mean%360
            if mean > 180:
                mean -= 180

            if ID in data:
                data[ID].append((mean,W))
            else:
                data[ID] = [(mean,W)]

        feedback.pushInfo(QCoreApplication.translate('RoseDiagram','Plotting Data'))

        values = []

        bins = float(bins)
        final = []
        values = []

        for k,v in data.items():

            counts = dict.fromkeys(np.arange(bins,360+bins,bins),0)

            num_values = []

            for num in v: #Get the reciprocal of the angle
                if num[0] == 0.0 or num[0] == 180.0:
                    num1 = 0.001
                else:
                    num1 = num[0]
                if num1 <= 180:
                    num2 = num1 + 180
                else:
                    num2 = num1 - 180

                k1 = int(math.ceil(num1 / bins)) * bins
                counts[k1] += num[1]  # Length weighted polar plot
                if R:
                    k2 = int(math.ceil(num2 / bins)) * bins
                    counts[k2] += num[1]

            count = list(counts.values())
            if SR:
                count = [math.sqrt(c) for c in count]

            if P:
                total = float(sum(count))
                count = [(c/total)*100 for c in count]

            binsV = [k - (bins/2.0) for k in counts.keys()]

            bars = go.Barpolar(r=count,theta=binsV,name=k)

            final.append(bars)

        ngtPath = 'https://raw.githubusercontent.com/BjornNyberg/NetworkGT/master/Images/NetworkGT_Logo1.png'
        if R:
            layout = go.Layout(
                images=[dict(source=ngtPath, xref="paper", yref="paper", x=0.85, y=0.05, sizex=0.2, sizey=0.2,
                             xanchor="right", yanchor="bottom")],
                title='Weighted Rose Diagram', font=dict(size=16), legend=dict(font=dict(size=16)),
                polar=dict(angularaxis=dict(direction="clockwise", tickfont=dict(size=14)), ), )
        else:
            layout = go.Layout(
                    images=[dict(source=ngtPath,xref="paper", yref="paper", x=0.85, y=0.05,sizex=0.2, sizey=0.2, xanchor="right", yanchor="bottom")],
                    title='Weighted Rose Diagram',font=dict(size=16),legend=dict(font=dict(size=16)),
                    polar=dict(angularaxis=dict(direction="clockwise",tickfont=dict(size=14)),sector = [-90,90]),)
            
        fig = go.Figure(final, layout=layout)
        try:
            py.plot(fig, filename='Rose Diagram', auto_open=True)
        except Exception as e:
            fig.show()

        return {}
Пример #21
0
def create_wx_figs(time: str, sid: str):
    start, now = helpers.get_time_range(time)
    client = MongoClient(os.environ["MONGODB_CLIENT"])
    db = client.wx
    df_wx_raw = pd.DataFrame(
        list(
            db.raw.find({
                "station_id": sid,
                "obs_time_utc": {
                    "$gt": start,
                    "$lte": now
                },
            }).sort([("obs_time_utc", -1)])))
    client.close()
    df_wx_raw.index = df_wx_raw["obs_time_local"]
    # df_wx_raw = df_wx_raw.tz_localize('UTC').tz_convert('US/Central')

    for col in df_wx_raw.columns:
        try:
            df_wx_raw.loc[df_wx_raw[col] < -50, col] = pd.np.nan
        except Exception:
            pass

    df_wx_raw["cloudbase"] = (
        (df_wx_raw["temp_f"] - df_wx_raw["dewpt_f"]) / 4.4) * 1000 + 50
    df_wx_raw.loc[df_wx_raw["pressure_in"] < 0, "pressure_in"] = pd.np.nan

    # df_wx_raw2 = df_wx_raw.resample('5T').mean().interpolate()
    # df_wx_raw2['dat'] = df_wx_raw2.index
    # df_wx_raw2['temp_delta'] = df_wx_raw2.temp_f.diff()
    # df_wx_raw2['precip_today_delta'] = df_wx_raw2.precip_total.diff()
    # df_wx_raw2.loc[df_wx_raw2['precip_today_delta'] < 0, 'precip_today_delta'] = 0
    # df_wx_raw2['precip_cum_in'] = df_wx_raw2.precip_today_delta.cumsum()
    # df_wx_raw2['pres_delta'] = df_wx_raw2.pressure_in.diff()
    # df_wx_raw2['dat_delta'] = df_wx_raw2.dat.diff().dt.seconds / 360
    # df_wx_raw2['dTdt'] = df_wx_raw2['temp_delta'] / df_wx_raw2['dat_delta']
    # df_wx_raw2['dPdt'] = df_wx_raw2['pres_delta'] / df_wx_raw2['dat_delta']
    # df_wx_raw3 = df_wx_raw2.drop(columns=['dat'])
    # df_wx_raw3 = df_wx_raw3.rolling(20*3).mean().add_suffix('_roll')
    # df_wx_raw = df_wx_raw2.join(df_wx_raw3)

    df_wx_raw["dat"] = df_wx_raw.index
    df_wx_raw.sort_values(by="dat", inplace=True)
    df_wx_raw["temp_delta"] = df_wx_raw.temp_f.diff()
    df_wx_raw["precip_today_delta"] = df_wx_raw.precip_total.diff()
    df_wx_raw.loc[df_wx_raw["precip_today_delta"] < 0,
                  "precip_today_delta"] = 0
    df_wx_raw["precip_cum_in"] = df_wx_raw.precip_today_delta.cumsum()
    df_wx_raw["pres_delta"] = df_wx_raw.pressure_in.diff()
    df_wx_raw["dat_delta"] = df_wx_raw.dat.diff().dt.seconds / 360
    df_wx_raw["dTdt"] = df_wx_raw["temp_delta"] / df_wx_raw["dat_delta"]
    df_wx_raw["dPdt"] = df_wx_raw["pres_delta"] / df_wx_raw["dat_delta"]

    df_wx_raw["date"] = df_wx_raw.index.date
    df_wx_raw["hour"] = df_wx_raw.index.hour

    df_wx_raw.loc[df_wx_raw["wind_speed_mph"] == 0, "wind_cat"] = "calm"
    df_wx_raw.loc[df_wx_raw["wind_speed_mph"] > 0, "wind_cat"] = "0-1"
    df_wx_raw.loc[df_wx_raw["wind_speed_mph"] > 1, "wind_cat"] = "1-2"
    df_wx_raw.loc[df_wx_raw["wind_speed_mph"] > 2, "wind_cat"] = "2-5"
    df_wx_raw.loc[df_wx_raw["wind_speed_mph"] > 5, "wind_cat"] = "5-10"
    df_wx_raw.loc[df_wx_raw["wind_speed_mph"] > 10, "wind_cat"] = ">10"

    df_wx_raw["wind_deg_cat"] = np.floor(df_wx_raw["wind_deg"] / 15) * 15
    df_wx_raw.loc[df_wx_raw["wind_deg_cat"] == 360, "wind_deg_cat"] = 0
    df_wx_raw["wind_deg_cat"] = (
        df_wx_raw["wind_deg_cat"].fillna(0).astype(int).astype(str))

    df_wx_raw.loc[df_wx_raw["wind_speed_mph"] == 0, "wind_deg"] = pd.np.nan

    wind = df_wx_raw[["wind_cat", "wind_deg_cat"]]
    wind.loc[:, "count"] = 1
    # wind['count'] = 1
    ct = len(wind)
    wind = pd.pivot_table(
        wind,
        values="count",
        index=["wind_deg_cat"],
        columns=["wind_cat"],
        aggfunc=np.sum,
    )
    ix = np.arange(0, 360, 5)
    col = ["calm", "0-1", "1-2", "2-5", "5-10", ">10"]
    wind_temp = pd.DataFrame(data=0, index=ix, columns=col)
    for i in ix:
        for j in col:
            try:
                wind_temp.loc[i, j] = wind.loc[str(i), j]
            except Exception:
                pass
    wind_temp = wind_temp.fillna(0)
    wind_temp["calm"] = wind_temp["calm"].mean()
    for col in range(len(wind_temp.columns)):
        try:
            wind_temp.iloc[:, col] = (wind_temp.iloc[:, col] +
                                      wind_temp.iloc[:, col - 1])
        except Exception:
            pass
    wind_temp = np.round(wind_temp / ct * 100, 2)
    wind_temp["wind_cat"] = wind_temp.index

    dt_min = df_wx_raw.index.min()
    dt_max = df_wx_raw.index.max()

    td_max = (max(
        df_wx_raw["temp_f"].max(),
        df_wx_raw["dewpt_f"].max(),
        df_wx_raw["heat_index_f"].max(),
        df_wx_raw["windchill_f"].max(),
    ) + 1)
    td_min = (min(
        df_wx_raw["temp_f"].min(),
        df_wx_raw["dewpt_f"].min(),
        df_wx_raw["heat_index_f"].min(),
        df_wx_raw["windchill_f"].min(),
    ) - 1)

    df_wx_raw.loc[df_wx_raw["heat_index_f"] == df_wx_raw["temp_f"],
                  "heat_index_f"] = pd.np.nan
    df_wx_raw.loc[df_wx_raw["windchill_f"] == df_wx_raw["temp_f"],
                  "windchill_f"] = pd.np.nan

    data_td = [
        go.Scatter(
            x=df_wx_raw.index,
            y=df_wx_raw["temp_f"],
            name="Temperature (F)",
            line=dict(
                color="rgb(255, 95, 63)",
                width=3,
                shape="spline",
                smoothing=0.3,
            ),
            xaxis="x",
            yaxis="y",
            mode="lines",
        ),
        go.Scatter(
            x=df_wx_raw.index,
            y=df_wx_raw["heat_index_f"],
            name="Heat Index (F)",
            line=dict(color="#F42ED0", width=3, shape="spline", smoothing=0.3),
            xaxis="x",
            yaxis="y",
            mode="lines",
        ),
        go.Scatter(
            x=df_wx_raw.index,
            y=df_wx_raw["windchill_f"],
            name="Windchill (F)",
            line=dict(color="#2EE8F4", width=3, shape="spline", smoothing=0.3),
            xaxis="x",
            yaxis="y",
            mode="lines",
        ),
        go.Scatter(
            x=df_wx_raw.index,
            y=df_wx_raw["dewpt_f"],
            name="Dewpoint (F)",
            line=dict(
                color="rgb(63, 127, 255)",
                width=3,
                shape="spline",
                smoothing=0.3,
            ),
            xaxis="x",
            yaxis="y2",
            mode="lines",
        ),
    ]

    layout_td = go.Layout(
        autosize=True,
        font=dict(family="Roboto Mono"),
        hoverlabel=dict(font=dict(family="Roboto Mono")),
        height=200,
        yaxis=dict(
            domain=[0.02, 0.98],
            title="Temperature (F)",
            range=[td_min, td_max],
            fixedrange=True,
            titlefont=dict(family="Roboto Mono", color="rgb(255, 95, 63)"),
        ),
        yaxis2=dict(
            domain=[0.02, 0.98],
            title="Dewpoint (F)",
            overlaying="y",
            side="right",
            range=[td_min, td_max],
            fixedrange=True,
            titlefont=dict(family="Roboto Mono", color="rgb(63, 127, 255)"),
        ),
        xaxis=dict(
            type="date",
            # fixedrange=True,
            range=[dt_min, dt_max],
        ),
        margin=dict(r=50, t=30, b=30, l=60, pad=0),
        showlegend=False,
    )

    data_pr = [
        go.Scatter(
            x=df_wx_raw.index,
            y=df_wx_raw["pressure_in"],
            name="Pressure (inHg)",
            line=dict(
                color="rgb(255, 127, 63)",
                width=3,
                shape="spline",
                smoothing=0.3,
            ),
            xaxis="x",
            yaxis="y",
            mode="lines",
        ),
        go.Scatter(
            x=df_wx_raw.index,
            y=df_wx_raw["humidity"],
            name="Humidity (%)",
            line=dict(
                color="rgb(127, 255, 63)",
                width=3,
                shape="spline",
                smoothing=0.3,
            ),
            xaxis="x",
            yaxis="y2",
            mode="lines",
        ),
    ]

    layout_pr = go.Layout(
        autosize=True,
        height=200,
        font=dict(family="Roboto Mono"),
        hoverlabel=dict(font=dict(family="Roboto Mono")),
        yaxis=dict(
            domain=[0.02, 0.98],
            title="Pressure (inHg)",
            # range=[0,120],
            fixedrange=True,
            titlefont=dict(family="Roboto Mono", color="rgb(255, 127, 63)"),
        ),
        yaxis2=dict(
            domain=[0.02, 0.98],
            title="Humidity (%)",
            overlaying="y",
            side="right",
            # range=[0,120],
            fixedrange=True,
            titlefont=dict(family="Roboto Mono", color="rgb(127, 255, 63)"),
        ),
        xaxis=dict(
            type="date",
            # fixedrange=True,
            range=[dt_min, dt_max],
        ),
        margin=dict(r=50, t=30, b=30, l=60, pad=0),
        showlegend=False,
    )

    data_pc = [
        go.Scatter(
            x=df_wx_raw.index,
            y=df_wx_raw["precip_rate"],
            name="Precip (in/hr)",
            line=dict(
                color="rgb(31, 190, 255)",
                width=3,
                shape="spline",
                smoothing=0.3,
            ),
            xaxis="x",
            yaxis="y",
            mode="lines",
        ),
        go.Scatter(
            x=df_wx_raw.index,
            y=df_wx_raw["precip_cum_in"],
            name="Precip Cumulative (in)",
            line=dict(
                color="rgb(63, 255, 255)",
                width=3,
                shape="spline",
                smoothing=0.3,
            ),
            xaxis="x",
            yaxis="y2",
            mode="lines",
        ),
    ]

    layout_pc = go.Layout(
        autosize=True,
        height=200,
        font=dict(family="Roboto Mono"),
        hoverlabel=dict(font=dict(family="Roboto Mono")),
        yaxis=dict(
            domain=[0.02, 0.98],
            title="Precip (in/hr)",
            # range=[0,120],
            fixedrange=True,
            titlefont=dict(family="Roboto Mono", color="rgb(31, 190, 255)"),
        ),
        yaxis2=dict(
            domain=[0.02, 0.98],
            title="Precip Cumulative (in)",
            overlaying="y",
            side="right",
            # range=[0,120],
            fixedrange=True,
            titlefont=dict(family="Roboto Mono", color="rgb(63, 255, 255)"),
        ),
        xaxis=dict(
            type="date",
            # fixedrange=True,
            range=[dt_min, dt_max],
        ),
        margin=dict(r=50, t=30, b=30, l=60, pad=0),
        showlegend=False,
    )

    data_cb = [
        go.Scatter(
            x=df_wx_raw.index,
            y=df_wx_raw["cloudbase"],
            name="Minimum Cloudbase (ft)",
            line=dict(
                color="rgb(90, 66, 245)",
                width=3,
                shape="spline",
                smoothing=0.3,
            ),
            xaxis="x",
            yaxis="y",
            mode="lines",
        ),
    ]

    layout_cb = go.Layout(
        autosize=True,
        height=200,
        font=dict(family="Roboto Mono"),
        hoverlabel=dict(font=dict(family="Roboto Mono")),
        yaxis=dict(
            domain=[0.02, 0.98],
            title="Minimum Cloudbase (ft)",
            # range=[0,120],
            fixedrange=True,
            titlefont=dict(family="Roboto Mono", color="rgb(90, 66, 245)"),
        ),
        xaxis=dict(
            type="date",
            # fixedrange=True,
            range=[dt_min, dt_max],
        ),
        margin=dict(r=50, t=30, b=30, l=60, pad=0),
        showlegend=False,
    )

    data_wd = [
        go.Scatter(
            x=df_wx_raw.index,
            y=df_wx_raw["wind_deg"],
            name="Wind Direction (degrees)",
            marker=dict(color="rgb(190, 63, 255)", size=8, symbol="x"),
            xaxis="x",
            yaxis="y",
            mode="markers",
        ),
        go.Scatter(
            x=df_wx_raw.index,
            y=df_wx_raw["wind_gust_mph"] * 0.869,
            name="Wind Gust (kts)",
            line=dict(
                color="rgb(31, 190, 15)",
                width=3,
                shape="spline",
                smoothing=0.3,
            ),
            xaxis="x",
            yaxis="y2",
            mode="lines",
        ),
        go.Scatter(
            x=df_wx_raw.index,
            y=df_wx_raw["wind_speed_mph"] * 0.869,
            name="Wind Speed (kts)",
            line=dict(
                color="rgb(127, 255, 31)",
                width=3,
                shape="spline",
                smoothing=0.3,
            ),
            xaxis="x",
            yaxis="y2",
            mode="lines",
        ),
    ]

    layout_wd = go.Layout(
        autosize=True,
        height=200,
        font=dict(family="Roboto Mono"),
        hoverlabel=dict(font=dict(family="Roboto Mono")),
        yaxis=dict(
            domain=[0.02, 0.98],
            title="Wind Direction (degrees)",
            range=[0, 360],
            fixedrange=True,
            titlefont=dict(family="Roboto Mono", color="rgb(190, 63, 255)"),
        ),
        yaxis2=dict(
            domain=[0.02, 0.98],
            title="Wind Speed / Gust (kts)",
            overlaying="y",
            side="right",
            range=[0, df_wx_raw["wind_gust_mph"].max() * 0.869],
            fixedrange=True,
            titlefont=dict(family="Roboto Mono", color="rgb(127, 255, 31)"),
        ),
        xaxis=dict(
            type="date",
            # fixedrange=True,
            range=[dt_min, dt_max],
        ),
        margin=dict(r=50, t=30, b=30, l=60, pad=0),
        showlegend=False,
    )

    data_su = [
        go.Scatter(
            x=df_wx_raw.index,
            y=df_wx_raw["solar"],
            name="Solar Radiation (W/m<sup>2</sup>)",
            line=dict(
                color="rgb(255, 63, 127)",
                width=3,
                shape="spline",
                smoothing=0.3,
            ),
            xaxis="x",
            yaxis="y",
            mode="lines",
        ),
        go.Scatter(
            x=df_wx_raw.index,
            y=df_wx_raw["uv"],
            name="UV",
            line=dict(
                color="rgb(255, 190, 63)",
                width=3,
                shape="spline",
                smoothing=0.3,
            ),
            xaxis="x",
            yaxis="y2",
            mode="lines",
        ),
    ]

    layout_su = go.Layout(
        autosize=True,
        height=200,
        font=dict(family="Roboto Mono"),
        hoverlabel=dict(font=dict(family="Roboto Mono")),
        yaxis=dict(
            domain=[0.02, 0.98],
            title="Solar Radiation (W/m<sup>2</sup>)",
            # range=[0,120],
            fixedrange=True,
            titlefont=dict(family="Roboto Mono", color="rgb(255, 63, 127)"),
        ),
        yaxis2=dict(
            domain=[0.02, 0.98],
            title="UV",
            overlaying="y",
            side="right",
            # range=[0,120],
            fixedrange=True,
            titlefont=dict(family="Roboto Mono", color="rgb(255, 190, 63)"),
        ),
        xaxis=dict(
            type="date",
            # fixedrange=True,
            range=[dt_min, dt_max],
        ),
        margin=dict(r=50, t=30, b=30, l=60, pad=0),
        showlegend=False,
    )

    t1 = go.Barpolar(
        r=wind_temp[">10"],
        theta=wind_temp["wind_cat"],
        name=">10 mph",
        width=10,
        base=0,
        marker=dict(color="#ffff00", line=dict(color="#ffff00")),
    )
    t2 = go.Barpolar(
        r=wind_temp["5-10"],
        theta=wind_temp["wind_cat"],
        name="5-10 mph",
        width=10,
        base=0,
        marker=dict(color="#ffcc00", line=dict(color="#ffcc00")),
    )
    t3 = go.Barpolar(
        r=wind_temp["2-5"],
        theta=wind_temp["wind_cat"],
        name="2-5 mph",
        width=10,
        base=0,
        marker=dict(color="#bfff00", line=dict(color="#bfff00")),
    )
    t4 = go.Barpolar(
        r=wind_temp["1-2"],
        theta=wind_temp["wind_cat"],
        name="1-2 mph",
        width=10,
        base=0,
        marker=dict(color="#00cc00", line=dict(color="#00cc00")),
    )
    t5 = go.Barpolar(
        r=wind_temp["0-1"],
        theta=wind_temp["wind_cat"],
        name="0-1 mph",
        width=10,
        base=0,
        marker=dict(color="#009999", line=dict(color="#009999")),
    )
    t6 = go.Barpolar(
        r=wind_temp["calm"],
        theta=wind_temp["wind_cat"],
        name="calm",
        width=10,
        base=0,
        marker=dict(color="#3366ff", line=dict(color="#3366ff")),
    )

    data_wr = [t1, t2, t3, t4, t5, t6]

    layout_wr = go.Layout(
        font=dict(family="Roboto Mono"),
        hoverlabel=dict(font=dict(family="Roboto Mono")),
        polar=dict(
            radialaxis=dict(
                # visible = False,
                showline=False,
                showticklabels=False,
                ticks="",
                range=[0, wind_temp[">10"].max()],
            ),
            angularaxis=dict(
                rotation=90,
                direction="clockwise",
            ),
        ),
    )

    graphJSON_td = json.dumps(
        dict(data=data_td, layout=layout_td),
        cls=plotly.utils.PlotlyJSONEncoder,
    )

    graphJSON_pr = json.dumps(
        dict(data=data_pr, layout=layout_pr),
        cls=plotly.utils.PlotlyJSONEncoder,
    )

    graphJSON_pc = json.dumps(
        dict(data=data_pc, layout=layout_pc),
        cls=plotly.utils.PlotlyJSONEncoder,
    )

    graphJSON_cb = json.dumps(
        dict(data=data_cb, layout=layout_cb),
        cls=plotly.utils.PlotlyJSONEncoder,
    )

    graphJSON_wd = json.dumps(
        dict(data=data_wd, layout=layout_wd),
        cls=plotly.utils.PlotlyJSONEncoder,
    )

    graphJSON_su = json.dumps(
        dict(data=data_su, layout=layout_su),
        cls=plotly.utils.PlotlyJSONEncoder,
    )

    graphJSON_wr = json.dumps(
        dict(data=data_wr, layout=layout_wr),
        cls=plotly.utils.PlotlyJSONEncoder,
    )

    graphJSON_thp = helpers.create_3d_plot(
        df_wx_raw,
        "temp_f",
        "dewpt_f",
        "humidity",
        config.cs_normal,
        "Temperature (F)",
        "Dewpoint (F)",
        "Humidity (%)",
        "rgb(255, 95, 63)",
        "rgb(255, 127, 63)",
        "rgb(63, 127, 255)",
    )

    freq = "1T"
    mult = 2
    try:
        df_wx_lt = pd.DataFrame(
            list(
                db.lightning.find({
                    "timestamp": {
                        "$gt": start,
                        "$lte": now
                    },
                }).sort([("timestamp", -1)])))
        client.close()
        # df_wx_lt = df_wx_lt[df_wx_lt["energy"] > 0]
        df_wx_lt["distance"] = 0.621 * df_wx_lt["distance"]
        df_wx_lt["distance"] = np.round(df_wx_lt["distance"] / mult, 0) * mult
        df_wx_lt = df_wx_lt.drop(columns=["_id", "type", "energy"])
        df_pivot = df_wx_lt.pivot_table(index="timestamp",
                                        columns="distance",
                                        aggfunc=len).fillna(0)
        df_pivot = df_pivot.resample(freq, base=dt_min.minute).sum()
        df_pivotT = df_pivot.T
        ymax = df_pivot.columns.max()
        df_pivotT_reindexed = df_pivotT.reindex(
            index=np.linspace(0, int(ymax), int(((1 / mult) * int(ymax)) + 1)))
        df_pivot = df_pivotT_reindexed.T.fillna(0)
        df_pivot = df_pivot.tz_localize("UTC")
        df_pivot = df_pivot.tz_convert("US/Central")
        df_pivot = df_pivot.tz_localize(None)
        idx = pd.date_range(
            dt_min.replace(second=0, microsecond=0),
            dt_max.replace(second=0, microsecond=0),
            freq=freq,
        )
        df_fill = pd.DataFrame(index=idx, columns=df_pivot.columns).fillna(0)
        df_fill = df_fill.tz_localize(None)
        df_pivot.index.name = None
        df_pivot = df_fill.add(df_pivot, fill_value=0)
        df_pivot = df_pivot.replace(0, pd.np.nan)
    except Exception:
        idx = pd.date_range(
            dt_min.replace(second=0, microsecond=0),
            dt_max.replace(second=0, microsecond=0),
            freq=freq,
        )
        df_fill = pd.DataFrame(
            index=idx,
            columns=np.linspace(0, int(50), int(((1 / mult) * int(50)) + 1)),
        ).fillna(0)
        df_pivot = df_fill.tz_localize(None)
        df_pivot = df_pivot.replace(0, pd.np.nan)

    data_lt = [
        go.Heatmap(
            x=df_pivot.index,
            y=df_pivot.columns,
            z=df_pivot.T.values,
            colorscale=config.scl_lightning,
            zmax=np.nanquantile(df_pivot, 0.95),
            zmin=1,
            zauto=False,
            showscale=False,
            # connectgaps=True,
        )
    ]

    layout_lt = go.Layout(
        autosize=True,
        font=dict(family="Roboto Mono"),
        hoverlabel=dict(font=dict(family="Roboto Mono")),
        height=300,
        yaxis=dict(
            range=[0, 30],
            domain=[0.02, 0.98],
            title="Distance (mi)",
            ticks="",
            fixedrange=True,
            titlefont=dict(family="Roboto Mono", color="rgb(255, 210, 63)"),
        ),
        xaxis=dict(
            type="date",
            range=[dt_min, dt_max],
            ticks="",
        ),
        margin=dict(r=50, t=30, b=35, l=60, pad=0),
        showlegend=False,
    )

    graphJSON_lt = json.dumps(
        dict(data=data_lt, layout=layout_lt),
        cls=plotly.utils.PlotlyJSONEncoder,
    )

    return (
        graphJSON_td,
        graphJSON_pr,
        graphJSON_cb,
        graphJSON_pc,
        graphJSON_wd,
        graphJSON_su,
        graphJSON_wr,
        graphJSON_thp,
        graphJSON_lt,
    )
#For some reason it stores all the values as a list inside another list,
#So this line just gets the real list of y values
y_values = y_values[0]

#Calculates each bar's RGB color
color = []
for i in range (0, len(y_values)):
    val = y_values[i]
    r_val = str(val * 200)
    g_val = str(10)
    b_val = str(200)
    color.append('rgb(' + r_val + ',' + g_val + ',' + b_val + ')')

#Creates the polar bar graph with the x values, y values, and colors from above
trace = go.Figure([go.Barpolar(opacity=0.75, theta=x_values, r=y_values, marker=dict(color=color))])

#Displays the dropdown menu
display(track_selection)

#Turns the polar bar graph into a FigureWidget so it will live update then displays it
fig_widget = go.FigureWidget(data=trace)
fig_widget


# In[ ]:




Пример #23
0
            "text": "Match 2",
            "x": 0.5,
            "y": 0.5
        }]
    }
}

########################  Radar chart: Effort in Matches 1 - 2 ########################
# - . - . - . - . - . - . - . - . - . - . - . - . - . - . - . - . - . - . - . - . - . - . - . - .
# Define radar  Data: score of answers questions per match
# - . - . - . - . - . - . - . - . - . - . - . - . - . - . - . - . - . - . - . - . - . - . - . - .
# Create traces
radar_trace0 = go.Barpolar(
    #   x = results_m1['qid'],
    r=results_m1['calculated_effort'],
    text=results_m1['qid'],
    # mode = 'lines+markers',
    name='Exploring raw data',
    marker=dict(color='rgb(106,81,163)'))

radar_trace1 = go.Barpolar(
    #   x = results_m1['qid'],
    r=results_m2['calculated_effort'],
    text=results_m2['qid'],
    # mode = 'lines+markers',
    name='Exploring views',
    marker=dict(color='rgb(203,201,226)'))

#trace1 = go.Barpolar(
#    r=[77.5, 72.5, 70.0, 45.0, 22.5, 42.5, 40.0, 62.5],
#    text=['North', 'N-E', 'East', 'S-E', 'South', 'S-W', 'West', 'N-W'],
Пример #24
0
def update_diff_rose(rose_dict, units, pcount):
    """Generate difference wind rose by taking difference in
    frequencies of speed/direction bins
    """
    # set up layout info first, used in event that selected station lacks
    # sufficient data for comparison
    station_name = luts.map_data.loc[rose_dict["sid"]]["real_name"]

    rose_layout = {
        "title": dict(
            text="",
            font=dict(size=18),
        ),
        "height": 700,
        "font": dict(family="Open Sans", size=14),
        "margin": {
            "l": 0,
            "r": 0,
            "b": 20,
            "t": 75
        },
        "legend": {
            "orientation": "h",
            "x": 0,
            "y": 1
        },
        "polar": {
            "legend": {
                "orientation": "h"
            },
            "angularaxis": {
                "rotation": 90,
                "direction": "clockwise",
                "tickmode": "array",
                "tickvals": [0, 45, 90, 135, 180, 225, 270, 315],
                "ticks": "",  # hide tick marks
                "ticktext": ["N", "NE", "E", "SE", "S", "SW", "W", "NW"],
                "tickfont": {
                    "color": "#444"
                },
                "showline": False,  # no boundary circles
                "color": "#888",  # set most colors to #888
                "gridcolor": "#efefef",
            },
            "radialaxis": {
                "color": "#888",
                "gridcolor": "#efefef",
                "ticksuffix": "%",
                "showticksuffix": "last",
                "tickcolor": "rgba(0, 0, 0, 0)",
                "tick0": 0,
                "dtick": {
                    8: 2,
                    16: 2,
                    36: 1
                }[pcount],
                "ticklen": 10,
                "showline": False,  # hide the dark axis line
                "tickfont": {
                    "color": "#444"
                },
            },
            "hole": 0.2,
        },
        "paper_bgcolor": luts.background_color,
    }

    if "trace_dict" in rose_dict:
        # this handles case of insufficient data for station
        # trace_dict only present if insufficient data for comparison
        empty_trace = go.Barpolar(rose_dict["trace_dict"])
        rose_layout["annotations"] = [rose_dict["anno_dict"]]

        return {"layout": rose_layout, "data": [empty_trace]}

    data_list = [pd.DataFrame(df_dict) for df_dict in rose_dict["data_list"]]

    rose_data = data_list[0]
    # compute freuency differences
    rose_data["frequency"] = data_list[1]["frequency"] - rose_data["frequency"]

    traces = []
    get_rose_traces(rose_data, traces, units, True, True)

    station_calms = pd.DataFrame(rose_dict["calms_dict"])
    # compute calm difference
    calm_diff = station_calms.iloc[1]["percent"] - station_calms.iloc[0][
        "percent"]
    calm_change = luts.calm_diff_lut[calm_diff > 0]
    calm_text = (
        f"calms <b>{calm_change['text']}</b><br>by {abs(round(calm_diff * 100, 1))}%"
    )
    rose_layout["annotations"] = [{
        "x": 0.5,
        "y": 0.5,
        "showarrow": False,
        "text": calm_text,
        "xref": "paper",
        "yref": "paper",
    }]
    rose_layout["shapes"] = [{
        "type": "circle",
        "x0": 0.455,
        "y0": 0.4,
        "x1": 0.545,
        "y1": 0.6,
        "text": calm_text,
        "xref": "paper",
        "yref": "paper",
        "line": {
            "color": "#fff"
        },
        "opacity": calm_diff / 0.2,
        "fillcolor": calm_change["fill"],
    }]

    decade1, decade2 = rose_dict["target_decades"]
    rose_layout["title"][
        "text"] = f"Change in winds from {decade1} to {decade2}, {station_name}"

    return {"layout": rose_layout, "data": traces}
Пример #25
0
import numpy as np
import pandas as pd
import plotly
#plotly.offline.init_notebook_mode(connected=True)
import plotly.offline as py
import plotly.graph_objs as go
from plotly import tools

dataset = pd.read_csv('C:/Users/BadBoy/Desktop/nightingale.csv', header=1)

first = go.Barpolar(
   r = dataset['All other causes.1'][0:12],
   theta=dataset['Month'][0:12],
    marker = dict(
        color = '#cf3317', 
        opacity = 0.7),  
    name = 'All other causes', 
    showlegend = True,
    subplot = 'polar1',)

second = go.Barpolar(
    r = dataset['Zymotic diseases.1'][0:12],
    theta = dataset['Month'][0:12],
    marker = dict(
        color = '#17cccf', 
        opacity = 0.7), 
    name = 'Zymotic diseases', 
    showlegend = True,
    subplot = 'polar1',)

Пример #26
0
def update_figure(year):
    
    dff = df[(df["year"] >= year[0]) & (df["year"] <= year[1])]
    
    [res, POT] = extract_peaks_rolling(dff, 48, True, 'weibull' )
    trace1 = []
    trace1.append(go.Scatter(x=dff["Date"], y=dff['hmo'], name='Significant Wave Height', mode='lines',
                                marker={'size': 8, "opacity": 0.6, "line": {'width': 0.5}}, ))
    trace1.append(go.Scatter(x=res["date_time"], y=res['hmo'], name='Storms/ Extreme events', mode='markers', marker_color='rgba(255, 0, 0, 0.9)'))
    
    trace2 = []
    trace2.append(go.Scatter(x=dff["Date"], y=dff['tp'], name='Peak Wave Period', mode='lines',
                                marker={'size': 8, "opacity": 0.6, "line": {'width': 0.5}}, ))
    trace2.append(go.Scatter(x=res["date_time"], y=res['tp'], name='Storms/ Extreme events', mode='markers', marker_color='rgba(255, 0, 0, 0.9)'))
    
    [lvl, rose_df] = wind_rose_update(dff)
    
    fig = go.Figure()
    
    fig.add_trace(go.Barpolar(
                    r=[i for i in rose_df['l4']],
                    text=[i[0] for i in rose_df['direction']],
                    name='<%0.2f m'%(lvl['l4'][1]),
                    marker=dict(color='rgb(242,240,247)')
                    ))
    fig.add_trace(go.Barpolar(
                    r=[i for i in rose_df['l3']],
                    text=[i[0] for i in rose_df['direction']],
                    name='%0.2f-%0.2f m'%(lvl['l3'][0],lvl['l3'][1]),
                    marker=dict(color='rgb(203,201,226)')
                    ))    
    fig.add_trace(go.Barpolar(
                    r=[i for i in rose_df['l2']],
                    text=[i[0] for i in rose_df['direction']],
                    name='%0.2f-%0.2f m'%(lvl['l2'][0],lvl['l2'][1]),
                    marker=dict(color='rgb(158,154,200)')
                    ))    
    fig.add_trace(go.Barpolar(
                    r=[i for i in rose_df['l1']],
                    text=[i[0] for i in rose_df['direction']],
                    name='%0.2f-%0.2f m'%(lvl['l1'][0],lvl['l1'][1]),
                    marker=dict(color='rgb(106,81,163)')
                    ))
    
    fig.update_traces(text=['North', 'N-E', 'East', 'S-E', 'South', 'S-W', 'West', 'N-W'])
    fig.update_layout(
        title='Significant Wave Height Directional Distribution',
        font_size=16,
        legend_font_size=16,
        polar_radialaxis_ticksuffix='%',
        polar_angularaxis_rotation=90,
        polar = dict(angularaxis = dict(direction = "clockwise",period = 6)                    )
        )
    
    ## Boxplot updates:
    # Initialise figure with subplots
    fig_bp = make_subplots(rows=3, cols=1, 
                           subplot_titles=(f"Significant wave heights for {'-'.join(str(i) for i in year)}",
                           f"Peak wave periods for {'-'.join(str(i) for i in year)}",
                           f"Significant wave height directional distributions for {'-'.join(str(i) for i in year)}"))
    
    # Add traces
    for month, month_name, cls in zip(dff.month.unique(), months, box_colours):
        fig_bp.add_trace(go.Box(y=dff[dff['month'] == month]['hmo'], name=month_name, marker={'size': 4, 'color': cls}, showlegend=False), row=1, col=1)
        fig_bp.add_trace(go.Box(y=dff[dff['month'] == month]['tp'], name=month_name, marker={'size': 4, 'color': cls}, showlegend=False), row=2, col=1)
        fig_bp.add_trace(go.Box(y=dff[dff['month'] == month]['dir'], name=month_name, marker={'size': 4, 'color': cls}, showlegend=False), row=3, col=1)
    
    # Update xaxis properties
    for i in [1,2,3]:
        fig_bp.update_xaxes(title_text='Month', row=i, col=1)
    
    # Update yaxis properties
    axes_labels = ['Sig wave height (m)', 'Peak wave period (s)', 'Sig wave dir (degrees)']
    for ylabel in axes_labels:
        fig_bp.update_yaxes(title_text=ylabel, row=(axes_labels.index(ylabel)+1), col=1)
        
    # Update figure layout
    fig_bp.update_layout(autosize=True,
                         margin={"l": 70, "b": 80, "r": 70},
                         xaxis={"showticklabels": True,},
                         yaxis={"zerolinecolor": "rgb(243, 243, 243)", "zerolinewidth": 3,},
                         width=960,
                         height=1100 #px
                         )
           
    return [{"data": trace1,
            "layout": go.Layout(title="Significant Wave Height", colorway=['#2c7bb6','#81e36d'],
                                yaxis={"title": "Hm0 ( meter )"}, yaxis2={"title": "Tp ( second )", "side":"right", "overlaying":'y'}, 
                                xaxis={"title": "Date"})},
            {"data": trace2,
            "layout": go.Layout(title="Peak Wave Period", colorway=['#81e36d'],
                                yaxis={"title": "Tp ( second )"}, xaxis={"title": "Date"})},
            fig,
            fig_bp
            ]