コード例 #1
0
def calculator(a, b, c, d):
    df3 = pd.DataFrame(a, columns=[i['name'] for i in b])
    df4 = pd.DataFrame(c, columns=[i['name'] for i in d])

    luas = np.random.normal(int(df3.iloc[2, 1]), int(df3.iloc[3, 1]),
                            int(df4.iloc[0, 0]))
    luas2 = luas.clip(int(df3.iloc[0, 1]), int(df3.iloc[1, 1]))

    ketebalan = np.random.normal(int(df3.iloc[2, 2]), int(df3.iloc[3, 2]),
                                 int(df4.iloc[0, 0]))
    ketebalan2 = ketebalan.clip(int(df3.iloc[0, 2]), int(df3.iloc[1, 2]))

    ntg = np.random.normal(int(df3.iloc[2, 3]), int(df3.iloc[3, 3]),
                           int(df4.iloc[0, 0]))
    ntg2 = ntg.clip(int(df3.iloc[0, 3]), int(df3.iloc[1, 3]))

    por = np.random.normal(int(df3.iloc[2, 4]), int(df3.iloc[3, 4]),
                           int(df4.iloc[0, 0]))
    por2 = por.clip(int(df3.iloc[0, 4]), int(df3.iloc[1, 4]))

    sw = np.random.normal(int(df3.iloc[2, 5]), int(df3.iloc[3, 5]),
                          int(df4.iloc[0, 0]))
    sw2 = sw.clip(int(df3.iloc[0, 5]), int(df3.iloc[1, 5]))

    bo = np.random.uniform(int(df3.iloc[0, 6]), int(df3.iloc[1, 6]),
                           int(df4.iloc[0, 0]))

    cadangan = 7758 * (luas2 * 0.000247105) * (ketebalan2 * 3.28084) * (
        ntg2 / 100) * ((100 - sw2) / 100) * (por2 / 100) / bo

    total = pd.DataFrame(cadangan, columns=[
        'OOIP'
    ]).describe(percentiles=[.1, .2, .25, .5, .6, .75, .9]).round().T

    fig = go.Figure()

    fig.add_trace(go.Histogram(x=cadangan, cumulative_enabled=True))
    fig.update_layout(
        title_text='OOIP Iteration ' + str(df4.iloc[0, 0]),  # title of plot
        xaxis_title_text='Barrel Oil',  # xaxis label
        yaxis_title_text='Count',  # yaxis label
    )
    des = [
        dash_table.DataTable(
            id='tes',
            columns=[{
                "name": i,
                "id": i
            } for i in total.columns],
            data=total.to_dict('records'),
        )
    ]

    return (des, fig)
コード例 #2
0
def make_hist(ys: Iterable[float], name: str):
    fig = go.Figure()
    fig.add_trace(go.Histogram(
        x=ys,
        xbins=dict(size=0.1)
    ))
    fig.update_layout(
        title_text=f'{name} Score Distribution',
        xaxis_title_text='Docking Score',
        yaxis_title_text='Count'
    )
    return fig.write_image(f'{name}_clusters_scores_histogram.pdf')
コード例 #3
0
ファイル: step3.py プロジェクト: chandanws/mexican-jobs-2020
def plot_hours(df):
    """Plots the hours required to work in an Histogram.

    Parameters
    ----------
    df : pandas.DataFrame
        A pandas DataFrame containing job offers data.

    """

    fig = go.Figure()

    fig.add_traces(go.Histogram(x=df["hours_worked"], marker_color="#ffa000"))

    fig.update_xaxes(title="Hours Required",
                     ticks="outside",
                     ticklen=10,
                     gridwidth=0.5,
                     tickcolor="#FFFFFF",
                     linewidth=2,
                     showline=True,
                     mirror=True,
                     nticks=35,
                     title_standoff=20)

    fig.update_yaxes(title="Number of Job Offers",
                     ticks="outside",
                     ticklen=10,
                     separatethousands=True,
                     tickcolor="#FFFFFF",
                     linewidth=2,
                     showline=True,
                     mirror=True,
                     nticks=18,
                     gridwidth=0.5,
                     title_standoff=5)

    # Add final customizations.
    fig.update_layout(showlegend=False,
                      width=1200,
                      height=800,
                      font_color="#FFFFFF",
                      font_size=18,
                      title_text="Labour Hours Distribution",
                      title_x=0.5,
                      title_y=0.93,
                      margin_l=120,
                      margin_b=120,
                      title_font_size=30,
                      paper_bgcolor="#37474f",
                      plot_bgcolor="#263238")

    fig.write_image("7.png")
