def generate_table(dataframe: pd.DataFrame, column_name_list: List[str] = None, out_file: str = 'table.html'):
    if column_name_list is None:
        table = ff.create_table(dataframe, index=True)
    else:
        table = ff.create_table(dataframe[column_name_list], index=True)

    if out_file is None:
        table.show()
    else:
        plot(table, filename=out_file)
def to_trials_table(trials, precision=6, sort_by_loss=False):
    fmt = '{{:.{}g}}'
    fmt = fmt.format(precision)

    hparams = list(sorted(set(chain.from_iterable([t.keys() for t in trials]))))
    hparams.remove('loss')
    hparams.remove('run')
    hparams = ['run'] + hparams + ['loss']

    data_matrix = []

    # add header
    data_matrix.append(hparams)

    if sort_by_loss:
        trials = sorted(trials, key=lambda trial: trial['loss'])

    for trial in trials:
        row = []
        for param in hparams:
            value = trial.get(param, float('nan'))
            if isinstance(value, float):
                value = fmt.format(value)
            row.append(value)
        data_matrix.append(row)

    table = ff.create_table(data_matrix)
    return table
Exemple #3
0
def plotTable(
    data,
    top_headers=None,  # only required if data is list/nparray, not for pandas df
    width=None,
    plot=True,
    title=None,
):
    '''
    Wrapper for plotly table function
    :return:
    '''
    import pandas as pd

    if type(data) == pd.core.frame.DataFrame:
        top_headers = data.columns
        tbl_data = data.values

    # TODO: this should only be done for numeric datatypes
    tbl_data = tbl_data.astype('|S7').astype(str)

    inp_data = np.vstack((top_headers, tbl_data))

    fig = ff.create_table(inp_data, hoverinfo='skip')

    fig.layout.width = width
    fig.layout.title = title
    fig.layout.margin = {'b': 80, 'r': 80}

    return plotOut(fig, plot)
def visualize_top20_MusicID(df_final):
    # #Unique values for Music Ids
    df_bar_music_id = unique_values(df_final, 'Music Id')
    index = list(range(10))
    music_id = list(df_bar_music_id['unique_values'][0:10])
    counts = list(df_bar_music_id['counts'][0:10])
    Table = []
    Table.append(['Index', 'Music Id', 'Count'])
    for i in range(0, len(music_id)):
        Table.append([i, music_id[i], counts[i]])
    fig = ff.create_table(Table, height_constant=60)
    Music_Bar = go.Bar(x=index,
                       y=counts,
                       xaxis='x2',
                       yaxis='y2',
                       marker=dict(color='#0099ff'),
                       name='Count')
    print(Table[:20])
    fig.add_traces(Music_Bar)
    # initialize xaxis2 and yaxis2
    fig['layout']['xaxis2'] = {}
    fig['layout']['yaxis2'] = {}
    # Edit layout for subplots
    fig.layout.xaxis.update({'domain': [0, .5]})
    fig.layout.xaxis2.update({'domain': [0.6, 1.]})
    # The graph's yaxis MUST BE anchored to the graph's xaxis
    fig.layout.yaxis2.update({'anchor': 'x2'})
    fig.layout.yaxis2.update({'title': 'Count'})
    fig.layout.xaxis2.update({'title': 'index'})
    fig.layout.margin.update({'t': 75, 'l': 50})
    fig.layout.update({'title': 'Trending Music on TikTok'})
    return fig
Exemple #5
0
def updateTabla(opciones):

        if 'Foto' in opciones:
            table =ff.create_table(df[df['direccion']=='{}/download/image/nameOfImage.extention'])
            py.iplot(table, filename='tablaArchivos')
        elif 'Datos' in opciones:

            table = ff.create_table(df[df['direccion']== '{}/download/data/archiveName.extention'] )

            py.iplot(table,filename = 'tablaArchivos')
        elif 'Buscar' in opciones:
            display(w)
            w.observe(buscaUnFichero,names='value')
        else:
            table = ff.create_table(df)
            py.iplot(table,filename = 'tablaArchivos')