コード例 #4
0
def q3Plotter(productCD, width=800, height=300):
  enable_plotly_in_cell()
  fig = make_subplots(rows=1, cols=2, subplot_titles=['Histogram', 'Violin Plot'], horizontal_spacing=0.1)
  fig.append_trace(go.Histogram(x = mergeData[mergeData.ProductCD==productCD].TransactionAmt), row=1, col=1)
  fig.append_trace(go.Violin(x = mergeData[mergeData.ProductCD==productCD].TransactionAmt,  box_visible=True), row=1, col=2)
  #trace = go.Histogram(x = mergeData[mergeData.ProductCD==i].TransactionAmt)
  #data = [trace]
  #layout = go.Layout(title=go.layout.Title(text='Distribution of TransactionAmt for ProductCD: '+i),
  #                  xaxis=go.layout.XAxis(title=go.layout.xaxis.Title(text="$")))
  #fig = go.Figure(data=data, layout=layout)
  fig.update_layout(height = height, width = width, showlegend=False, title_text="Distribution of TransactionAmt for ProductCD: "+productCD)
  iplot(fig)
コード例 #5
0
def histBox(df, col):

    fig = make_subplots(rows=1, cols=2)

    fig.add_trace(go.Histogram(x=df[col], name='Hitrogram'), row=1, col=1)

    fig.add_trace(go.Box(y=df[col], name='Boxplot'), row=1, col=2)

    fig.update_layout(height=600,
                      width=800,
                      title_text=f'Distribution of {col}')
    return fig
コード例 #6
0
def histogram(vals, thresholds):
    nbins = int(np.sqrt(vals.size))
    h_up = np.histogram(vals, bins=nbins)[0].max()
    hist = go.Histogram(x=vals, nbinsx=nbins)
    fig = go.Figure(data=[hist] + [
        go.Scatter(x=[x, x],
                   y=[0, h_up],
                   mode='lines',
                   name='Threshold {0}'.format(idx + 1))
        for idx, x in enumerate(thresholds)
    ])
    return fig
コード例 #7
0
def plot_hist(kernel_name_1, bin_size_1, kernel_name_1000, bin_size_1000, layer_dfs):

    fig1 = go.Figure()
    fig1000 = go.Figure()

    # BatchSize=1
    fig1.add_trace(go.Histogram(x=layer_dfs['l1_df'].query('Name==\'%s\''%kernel_name_1).Duration, name='L1: '+kernel_name_1[:15], xbins=dict(size=bin_size_1), marker_color='lightblue'))
    fig1.add_trace(go.Histogram(x=layer_dfs['l2_df'].query('Name==\'%s\''%kernel_name_1).Duration, name='L2: '+kernel_name_1[:15], xbins=dict(size=bin_size_1), marker_color='blue'))
    fig1.add_trace(go.Histogram(x=layer_dfs['l3_df'].query('Name==\'%s\''%kernel_name_1).Duration, name='L3: '+kernel_name_1[:15], xbins=dict(size=bin_size_1), marker_color='darkblue'))

    # BatchSize=1000
    fig1000.add_trace(go.Histogram(x=layer_dfs['l1_df_1000'].query('Name==\'%s\''%kernel_name_1000).Duration, name='L1: '+kernel_name_1000[:15], xbins=dict(size=bin_size_1000), marker_color='lightgreen'))
    fig1000.add_trace(go.Histogram(x=layer_dfs['l2_df_1000'].query('Name==\'%s\''%kernel_name_1000).Duration, name='L2: '+kernel_name_1000[:15], xbins=dict(size=bin_size_1000), marker_color='green'))
    fig1000.add_trace(go.Histogram(x=layer_dfs['l3_df_1000'].query('Name==\'%s\''%kernel_name_1000).Duration, name='L3: '+kernel_name_1000[:15], xbins=dict(size=bin_size_1000), marker_color='darkgreen'))

    # Additional formatting and titles
    fig1.update_layout(barmode='overlay',
                       title_text='BatchSize=1 Kernel Runtime Variations',
                       xaxis_title_text='Kernel Duration (us)',
                       yaxis_title_text='Number of Occurances (out of 50 trials)'
                      )
    fig1.update_traces(opacity=.75)

    fig1000.update_layout(barmode='overlay',
                       title_text='BatchSize=1 Kernel Runtime Variations',
                       xaxis_title_text='Kernel Duration (us)',
                       yaxis_title_text='Number of Occurances (out of 50 trials)'
                      )
    fig1000.update_traces(opacity=.75)

    fig1.show()
    fig1000.show()