Exemple #6
0
def create_table_plot2():
    '''
        Створення бар-чарту для снеків
    '''
    table_data = [['Snack name', 'Snack price', 'Number of orders']]
    dd = db.execute('SELECT snack_name, price, orders_num FROM snack')
    for row in dd:
        table_data.append([row[0], row[1], row[2]])

    # Initialize a fig with ff.create_table(table_data)
    fig = ff.create_table(table_data, height_constant=60)

    data = table_data[1:]
    names = []
    price = []
    for row in data:
        names.append(row[0])
        price.append(row[2])

    fig.add_trace(go.Bar(x=names, y=price, xaxis='x2', yaxis='y2',
                         marker=dict(color='#FF1D84')))
    fig.update_layout(
        title_text='Snack stats',
        height=800,
        margin={'t': 75, 'l': 50},
        yaxis={'domain': [0, .45]},
        xaxis2={'anchor': 'y2'},
        yaxis2={'domain': [.6, 1], 'anchor': 'x2', 'title': 'Orders'}
    )

    graph = plotly.io.to_html(fig)

    return graph
def liste_hotel(input_value):
    df_sel = df_hebergement[df_hebergement['Code insee'] == input_value]
    if df_sel.shape[0] == 0:
        nombre = 0
        commune = df[df['CODE_INSEE'] == input_value]['COMMUNE']
        df_hotel = [['Commune', "Nombre d'hébergements"], [commune, nombre]]
        df_hotel = ff.create_table(df_hotel, colorscale=colorscale)
    elif df_sel.shape[0] < 6:
        commune = df_sel.iloc[0]['Commune']
        df_hotel = ff.create_table(df_sel[['Commune', 'Nom', 'Type']], colorscale=colorscale)
    else:
        nombre = df_sel.shape[0]
        commune = df_sel.iloc[0]['Commune']
        df_hotel = [['Commune', "Nombre d'hébergements"], [commune, nombre]]
        df_hotel = ff.create_table(df_hotel, colorscale=colorscale)
    return df_hotel
Exemple #8
0
def btc_sort():
    btc = read_to_df('xbtusd', '1d', update=True)
    btc = add_opens_days(btc)
    btc = apply_WO(btc)
    btc = apply_MO(btc)
    btc = find_body_ratio(btc)
    btc = find_volume_ratio(btc)
    btc = calc_ma(btc)
    btc = find_gradient(btc)

    btc_1m = read_to_df('xbtusd', '5m', update=True)
    btc_1m = add_opens_days(btc_1m)
    btc_1m = apply_WO(btc_1m)
    btc_1m = apply_MO(btc_1m)
    vwaps = calc_vwap(btc_1m)

    btc = btc.assign(W_vwap=vwaps[['W_vwap']])
    btc = btc.assign(M_vwap=vwaps[['M_vwap']])
    btc = find_returns(btc)

    table_btc, btc, signals_test, columns = create_table(btc)
    table_btc.insert(0, columns)
    btc = find_percentiles(btc)
    btc = find_body_ratio(btc)
    btc = find_volume_ratio(btc)
    btc = calc_ma(btc)
    btc = find_gradient(btc)

    fig_btc = dash_table.DataTable
    fig_btc = ff.create_table(table_btc)

    return btc, fig_btc
def results_py(df, dict):
    """
    inputs:
        df = Dataframe of doc_info
        dict = Dictionary of user input of values
    """
    orig_df_len = len(df)
    d_true_values = {}
    for key, value in dict.items():
        #Basically making a new dict with only values where a user inputted
        if value:
            d_true_values[key] = value
    for k in d_true_values:
        #Go through all the values that were inputted
        #If we're not going to get no results back:
        if len(df[df[k] == str(d_true_values[k]).upper()]) != 0:
            df = df[df[k] == str(d_true_values[k]).upper()]
        else:
            #If our query makes it so we get no results, break & don't change the df
            break
    if len(df) == 0 or len(df) == orig_df_len:
        return (
            '<p><u><h4><b>Your search returned no results, <a href="../" target="">would you like to search again?</a></b></h4></u></p>'
        )
    else:
        make_link(df)
        table = ff.create_table(df)
        return (plotly.offline.plot(table,
                                    include_plotlyjs=False,
                                    output_type='div'))