コード例 #8
0
def plot_gain(df):
    '''
        Input: df - Dataframe of the stock

        Output: Histograms of the daily returns and the daily change in percentage of the stock

    '''

    xDR = np.arange(min(df['Daily Return'].dropna().tolist()),
                    max(df['Daily Return'].dropna().tolist()),
                    len(df['Daily Return'].dropna()))
    xC = np.arange(min(df['Change %'].dropna().tolist()),
                   max(df['Change %'].dropna().tolist()),
                   len(df['Change %'].dropna()))

    fig = make_subplots(rows=1, cols=2,
                        subplot_titles=(f'Daily Return of stock "{df["Company stock name"][0]}"',
                                        f'Daily change in % of stock "{df["Company stock name"][0]}"'))

    fig.add_trace(go.Histogram(x=df['Daily Return'].dropna(), marker_color='#330C73', opacity=0.8), row=1, col=1)
    fig.add_trace(go.Scatter(x=xDR, y=df['Daily Return'].dropna(), mode='lines', line_color='#330C73'), row=1, col=1)

    fig.add_trace(go.Histogram(x=df['Change %'].dropna(), marker_color='#330C73', opacity=0.8), row=1, col=2)
    fig.add_trace(go.Scatter(x=xC, y=df['Change %'].dropna(), mode='lines', line_width=5, line_color='#330C73'), row=1,
                  col=2)

    fig.update_layout(showlegend=False)

    fig.update_xaxes(title_text="Price USD ($)", row=1, col=1)
    fig.update_xaxes(title_text="Percentage %", row=1, col=2)

    fig.update_yaxes(title_text="Counts", row=1, col=1)
    fig.update_yaxes(title_text="Counts", row=1, col=2)

    fig.update_layout(
        bargap=0.1,
        bargroupgap=0.1
    )

    return fig
コード例 #9
0
def generate_histogram(n_clicks, decision, range, table_data):
    if n_clicks > 0 and decision and range:
        df = pd.DataFrame(table_data)
        data = df[decision]
        min_val = data.min()
        max_val = data.max()
        size = (max_val - min_val) / int(range)

        return {
            'data': [go.Histogram(x=df[decision], xbins=dict(
                      start=min_val,
                      end=max_val,
                      size=size),
                      autobinx=False)],
            'layout': go.Layout(
                xaxis={'title': decision},
                yaxis={'title': 'Quantity'},
                margin={'l': 40, 'b': 40, 't': 30, 'r': 0},
                clickmode='event+select',
                title='histogram'
            )
        }
    elif n_clicks > 0 and decision:
        df = pd.DataFrame(table_data)

        return {
            'data': [go.Histogram(x=df[decision])],
            'layout': go.Layout(
                xaxis={'title': decision},
                yaxis={'title': 'Ilość'},
                margin={'l': 40, 'b': 40, 't': 30, 'r': 0},
                clickmode='event+select',
                title='histogram'
            )
        }
    else:
        return {
            'data': [],
            'layout': go.Layout(title='histogram'),
        }
コード例 #10
0
    def plot_distributions(self):
        df = self.normalised_df[self.col_types['int']].set_index(
            self.y_cols[0])
        if df.shape[0] > 1000:
            df = df.sample(1000)
        fig = go.Figure()

        def get_kde(col, var):
            fig_temp = ff.create_distplot(
                [df[col]], ['distplot'])  # TODO: check curve_type='normal'
            x = fig_temp['data'][1].x
            y = fig_temp['data'][1].y
            if var == 'x':
                return x
            elif var == 'y':
                return y

        fig_temp = ff.create_distplot([df[df.columns[0]]], ['distplot'])
        fig.add_trace(
            go.Histogram(x=df[df.columns[0]],
                         visible=True,
                         histnorm='probability density',
                         marker_color='#2D3949',
                         opacity=0.75))
        fig.add_trace(
            go.Scatter(x=fig_temp['data'][1].x,
                       y=fig_temp['data'][1].y,
                       visible=True,
                       marker_color='#ff9900'))
        buttons = []
        for col in df.columns:
            buttons.append(
                dict(
                    method='restyle',
                    label=col,
                    visible=True,
                    args=[{
                        'y': [None, get_kde(col, 'y')],
                        'x': [df[col], get_kde(col, 'x')],
                        'type': ['histogram', 'scatter']
                    }],
                ))

        updatemenu = set_up_buttons(buttons)
        fig.update_layout(
            showlegend=False,
            updatemenus=updatemenu,
            title_text=f"Distribution",
            template="plotly_white_custom",
        )

        return opy.plot(fig, auto_open=False, output_type='div')