Exemple #10
0
def log_df(wandb_name: str,
           wandb_step: int,
           writer: SummaryWriter,
           df: pd.DataFrame,
           title: Optional[str] = None):

    # Log table to WandB
    fig = ff.create_table(df, index=True)
    log_plotly_ff(wandb_name, wandb_step, fig, title)

    # Log to Logger
    tb = PrettyTable()
    tb.field_names = ["Category"] + list(df.columns)
    tb.align = "r"
    for row in df.itertuples():
        tb.add_row(row)
        # Log metrics to WandB
        index_name = row[0]
        for metric_name, metric_value in zip(df.columns, row[1:]):
            writer.add_scalar(f'{wandb_name}/{index_name}_{metric_name}',
                              metric_value, wandb_step)

    if title is not None:
        logger.info("%s\n%s", title, tb.get_string())
    else:
        logger.info("\n%s", tb.get_string())
Exemple #11
0
def runge_kutta():
    h = 0.1
    x = [0.0, 0.1, 0.2, 0.3, 0.4, 0.5]
    y_eval = [0.0]
    delta_y = [0.0]
    y_real = [0.0]
    eps = [0.0]

    for i in range(1, len(x)):
        k1 = h * fun(x[i - 1], y_eval[i - 1])
        k2 = h * fun(x[i - 1] + 0.5 * h, y_eval[i - 1] + 0.5 * k1)
        k3 = h * fun(x[i - 1] + 0.5 * h, y_eval[i - 1] + 0.5 * k2)
        k4 = h * fun(x[i - 1] + h, y_eval[i - 1] + k3)

        d = (k1 + 2 * k2 + 2 * k3 + k4) / 6.0
        y_eval.append(y_eval[i - 1] + d)

        delta_y.append(h * fun(y_eval[i], x[i]))
        y_real.append(real_fun(x[i]))
        eps.append(abs(y_real[i] - y_eval[i]))

    # print in table format
    print(y_eval)
    print(delta_y)
    print(y_real)
    print(eps)

    data_matrix = [['k', 'x', 'y', 'delta_y', 'y_real', 'eps']]
    for i in range(0, len(x)):
        data_matrix.append([i, x[i], y_eval[i], delta_y[i], y_real[i], eps[i]])

    table = ff.create_table(data_matrix)
    plot(table)
Exemple #12
0
def update_table(json_cur_data):
	df = pd.read_json(json_cur_data).sort_index(axis=0)
	df = df.tail(min(len(df), 15))	
	df = df[data.columns]
	df = df.sort_index(ascending=False)
	
	return ff.create_table(df, colorscale=[[0, '#42C4F7 '],[.5, '#f2e5ff'],[1, '#ffffff']])
def table_world():
    df = scrape_world()
    df = df.copy().drop(
        columns=['Serious_or_Critical', 'Cases_per_1M_Pop', 'Population'])
    df3 = ff.create_table(df)
    # return df3
    return plotly.offline.plot(df3, output_type='div')
def countStatistics():
    # 读取数据文件
    my_file = ReadCsv("directory.csv").readCsv()
    # 清洗数据-处理缺省值
    my_file = my_file.fillna("None")
    timeZone = my_file["Timezone"]
    # 处理重复数据并排序
    timeZoneSort = sorted(set(timeZone))
    # 根据 TImeZone 重新排列
    group_by_time_zone = my_file.groupby(timeZone)
    # 计算相同时区出现的次数
    time_zone_count = dict(group_by_time_zone["Timezone"].value_counts())
    # 计算星巴克的总数
    store_sum = sum(time_zone_count.values())
    # 每个时区的星巴克的比例
    rate_text = [(value / store_sum) for value in time_zone_count.values()]

    length = len(timeZoneSort)
    values_list = list(time_zone_count.values())
    # 把时区的相关信息写入文件
    with open("timeZone.csv", "w") as csvFile:
        writer = csv.writer(csvFile)
        writer.writerow(["Timezone", "Amount", "Rate"])
        for x in range(length):
            writer.writerow([timeZoneSort[x], values_list[x], rate_text[x]])
    file = ReadCsv("timeZone.csv").readCsv()
    table = FF.create_table(file)
    py.offline.plot(table, filename='countStatistics.html')