コード例 #11
0
def histogram(df,
              title='Histogram',
              out_path=None,
              max_col=2,
              layout_kwargs={},
              to_image=False,
              bin_algo='default',
              str_length=None,
              hidden_char='..'):

    bin_algos = ['default', 'count', 'width']
    assert bin_algo in bin_algos, f'bin_algo not in valid list: {bin_algos}'

    data = []
    colors = DEFAULT_PLOTLY_COLORS
    columns = df.columns

    for column in columns:
        try:
            # https://www.qimacros.com/histogram-excel/how-to-determine-histogram-bin-interval/
            n_data = len(np.unique(df[column]))
            n_bins = int(np.ceil(np.sqrt(n_data)))
            width = (df[column].max() - df[column].min()) / n_bins

            nbinsx = n_bins if bin_algo == 'count' else None
            xbins = {'size': width} if bin_algo == 'width' else None

        except TypeError:
            nbinsx = None
            xbins = None

        x = df[column].copy()
        if x.dtype == object:
            x = x.sort_values()
            x = np.where(
                x.str.len() > str_length,
                x.str.slice(stop=str_length).str.strip() + hidden_char, x)

        data.append(
            go.Histogram(x=x,
                         name=column,
                         showlegend=False,
                         nbinsx=nbinsx,
                         xbins=xbins,
                         marker={'color': colors[0]}))

    plot_subplots(data,
                  max_col=max_col,
                  title=title,
                  out_path=out_path,
                  layout_kwargs=layout_kwargs,
                  to_image=to_image)
コード例 #12
0
def create_histogram(df: pd.DataFrame, column: str) -> dcc.Graph:
    """Create Histogram for dataframe and column"""
    return dcc.Graph(
        id="graph-{:s}".format(column),
        figure={
            "data": [go.Histogram(x=df[column])],
            "layout": {
                "title": column.title(),
                "xaxis": {"title": column.title()},
                "yaxis": {"title": "Frequency"},
            }
        }
    )
コード例 #13
0
def plot_hit_miss(data, min_value, max_value, step):
        fig = go.Figure()
        fig.add_trace(go.Histogram(
            x=data['hits'],
            name='hits',
            xbins=dict(
                start=min_value,
                end=max_value,
                size=step
            ),
        ))
        fig.add_trace(go.Histogram(
            x=data['misses'],
            name='misses',
            xbins=dict(
                start=min_value,
                end=max_value,
                size=step
            ),
        ))
        fig.layout.xaxis.update(range=[min_value,max_value])
        fig.show()
コード例 #14
0
def plot_histogram(X,opt):
    if opt == 'ambos':
        #Dataset completo
        x = df[X]
    elif opt == 'crash':
        #Dataset filtrado por coque
        x = df[df[trg[0]]==1][X]
    elif opt == 'libre':
        #Dataset filtrado por libre de accidente
        x = df[df[trg[0]]==0][X]
    fig = go.Figure(data=[go.Histogram(x=x)])
    fig.update_layout(title_text=X)
    return fig
コード例 #15
0
ファイル: Dense.py プロジェクト: ckaelig/dnnviewer
    def get_unit_tab_content(self, unit_idx, active_tab):
        """ Get the content of the selected tab """
        w = self.weights[:, unit_idx]

        if active_tab == 'info':
            return self._get_unit_info(unit_idx, len(w)), None

        elif active_tab == 'weights':
            fig = go.Figure(data=[
                go.Histogram(x=w,
                             marker=self.theme.gradient_color_scale.as_dict(w))
            ])
            fig.update_layout(
                margin=self.theme.bottom_figure_margins,
                title=dict(text='Weight histogram', font=dict(size=14)),
                xaxis_title_text='Amplitude',
                bargap=0.2,  # gap between bars of adjacent location coordinates)
                template=self.theme.plotly)
            return [], fig

        elif active_tab == 'grads':
            if self.grads is None:
                return html.P("No gradients available"), None

            g = self.grads[:, unit_idx]
            fig = go.Figure(data=[
                go.Histogram(x=g,
                             marker=self.theme.gradient_color_scale.as_dict(g))
            ])
            fig.update_layout(
                margin=self.theme.bottom_figure_margins,
                title=dict(text='Gradients histogram', font=dict(size=14)),
                xaxis_title_text='Amplitude',
                # yaxis_title_text='Count',
                bargap=0.2,  # gap between bars of adjacent location coordinates)
                template=self.theme.plotly)
            return [], fig

        return AbstractLayer.get_layer_tab_content(self, active_tab)
コード例 #16
0
ファイル: make_plots.py プロジェクト: dfox3/srna
def trimPlot(data, out_pre):
    k = list(data.keys())
    k.sort()
    y1 = [data[y][READS_W_ADAPTERS] for y in k]
    y2 = [data[y][READS_WRITTEN] for y in k]
    fig = go.Figure()
    fig.add_trace(go.Histogram(histfunc="sum", y=y1, x=k,
                               name="reads written"))
    fig.update_layout(autosize=True, height=700)
    fig.update_xaxes(title_text='File Name')
    fig.update_yaxes(title_text='Percent Trimmed with 3\' Adapter Found')

    fig.write_html(str(out_pre) + "/trim_plot.html")
コード例 #17
0
def view_data(state):
    # Get data...
    mvals = df[(df['State_Name'].str.match(state)) & (df['Mean'] != 0)]['Mean']

    # Print Histogram...
    fig = go.Figure(data=[go.Histogram(x=mvals)])

    fig.update_layout(title_text='{} Mean Household Income'.format(state),
                      xaxis_title_text='Household Income',
                      yaxis_title_text='Count',
                      bargap=0.2,
                      bargroupgap=0.1)

    fig.show()

    # Print Probability Plot...
    stats.probplot(mvals, plot=plt)
    plt.show()

    # Log Transformation...
    mvals_log = df[(df['State_Name'].str.contains(state))
                   & (df['Mean'] != 0)]['Mean'].apply(lambda x: np.log(x))

    # Log Transformation Histogram...
    fig = go.Figure(data=[go.Histogram(x=mvals_log)])

    fig.update_layout(
        title_text='{} Mean Household Income (Log Transformation)'.format(
            state),
        xaxis_title_text='Household Income',
        yaxis_title_text='Count',
        bargap=0.2,
        bargroupgap=0.1)

    fig.show()

    # Log Transforamtion Probability Plot
    stats.probplot(mvals_log, plot=plt)
    plt.show()
コード例 #18
0
def histogram(column, telcom):
    # Separating churn and non churn customers
    churn = telcom[telcom["Churn"] == "Yes"]
    not_churn = telcom[telcom["Churn"] == "No"]
    trace1 = go.Histogram(x=churn[column],
                          histnorm="percent",
                          name="Churn Customers",
                          marker=dict(line=dict(width=.5, color="black")),
                          opacity=.9)
    x = np.random.randn(500)
    fig = go.Figure(data=[go.Histogram(x=x, histnorm='probability')])

    fig.show()

    trace2 = go.Histogram(x=not_churn[column],
                          histnorm="percent",
                          name="Non churn customers",
                          marker=dict(line=dict(width=.5, color="black")),
                          opacity=.9)

    data = [trace1, trace2]
    layout = go.Layout(
        dict(
            title=column + " distribution in customer attrition ",
            plot_bgcolor="rgb(243,243,243)",
            paper_bgcolor="rgb(243,243,243)",
            xaxis=dict(gridcolor='rgb(255, 255, 255)',
                       title=column,
                       zerolinewidth=1,
                       ticklen=5,
                       gridwidth=2),
            yaxis=dict(gridcolor='rgb(255, 255, 255)',
                       title="percent",
                       zerolinewidth=1,
                       ticklen=5,
                       gridwidth=2),
        ))
    fig = go.Figure(data=data, layout=layout)
    py.plot(fig)