Exemple #15
0
def plot_answer(X, Y, epsilons, filename='answer'):
    df = [['X', 'Y', 'eps']]
    for x, y, eps in zip(X, Y, epsilons):
        df.append([x, y, eps])
    df = pd.DataFrame(columns=df[0], data=df[1:])
    table = ff.create_table(df)
    py.plot(table, filename=filename)
def main():
    # load in the iris dataset
    dataframe = pd.read_csv(
        'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data',
        header=None)
    dataframe.columns = [
        'sepal_len', 'sepal_wid', 'petal_len', 'petal_wid', 'class'
    ]

    table = ff.create_table(dataframe[:10])
    plotly.offline.iplot(table, filename='simple_table')
    X = dataframe.iloc[:, 0:4].values
    y = dataframe.iloc[:, 4].values
    # _X now has 2 dimensions....
    _X = PCA(X).compress_with_eigen(2)

    # display data
    traces = []
    for name in ('Iris-setosa', 'Iris-versicolor', 'Iris-virginica'):
        trace = Scatter(x=_X[y == name, 0],
                        y=_X[y == name, 1],
                        mode='markers',
                        name=name,
                        marker=Marker(size=12,
                                      line=Line(
                                          color='rgba(217, 217, 217, 0.14)',
                                          width=0.5),
                                      opacity=0.8))
        traces.append(trace)

    data = Data(traces)
    layout = Layout(xaxis=XAxis(title='PC1', showline=False),
                    yaxis=YAxis(title='PC2', showline=False))
    fig = Figure(data=data, layout=layout)
    plotly.offline.iplot(fig)
Exemple #17
0
    def __visualize_table_ff(amount_of_features, df, header_background_color=None,
                             uneven_cell_color=None, even_cell_color=None):
        if header_background_color is None:
            header_background_color = "#00083e"
        if uneven_cell_color is None:
            uneven_cell_color = "#f2e5ff"
        if even_cell_color is None:
            even_cell_color = "#ffffff"

        df = df.iloc[:, 0:amount_of_features]

        df = df.astype(str)
        columns = list(df)
        max_amount = 115/len(columns)
        shorten = lambda row: [i[:max_amount - 4] + "..." if len(i) > max_amount else i for i in row]

        df = df.apply(shorten)
        df.columns = shorten(columns)

        color_scale = [[0, header_background_color], [.5, uneven_cell_color], [1, even_cell_color]]
        figure = ff.create_table(df, colorscale=color_scale)#, height_constant=60)

        figure.layout.width = 800

        for i in range(len(figure.layout.annotations)):
            figure.layout.annotations[i].font.size = 13

        return figure
Exemple #18
0
def make_stock_table(database, ticker):
    database.reset_index(inplace = True)
    database = database[:50]
    database = database.iloc[:, :5]
    table = ff.create_table(database)
    table_div = pyo.plot(table, output_type = 'div', include_plotlyjs=False)
    return table_div
def draw_table_by_city(state, city):
    df = get_table_from_city(state, city)
    fig = ff.create_table(df, index=True)
    #fig.layout.width=1200
    for i in range(len(fig.layout.annotations)):
        fig.layout.annotations[i].font.size = 8
    return fig
Exemple #20
0
def euler():
    h = 0.1
    x = [0.0, 0.1, 0.2, 0.3, 0.4, 0.5]
    y_eval = [0.0]
    delta_y = [0.0]
    y_real = [0.0]
    eps = [0.0]

    for i in range(1, len(x)):
        y_eval.append(y_eval[i - 1] + h * fun(x[i - 1], y_eval[i - 1]))
        delta_y.append(h * fun(y_eval[i], x[i]))
        y_real.append(real_fun(x[i]))
        eps.append(abs(y_real[i] - y_eval[i]))

    # print in table format
    print(y_eval)
    print(delta_y)
    print(y_real)
    print(eps)

    data_matrix = [['k', 'x', 'y', 'delta_y', 'y_real', 'eps']]
    for i in range(0, len(x)):
        data_matrix.append([i, x[i], y_eval[i], delta_y[i], y_real[i], eps[i]])

    table = ff.create_table(data_matrix)
    plot(table)
Exemple #21
0
def plot():

    df = pd.read_csv('redsan1.csv')

    data_table = FF.create_table(df.head())
    py.plot(data_table, filename='redsan-table')

    trace1 = go.Scatter(
        x=df['date'],
        y=df['polarity'],  # Data
        mode='lines',
        name='polarity'  # Additional options
    )
    # trace2 = go.Scatter(x=df['date'], y=df['polarity'], mode='lines', name='polarity' )
    trace3 = go.Scatter(x=df['date'],
                        y=df['subjectivity'],
                        mode='lines',
                        name='subjectivity')

    layout = go.Layout(
        title=
        'Sentiments About Safaricom with a random sample size of 1000 tweets',
        plot_bgcolor='rgb(230, 230,230)')

    fig = go.Figure(data=[trace1, trace3], layout=layout)

    # Plot data in the notebook
    py.plot(fig, filename='simple-plot-from-csv')

    return render_template('plot.html', title="Dashboard")
Exemple #22
0
    def metrics_table(self):

        # AUC score
        lb = preprocessing.LabelBinarizer()
        lb.fit(self.y_test)
        y_test_roc = lb.transform(self.y_test)
        y_pred_roc = lb.transform(self.y_pred)
        auc = roc_auc_score(y_test_roc, y_pred_roc, average="macro").round(2)

        # MAE
        mae = mean_absolute_error(self.y_test, self.y_pred).round(2)
        # MSE
        mse = mean_squared_error(self.y_test, self.y_pred).round(2)

        # Accuracy
        accuracy = accuracy_score(self.y_test, self.y_pred).round(2)

        # matthews_corrcoef
        matthews_corrcoe = matthews_corrcoef(self.y_test, self.y_pred).round(2)

        # Make DataFrames
        metric = [
            'Accuracy', 'Area Under Curve', 'MAE', 'MSE', 'Matthews Corrcoef'
        ]
        values = [accuracy, auc, mae, mse, matthews_corrcoe]
        metrics_tab = pd.DataFrame({'metric': metric, 'values': values})

        fig_metrics_table = ff.create_table(metrics_tab, height_constant=15)

        return fig_metrics_table
    def get_plotly_path_combination_table(self,
                                          file_name='產品組合資訊表.html',
                                          df=None,
                                          w=None):
        '''畫產品組合資訊表
        df為dataframe,末尾一行為組合。
        w為權重
        '''
        path_plotly = self.path_dir_plotly_html + os.sep + file_name
        risk_free = 0.03
        std_year = df.std() * 50
        mean_year = df.pct_change().mean() * 50 - risk_free
        sharp_year = mean_year / std_year
        max_drawback = (df / df.cummax()).min()

        _temp = {
            i[0]: i[1]
            for i in zip(['風險', '均值', 'sharp比', '最大回撤'],
                         [std_year, mean_year, sharp_year, max_drawback])
        }
        df_info = pd.concat(_temp, axis=1).T
        df_info.index.name = '指標'
        df_info = df_info.round(decimals=3)
        table = ff.create_table(df_info, index=True, index_title='指標')

        pyof.plot(table, filename=path_plotly, auto_open=False)
        return path_plotly
Exemple #24
0
    def actuals(self):

        cnf_matrix = confusion_matrix(self.y_test, self.y_pred)

        FP = cnf_matrix.sum(axis=0) - np.diag(cnf_matrix)
        FN = cnf_matrix.sum(axis=1) - np.diag(cnf_matrix)
        TP = np.diag(cnf_matrix)
        TN = cnf_matrix.sum() - (FP + FN + TP)
        fp = FP.astype(float).sum().round()
        fn = FN.astype(float).sum().round()
        tp = TP.astype(float).sum().round()
        tn = TN.astype(float).sum().round()

        total = tn + fn + fp + tp

        predicted_no = [tn, fn]
        predicted_yes = [fp, tp]

        data = {'Predicted No': predicted_no, 'Predicted Yes': predicted_yes}

        # Creates pandas DataFrame.
        df = pd.DataFrame(data, index=['No', 'Yes'])
        df['Total'] = df.sum(axis=1)
        df.loc['Total', :] = df.sum(axis=0)
        df.reset_index(inplace=True)
        df.rename({"index": 'Actual'}, axis=1, inplace=True)

        actuals_table = ff.create_table(df, height_constant=15)

        return actuals_table