コード例 #19
0
    def GetTotalsPlot():

        # get the data
        # later must filter by active movies

        master_ls = list(TB.MasterMovie.objects.values())
        year_distrib = {'netflix': [], 'amazon': [], 'hulu': []}

        for mov in master_ls:
            year = int(mov['Year'])
            index_dx = json.loads(mov['Indeces'])
            
            for key, val in index_dx.items():
                if key in year_distrib and year >= 1980:
                    year_distrib[key].append(year)

        # create the plot 

        fig = GO.Figure()
        fig.add_trace(GO.Histogram(x= year_distrib['amazon'], xbins={'size': 1}, name='Amazon', 
                                marker_color='darkblue', opacity=0.6))
        fig.add_trace(GO.Histogram(x= year_distrib['netflix'], xbins={'size': 1}, name='Netflix', 
                                marker_color='crimson', opacity=0.7))
        fig.add_trace(GO.Histogram(x= year_distrib['hulu'], xbins={'size': 1}, name='Hulu', 
                                marker_color='green', opacity=0.8))
        fig.update_layout(
            title="Total Movie Count for Each Service",
            xaxis_title="Release Year",
            yaxis_title="Movie Count",
            width=600,
            height=400,
            margin=GO.layout.Margin(t=50, r=20, b=50, l=70, pad=0),
            paper_bgcolor="LightSteelBlue",
            barmode='overlay', 
        )

        # format and send to frontend

        return UT.ConvertFigureToJson(fig)
コード例 #20
0
def plot_distribution(metric, start, end, size):
    fig = go.Figure()
    fig.add_trace(
        go.Histogram(x=df_stat[metric],
                     name=metric,
                     xbins=dict(start=start, end=end, size=size)))
    fig.update_layout(
        barmode='overlay',
        title_text=metric + ' distribution',
        xaxis_title_text='Value',  # xaxis label
        yaxis_title_text='Count',  # yaxis label
    )
    return fig
コード例 #21
0
def histogram(selected_patient, selector, value):
    x = histogram_soz(selected_patient, selector, value)
    data = []
    for e in x:
        d = go.Histogram(x=e['d'], name=e[0], opacity=0.75, bingroup=1)
        data.append(d)
    layout = go.Layout(title_text="Histogram prove",
                       showlegend=True,
                       xaxis_title_text=value,
                       yaxis_title_text='Count',
                       barmode='overlay')
    fig = go.Figure(data=data, layout=layout)
    return fig
コード例 #22
0
ファイル: app.py プロジェクト: insaiyancvk/TwitterStalker
def plot_user_analysis_chart(df, search_type):
    if (df is None) or (search_type is None):
        raise PreventUpdate
    subplot_titles = [
        'Followers Count', 'Statuses Count', 'Friends Count',
        'Favourites Count', 'Verified', 'Tweet Source', 'Lang',
        'User Created At'
    ]
    df = pd.DataFrame(df).drop_duplicates('user_screen_name')
    fig = make_subplots(rows=2, cols=4, subplot_titles=subplot_titles)

    for i, col in enumerate(subplot_titles[:4], start=1):
        col = ('user_' + col).replace(' ', '_').lower()
        fig.append_trace(go.Histogram(x=df[col], nbinsx=30, name='Users'), 1,
                         i)
    for i, col in enumerate(subplot_titles[4:7], start=5):
        if (i == 6) and (search_type == 'Search Users'):
            continue
        if col == 'Tweet Source':
            col = 'tweet_source'
        else:
            col = ('user_' + col).replace(' ', '_').lower()
        fig.append_trace(
            go.Bar(x=df[col].value_counts().index[:14],
                   width=0.9,
                   y=df[col].value_counts().values[:14],
                   name='Users'), 2, i - 4)
    fig.append_trace(
        go.Histogram(
            x=df['user_created_at'],
            name='Users',
            nbinsx=30,
        ), 2, 4)

    fig['layout'].update(height=600,
                         plot_bgcolor='#878787',
                         paper_bgcolor='#878787',
                         showlegend=False)
    return fig