Exemple #25
0
    def plot_qc_metrics_table(self,
                              id,
                              qc_metrics_summary_list,
                              title="QC Metrics Summary",
                              section_name=None,
                              description=None,
                              helptext=None):
        fig = ff.create_table(qc_metrics_summary_list, height_constant=60)

        html = plotly_plot(
            fig, {
                'id': id + '_plot',
                'data_id': id + '_data',
                'title': title,
                'auto_margin': True
            })

        # Add a report section with the scatter plot
        self.add_section(
            name='QC Metrics Summary',
            anchor=id + '_anchor',
            description=description if description else
            'Performance metrics and thresholds using reference RNAs',
            helptext=helptext if helptext else '''
            This longer description explains what exactly the numbers mean
            and supports markdown formatting. This means that we can do _this_:

            * Something important
            * Something else important
            * Best of all - some `code`

            Doesn't matter if this is copied from documentation - makes it
            easier for people to find quickly.
            ''',
            plot=html)
Exemple #26
0
def plotly_describes(data: list, names: list = [], width: int = 900, height: int = 700, save: bool = False, filename: str = 'Descriptive Statistics'):
    '''Docstring of `plotly_describes`

    Plot a table of descriptive statistics of given data with plotly.

    Args:
        data: A list of numerical data.
        names: A list contains names corresponding to data.
        save: Whether to save the plot or not.
        filename: Save the plot with this name.
    '''
    ndata = len(data)
    names = names or ['']*ndata
    describes = np.empty((12, ndata+1), dtype=object)
    for i, d, n in zip(range(ndata), data, names):
        des = advanced_describe(d, name=n)
        if i == 0:
            describes[0, 0] = 'Describes'
            describes[1:, 0] = des[2:, 0]
        describes[0, i+1] = des[0, 1]
        describes[1:, i+1] = [int(v*10000)/10000 for v in des[2:, 1]]
    fig = ff.create_table(describes, index=True)
    fig.layout.width = width
    fig.layout.height = height
    save and plt.plot(fig, filename=filename+'.html', auto_open=False)
    plt.iplot(fig)
Exemple #27
0
def update_hudunits(value, gvalue):
    if gvalue == 'counties':
        data = countydata
    else:
        data = placedata

    if "Puerto Rico" not in value:
        h1 = data[data['NAME'] == value]

        h2 = h1[[
            'Project Based Section 8', 'Housing Choice Vouchers',
            'Public Housing', '202/PRAC', '811/PRAC', 'Mod Rehab', 'S236/BMIR',
            'RentSup/RAP', 'LIHTC Units'
        ]]
        h2.columns = [
            'Public Housing Units', 'Houcing Choice Voucher Recipients',
            'Mod Rehab Units', 'Project Based Voucher Units',
            'RenSup/RAP Units', 'S236/BMIR Units', '202/PRAC Units',
            '811/PRAC Units', 'LIHTC Units'
        ]
        h2 = h2.transpose()
        h2 = h2.reset_index()

        h2.columns = ['HUD Assisted Units/Households ', '']
        h2 = h2[h2[''] > 0]
        h2[''] = h2[''].apply(lambda x: "{:,}".format(round(x)))

        fig4 = ff.create_table(h2)
        return fig4

    else:
        return no_data_fig