コード例 #23
0
ファイル: Q2.py プロジェクト: ShiXianChua/AlgorithmAssignment
def drawHistogram(pos,neg,t):
    x = []
    y = []
    xn = []
    yn = []
    for keys, values in pos.items():
        x.append(keys)
        y.append(values)
    for keysn,valuesn in neg.items():
        xn.append(keysn)
        yn.append(valuesn)

    fig = go.Figure()
    fig.add_trace(go.Histogram(histfunc="sum", y=y, x=x, name="positive"))
    fig.add_trace(go.Histogram(histfunc="sum", y=yn, x=xn, name="negative"))
    fig.update_layout(
        title = t,
        xaxis_title="Words",
        yaxis_title="Frequency",

    )
    fig.show()
コード例 #24
0
def plotHistogram(datapoints, title, xlabel, ylabel):
    layout = go.Layout(title=title,
                       xaxis=dict(title=xlabel),
                       yaxis=dict(title=ylabel))
    fig = go.Figure(layout=layout)

    fig.update_layout(template="ggplot2")
    fig.add_trace(
        go.Histogram(x=datapoints.values,
                     # xbins = {'start': 1, 'size': 0.1, 'end' : 5}
                     ))

    return fig
コード例 #25
0
def hist_by(df:pd.DataFrame, column:str, by:str, alias_column:str=None, 
                alias_by:str=None, colors:list=None, 
                nbins:int=10, func:callable=np.sum) -> go.Figure:
    '''
        This function excludes null values on "column" and "by" doing a simple & functions
        df      -> Pandas DataFrame
        column  -> Column to analyze
        by      -> Column respect to analyze "column"
        alias_column -> String to show in texts (legend, titles, axis)
        alias_by     -> String to show in texts (legend, titles, axis)
        func         -> Criteria for the histogram. Frequency by defaul
        colors       -> list of colors wich the plots will take. This colors should be representated
                        in format:
                        hexa   -> '#F33DF5'
                        rgb    -> 'rgb(200, 56, 13)'
                        rgba   -> 'rgba(20, 189, 12, 90)'
                        string -> 'green'
                        Thes list can contain mix format.
                        colors=['lightgreen', 'rgba(1,200,3,10)', '#FF0034']
                        colors=['green', 'lightgreen', 'darkgreen']
                        This list must be at least teh same lenght of unique values to plot
        nibins       -> Number of bins for the histograms
        return plotly figure or None
    '''
    if not alias_column:
        alias_column = column
    if not alias_by:
        alias_by = by
    new_df = not_nulls(df, column, by)
    uniques = uniques_values(new_df, by)
    if not colors:
        colors = ['#7ED388', '#2F668C', '#ABB392', '#EA7251', '#8501BA', '#09993E', '#BB60C4', '#65F587', '#13CEB7', '#C17B62', '#73A12E', '#344620', '#9B355F', '#B02D36', '#22B407', '#B3391C', '#408C09', '#7846C3', '#548FE2', '#290AFC', '#7C01A8', '#0D8911', '#DEC5CB', '#741BE5', '#5E11F9', '#1C4D07', '#7827A1', '#BFA409', '#F6CB1C', '#DC7AE4', '#97F7ED', '#492CDE', '#CEE30D', '#FAD149', '#BE98C9', '#04D364', '#3D4FF6', '#BB326A', '#4F50A5', '#D02CE0', '#11C68F', '#1863DD', '#0BC224', '#4F2000', '#A38BBC', '#06C5B2']*5
    fig = make_subplots(
        rows=len(uniques),
        subplot_titles=list(uniques))
    for i, unique_ in enumerate(uniques):
        filter_ = new_df[by].apply(contain_substr, args=(unique_,)) # get certain value even on multimple values rows
        filtered_df = new_df[filter_] # filtered dataframe
        fig.add_trace(
            go.Histogram(x=filtered_df[column], name=unique_, 
                        marker_color=colors[i], nbinsx=nbins
                  ), row=i+1, col=1
        )
        fig.update_xaxes(title_text=alias_column, row=i + 1, col=1)
        fig.update_yaxes(title_text=alias_by, row=i + 1, col=1)

    # configurating size, titles and legend
    fig.update_layout(height=350*len(uniques), width=800,
                      title_text=alias_column + ' by ' + alias_by,
                    showlegend=False)
    return fig