Exemple #28
0
def update_units_vacancy(value, gvalue):
    if gvalue == 'counties':
        data = countydata
    else:
        data = placedata

    units = data[data['NAME'] == value]
    units = units[[
        'Vacant Housing Units', 'Homeowner Vacancy Rate',
        'Rental Vacancy Rate', 'Homeownership Rate', 'Rental Rate'
    ]]
    units['Vacant Housing Units'] = units.apply(
        lambda x: "{:,}".format(round(x['Vacant Housing Units'])), axis=1)
    units['Homeowner Vacancy Rate'] = units.apply(
        lambda x: "{:.1%}".format(float(x['Homeowner Vacancy Rate'])), axis=1)
    units['Rental Vacancy Rate'] = units.apply(
        lambda x: "{:.1%}".format(float(x['Rental Vacancy Rate'])), axis=1)
    units['Homeownership Rate'] = units.apply(
        lambda x: "{:.1%}".format(float(x['Homeownership Rate'])), axis=1)
    units['Rental Rate'] = units.apply(
        lambda x: "{:.1%}".format(float(x['Rental Rate'])), axis=1)
    units = units.transpose()
    units.columns = [' ']
    dff_cols = [
        'Vacant Housing Units', 'Homeowner Vacancy Rate',
        'Rental Vacancy Rate', 'Homeownership Rate', 'Rental Rate'
    ]
    units.insert(0, 'Vacancy and Tenure Rates', dff_cols, True)
    fig3 = ff.create_table(units)
    fig3.layout.autosize == 'true'

    return fig3
Exemple #29
0
def model_performance(model):
    X_train, X_test, y_train, y_test = train_test_split(X,
                                                        y,
                                                        test_size=0.3,
                                                        random_state=120)
    result = model.fit(X_train, y_train)

    predictions = model.predict(X_test)
    accuracy = accuracy_score(y_test, predictions)
    recallscore = recall_score(y_test, predictions)
    precision = precision_score(y_test, predictions)
    roc_auc = roc_auc_score(y_test, predictions)
    f1score = f1_score(y_test, predictions)
    kappa_metric = cohen_kappa_score(y_test, predictions)

    df = pd.DataFrame({
        "Accuracy_score": [accuracy],
        "Recall_score": [recallscore],
        "Precision": [precision],
        "f1_score": [f1score],
        "Area_under_curve": [roc_auc],
        "Kappa_metric": [kappa_metric]
    })

    model_performance = pd.concat([df], axis=0).reset_index()
    model_performance = model_performance.drop(columns="index", axis=1)
    table = ff.create_table(np.round(model_performance, 5))
    py.iplot(table)
Exemple #30
0
def createTable():
    table_data = []
    table_data.append([
        'City', 'Commercial Rate', 'Residential Rate', 'Industrial Rate',
        'Average Rate'
    ])
    index = 0
    for city in cities:
        city_state = city.capitalize() + ', ' + cities[city].capitalize()
        city_state.replace('-', ' ')
        table_data.append([
            city_state,
            str(com_rates[index] + ' ¢/kWh'),
            str(res_rates[index] + ' ¢/kWh'),
            str(ind_rates[index] + ' ¢/kWh'),
            str(avg_rates[index] + ' ¢/kWh')
        ])
        index += 1

    # Init a figure
    colorscale = [[0, '#8B5600'], [.5, '#FFEB60'], [1, '#ffffff']]
    figure = FF.create_table(table_data, colorscale=colorscale)
    figure.layout.width = 1000
    #figure.layout.update({'title': 'Electricity rates in ¢/kWh'})

    # Make text size larger
    for i in range(len(figure.layout.annotations)):
        figure.layout.annotations[i].font.size = 16

    py.iplot(figure, filename='electricity-table-rates')
Exemple #31
0
    def get_plotly_path_combination_table(self,file_name='产品组合信息表.html',df=None,w=None):
        '''画产品组合信息表
        df为dataframe,末尾一列为组合。
        w为权重
        '''
        path_plotly = self.path_dir_plotly_html + os.sep + file_name
        risk_free = 0.03
        std_year = df.std() * 50
        mean_year = df.pct_change().mean() * 50 - risk_free
        sharp_year = mean_year / std_year
        max_drawback = (df / df.cummax()).min()

        _temp = {i[0]: i[1] for i in zip(['风险', '均值', '夏普比', '最大回撤'], [std_year, mean_year, sharp_year, max_drawback])}
        df_info = pd.concat(_temp, axis=1).T
        df_info.index.name = '指标'
        df_info = df_info.round(decimals=3)
        table = ff.create_table(df_info, index=True, index_title='指标')


        pyof.plot(table, filename=path_plotly, auto_open=False)
        return path_plotly
Exemple #32
0
 def create_table(*args, **kwargs):
     FigureFactory._deprecated('create_table')
     from plotly.figure_factory import create_table
     return create_table(*args, **kwargs)