コード例 #26
0
def histogram_plot(performance_data, ticker):
    returns = performance_data.diff(axis=0) / performance_data

    returns = performance_data.diff(axis=0) / performance_data

    trace_open = go.Histogram(x=returns['Open'],
                              marker={'colorscale': 'Viridis'},
                              name='Open')

    trace_close = go.Histogram(x=returns['Open'],
                               marker={'colorscale': 'Viridis'},
                               name='Close')

    data = [trace_open, trace_close]

    layout = {
        'title': f'{ticker} Histogram'
        # 'yaxis':{'type': 'lin'}
    }

    fig_histogram = dict(data=data, layout=layout)

    return fig_histogram
コード例 #27
0
 def create_graph(self):
     self.menu._close()
     #fig = go.Figure(data=go.Scatter(x=self.game.time, y=self.game.life))
     #fig.show()
     fig = go.Figure(data=[go.Histogram(x=self.game.life)])
     # Documentazione https://plotly.com/python/histograms/
     fig.update_layout(
         title_text='Tempi percorrenza',  # title of plot
         xaxis_title_text='Value',  # xaxis label
         yaxis_title_text='Count',  # yaxis label
         #bargap=0.2, # gap between bars of adjacent location coordinates
         bargroupgap=0.1  # gap between bars of the same location coordinates
     )
     fig.write_html('tmp.html', auto_open=True)
コード例 #28
0
def plot_distribution(random_sample, bins):
    fig = go.Figure(data=[go.Histogram(x=random_sample, nbinsx=bins)])
    fig.update_layout(title_text="Гистограмма")
    st.write(fig)

    fig = ff.create_distplot([random_sample], [""],
                             bin_size=.2,
                             show_hist=False)
    fig.update_layout(title_text="Плотность")
    st.write(fig)

    fig = go.Figure(go.Histogram2dContour(x=random_sample, y=random_sample))
    fig.update_layout(title_text="Контуры плотности")
    st.write(fig)
コード例 #29
0
ファイル: stats_analysis.py プロジェクト: ronitkumar7/work
def normal_histogram(tweets: List[Tweet]) -> None:
    """Displays a normal histogram in plotly containing the compound values of each tweet
     in tweets.

    Precondition:
        - all(t.sentiment is not None for t in tweets)
    """
    # Retrieves the compound scores of each tweet
    compound_values = [tweet.sentiment['compound'] for tweet in tweets]
    # Compute the summary statistics of the compound values
    summary_data = summary(compound_values)
    # Store the summary statistics of the compound values in text form to add as annotation
    lines = [
        'Mean :' + str(summary_data['mean']),
        'Median :' + str(summary_data['median']),
        'Standard Deviation :' + str(summary_data['stdev']),
        'Range :' + str(summary_data['range'])
    ]

    text = '<br>'.join(lines)  # HTML '<br>' sequence gives newlines
    # Adds the annotation that displays the summary statistics in a box below the graph.
    layout = go.Layout(
        height=800,
        width=800,
        yaxis=go.layout.YAxis(domain=[0.5, 1]),
        annotations=[
            go.layout.Annotation(
                bordercolor='black',
                align='left',
                yanchor='top',  # Align text box's top edge with y axis
                text=text,
                showarrow=False,
                width=650,
                xref='paper',  # Place relative to figure, not axes
                yref='paper',
                font={'family': 'Courier'},
                x=0,  # Coordinates start from top left corner
                y=0.4)
        ])
    # Creates the figure object that draws the histogram and takes in the annotation created above
    fig = go.Figure(
        data=[go.Histogram(x=compound_values, histnorm='probability')],
        layout=layout)
    fig.update_traces(xbins_size=0.01, selector=dict(type='histogram'))
    fig.update_layout(
        title='Percentage of frequency of tweets against compound value range',
        xaxis_title='Compound value range',
        yaxis_title='Percentage of occurrence')
    # Shows the figure object
    fig.show()
コード例 #30
0
ファイル: make_plots.py プロジェクト: dfox3/srna
def alignPlot(data, out_pre):
    k = list(data.keys())
    k.sort()
    y = [data[y] for y in k]
    fig = go.Figure()
    fig.add_trace(
        go.Histogram(histfunc="sum",
                     y=y,
                     x=k,
                     name="percent aligned to miR reference"))
    fig.update_layout(autosize=True, height=700)
    fig.update_xaxes(title_text='File Name')
    fig.update_yaxes(title_text='Percent of Trimmed Reads Aligned')
    fig.write_html(str(out_pre) + "/align_plot.html")