def plot_graph_wrapper(df, title='', xTitle='', yTitle='',
                       filename='output.html'):
    """Cufflink offline plot for easy viewing"""
    cf.set_config_file(offline=True, world_readable=True, theme='ggplot')
    cf_output = df.iplot(kind='scatter', title=title, xTitle=xTitle,
                         online=False, asFigure=True)
    py.offline.plot(cf_output, filename=filename)
Esempio n. 2
0
def interactive_charts(df: pd.DataFrame, x: str, y: str, kind: str):
    # https://github.com/santosjorge/cufflinks/blob/master/Cufflinks%20Tutorial%20-%20Pandas%20Like.ipynb
    import plotly.offline
    import cufflinks as cf
    cf.go_offline()
    cf.set_config_file(offline=False, world_readable=True)
    df.iplot(x=x, y=y, kind=kind)
Esempio n. 3
0
def get_data_view(limit):

    data = pd.read_csv('forbes.csv')
    regions_available = list(data.values)
    cf.set_config_file(offline=True, theme="ggplot")
    py.offline.init_notebook_mode()
    N = pd.read_csv('forbes.csv',
                    encoding="utf8",
                    keep_default_na=False,
                    na_values='na_rep')
    N.head()

    # Count crime numbers in each neighborhood
    limit = 100
    data5 = N.iloc[0:limit, :]
    print(data5)
    input()

    # disdata5 = pd.DataFrame(data['行业'].value_counts())
    # disdata5.reset_index(inplace=True)
    # disdata5.rename(
    #     columns={'index': '分类', 'PdDistrict': 'Count'}, inplace=True)
    # print(disdata5)
    # input()

    limit = 20
    data4 = N.iloc[0:limit, :]
    print(data4)
    input()
Esempio n. 4
0
def IV_final_2020():
    Locality_available = list(df.Year.dropna().unique())
    cf.set_config_file(offline=True, theme="ggplot")
    py.offline.init_notebook_mode()
    data_str = df.to_html()
    return render_template('results3.html',
                           the_res = data_str,
                           the_select_region=Locality_available)
Esempio n. 5
0
def area_situation():
    Year_available = list(df.Year.dropna().unique())
    cf.set_config_file(offline=True, theme="ggplot")
    py.offline.init_notebook_mode()
    data_str = df[:30].to_html()
    return render_template('area_situation.html',
                           the_res = data_str,
                           the_select_Year=Year_available)
Esempio n. 6
0
def zm_qwm():
    df4 = pd.read_csv('G.csv', encoding='gbk')
    zb_available = list(df4.指标.dropna().unique())
    cf.set_config_file(offline=True, theme="ggplot")
    py.offline.init_notebook_mode()
    data_str = df4.to_html()
    return render_template('zm_qwm.html',
                           the_res=data_str,
                           the_select_year=zb_available)
Esempio n. 7
0
def ge_data():
    df2 = pd.read_csv('F.csv', encoding='gbk')
    year_available = list(df2.年份.dropna().unique())
    cf.set_config_file(offline=True, theme="ggplot")
    py.offline.init_notebook_mode()
    data_str = df2.to_html()
    return render_template('ge_data.html',
                           the_res=data_str,
                           the_select_year=year_available)
Esempio n. 8
0
def histog(data):
	
	cf.set_config_file(offline=False, world_readable=True, theme='pearl')

	df = pd.DataFrame({'Distances': data})

	df.head(2)

	df.iplot(kind='histogram', subplots=True, shape=(3, 1), filename='cufflinks/histogram-subplots')
Esempio n. 9
0
def zd_jr():
    df = pd.read_csv('junfeizhanbi.csv', encoding='gbk')
    jf_available = ['高收入国家','低收入国家'] # 列表下拉值赋予给regions_available
    cf.set_config_file(offline=True, theme="ggplot")
    py.offline.init_notebook_mode()
    data_str = df[:40].to_html()
    return render_template('zd_jf.html',
                           the_select_jf=jf_available,
                           the_res = data_str)
Esempio n. 10
0
def plot_timeseries_with_bound(df,
                               val_col,
                               bound_col,
                               true_col,
                               xTitle='',
                               yTitle='',
                               title='',
                               filename='LSTM_output_bounds.html'):
    cf.set_config_file(offline=True, world_readable=True, theme='ggplot')
    #    cf_output = df.iplot(kind='scatter', title=title, xTitle=xTitle,
    #                         online=False, asFigure=True)

    upper_bound = go.Scatter(
        name='Upper Bound',
        #x=df['Time'],
        y=df[val_col] + df[bound_col],
        mode='lines',
        marker=dict(color="444"),
        line=dict(width=0),
        fillcolor='rgba(68, 68, 68, 0.3)',
        fill='tonexty')

    trace = go.Scatter(
        name='Measurement',
        #x=df['Time'],
        y=df[val_col],
        mode='lines',
        line=dict(color='rgb(31, 119, 180)'),
        fillcolor='rgba(68, 68, 68, 0.3)',
        fill='tonexty')

    lower_bound = go.Scatter(
        name='Lower Bound',
        #x=df['Time'],
        y=df[val_col] - df[bound_col],
        marker=dict(color="444"),
        line=dict(width=0),
        mode='lines')

    true_line = go.Scatter(
        name='Actual',
        #x=df['Time'],
        y=df[true_col],
        mode='lines',
        line=dict(color='rgb(180, 119, 180)'),
        fillcolor='rgba(68, 68, 68, 0.3)',
        fill='lines')

    # Trace order can be important
    # with continuous error bars
    data = [lower_bound, trace, upper_bound, true_line]

    layout = go.Layout(yaxis=dict(title=yTitle), title=title, showlegend=True)
    fig = go.Figure(data=data, layout=layout)

    py.offline.plot(fig, filename=filename)
Esempio n. 11
0
def map1() -> 'html':
    Year_available = list(df.Year.dropna().unique())
    cf.set_config_file(offline=True, theme="ggplot")
    py.offline.init_notebook_mode()
    the_Year = request.form["the_Year_selected"]
    dfs = df.query("Year=='{}'".format(the_Year))
    State = list(dfs['State'].unique())
    State.remove('United States')
    p = []
    z = []
    for st in State:
        df4 = dfs[dfs.State == st]
        z.append(sum(df4['Death_Rate']))
        p.append(sum(df4['Population']))

    fig = go.Figure(data=go.Choropleth(
    locations=State,  # Spatial coordinates
    z=z,  # Data to be color-coded
    locationmode='USA-states',  # set of locations match entries in `locations`
    colorscale='Reds',
    colorbar_title="人数",
    ))

    fig.update_layout(
        title_text='1999-2017年美国各州的药物中毒人数地图可视化',
        geo_scope='usa',  # limite map scope to USA
    )

    py.offline.plot(fig, filename="us.html", auto_open=False)
    with open("us.html", encoding="utf8", mode="r") as f:
        plot_all2 = "".join(f.readlines())

    fig = go.Figure(data=go.Choropleth(
    locations=State,  # Spatial coordinates
    z=p,  # Data to be color-coded
    locationmode='USA-states',  # set of locations match entries in `locations`
    colorscale='Reds',
    colorbar_title="人数",
    ))

    fig.update_layout(
        title_text='1999-2017年美国各州的人数地图可视化',
        geo_scope='usa',  # limite map scope to USA
    )

    py.offline.plot(fig, filename="us.html", auto_open=False)
    with open("us.html", encoding="utf8", mode="r") as f:
        plot_all3 = "".join(f.readlines())

    data_str = dfs[:30].to_html()
    return render_template('area_situation.html',
                           the_plot_all2 = plot_all2,
                           the_plot_all3 = plot_all3,
                            the_res = data_str,
                            the_select_Year=Year_available,
                           )
Esempio n. 12
0
def hr():
    df = pd.read_csv('hurun.csv', encoding='utf-8', delimiter="\t")
    # df = df.set_index('Index')
    regions_available = list(df.region.dropna().unique())
    cf.set_config_file(offline=True, theme="ggplot")
    py.offline.init_notebook_mode()
    data_str = df.to_html(classes='table align-items-center table-flush')
    return render_template('layouts/default.html',
                           content=render_template('pyecharts/index.html',
                                                   the_res=data_str))
Esempio n. 13
0
 def show_graph(self):
     cf.set_config_file(sharing='public', theme='pearl', offline=False)
     cf.go_offline
     init_notebook_mode(connected=True)
     df = pd.DataFrame({'Activity': self.graphActivityData},
                       index=self.graphTimeData)
     #df.head()
     print(df)
     print("bfr")
     df.plot()
     print("afr")
Esempio n. 14
0
def trend_situation():
    Race_available = list(df.Race.dropna().unique())  # 列表下拉值赋予给regions_available
    cf.set_config_file(offline=True, theme="ggplot")
    py.offline.init_notebook_mode()
    data_str = df[:30].to_html()
    def line_markline2() -> Line:
        df = pd.read_csv('Mortality_States.csv')
        time = list(df['Year'].unique())
        times = []
        for t in list(time):
            times.append(str(t))

        Race1 = list(df['Race'].unique())
        r2 = []
        for r in Race1:
            df5 = df[df.Race == r]
            r1 = []
            r2.append(r1)
            for t in time:
                df6 = df5[df5.Year == t]
                r1.append(int(sum(df6['Death_Rate'])))
        c = (
            Line()
                .add_xaxis(times)
                .add_yaxis(
                "All Races-All Origins",
                r2[0],
                markline_opts=opts.MarkLineOpts(data=[opts.MarkLineItem(type_="average")]),
            )
                .add_yaxis(
                "Hispanic",
                r2[1],
                markline_opts=opts.MarkLineOpts(data=[opts.MarkLineItem(type_="average")]),
            )
                .add_yaxis(
                "Non-Hispanic Black",
                r2[2],
                markline_opts=opts.MarkLineOpts(data=[opts.MarkLineItem(type_="average")]),
            )
                .add_yaxis(
                "Non-Hispanic White",
                r2[3],
                markline_opts=opts.MarkLineOpts(data=[opts.MarkLineItem(type_="average")]),
            )
                .set_global_opts(title_opts=opts.TitleOpts(title="种族药物中毒死亡率"))
        )
        return c
    line_markline2().render()
    with open("render.html", encoding="utf8", mode="r") as f:
        plot_all2 = "".join(f.readlines())
    return render_template('trend_situation.html',
                           the_plot_all2=plot_all2,
                           the_res = data_str,
                           the_select_Race=Race_available)
 def __init__(self, upid):
     cf.set_config_file(world_readable=True,
                        theme='henanigans',
                        offline=True)
     cf.go_offline()
     self.mongo_persist = MongoPersist()
     self.upid = upid
     data_dict = self.mongo_persist.read("up_video_list", {"mid": upid})
     self.df_data = pd.DataFrame(data_dict)
     self.df_data['created'] = pd.to_datetime(self.df_data['created'],
                                              unit='s')
Esempio n. 16
0
 def __init__(self, db):
     self.db = db
     if isinstance(self.db, dict):
         self.materials = RecursiveDict()
         self.compositions = RecursiveDict()
     else:
         import plotly.plotly as py
         import cufflinks
         cufflinks.set_config_file(world_readable=True, theme='pearl')
         opts = bson.CodecOptions(document_class=bson.SON)
         self.contributions = self.db.contributions.with_options(codec_options=opts)
         self.materials = self.db.materials.with_options(codec_options=opts)
         self.compositions = self.db.compositions.with_options(codec_options=opts)
Esempio n. 17
0
def plot_chart(path_to_png, path_to_log_list):
    print(path_to_png[0:-4] + ".html")
    output_file(path_to_png[0:-4] + ".html")
    TOOLS = 'pan,box_zoom,wheel_zoom,save,hover,reset,resize'
    p = figure(title="TrainLoss(smoothed) vs NumIters",
               x_axis_label='NumIters')
    fig, ax1 = plt.subplots()

    cf.set_config_file(offline=False, world_readable=True, theme='ggplot')
    for path_to_log in path_to_log_list:
        os.system('%s %s ./ ' % (get_log_parsing_script(), path_to_log))
        data_file = get_data_file(6, path_to_log)
        pddata = pd.read_csv(data_file)
        standard = ['NumIters', 'Seconds', 'LearningRate']
        labels = [label for label in pddata if label not in standard]
        sp = 500 if len(pddata['NumIters']) > 2000 else 5
        skip = 5 if len(pddata['NumIters']) > 2000 else 0
        ylims = [100, -100]
        data = []
        for label, i in zip(labels, range(len(labels))):
            Y = pddata[label].ewm(span=sp, adjust=True).mean()
            plt.plot(pddata["NumIters"], Y, alpha=0.4)
            ylims[0] = min(ylims[0], Y[skip:].min())
            ylims[1] = max(ylims[1], Y[skip:].max())
            data += [go.Scattergl(x=pddata["NumIters"], y=Y, name=label)]
            # p.line(pddata["NumIters"], Y, legend=label,
            #         color=Spectral11[i%11], line_width=2)
        print(int(pddata["NumIters"].iloc[-1]))
        plt.legend()

        ax1.set_ylim(ylims)
        # p.extra_y_ranges = {"LearningRate": Range1d(start=0, end=pddata['LearningRate'].max()*1.1)}
        # p.add_layout(LinearAxis(y_range_name="LearningRate"), 'right')
        # p.line(pddata["NumIters"],
        #        pddata['LearningRate'],
        #        legend='LearningRate',
        #        color='navy', y_range_name="LearningRate")
        # p.add_layout(LinearAxis(y_range_name="LearningRate"), 'left')
    # save(p)
    # ax2 = ax1.twinx()
    # ax2.plot(pddata["NumIters"], pddata['LearningRate'], alpha=0.4)
    plt.title('TrainLoss vs NumIters')
    # ax2.set_ylabel('Learning Rate', color='r')
    plt.xlabel('NumIters')
    plt.savefig(path_to_png)
    url = py.plot(data, filename=path_to_png[0:-4], fileopt='overwrite')
    print(url)
Esempio n. 18
0
def plot_hist(ds, user_id: str, x_axis_column=None):
    """
    histogram plot of timeseries data

    Args:
        ds (DataStream):
        user_id (str): uuid of a user
        x_axis_column (str): x axis column of the plot
    """

    pdf = ds_to_pdf(ds, user_id)
    cf.set_config_file(offline=True, world_readable=True, theme='ggplot')
    init_notebook_mode(connected=True)
    pdf = _remove_cols(pdf)
    if x_axis_column:
        data = [go.Histogram(x=pdf[str(x_axis_column)])]
        iplot(data, filename='basic histogram')
    else:
        pdf.iplot(kind='histogram', filename='basic histogram')
Esempio n. 19
0
    def plot(self, traces=None):
        try:
            import cufflinks as cf
            cf.set_config_file(offline=True, theme='white')

            if traces is None:
                traces = self.data.columns.drop(TIMESTAMP).tolist()

            if not isinstance(traces, Iterable):
                traces = [traces]

            self.data.iplot(x=TIMESTAMP,
                            y=traces,
                            mode='markers+lines',
                            symbol="x",
                            size=5,
                            width=.5,
                            zerolinecolor="black")
        except ImportError as exc:
            logger.exception("It appears there was a problem during plotting.")
Esempio n. 20
0
def map() -> 'html':
    Locality_available = list(df.Year.dropna().unique())
    cf.set_config_file(offline=True, theme="ggplot")
    py.offline.init_notebook_mode()
    the_region = request.form["the_region_selected"]
    dfs = df.query("Year=='{}'".format(the_region))
    State = list(dfs['State'].unique())
    State.remove('United States')
    z = []
    for st in State:
        df4 = dfs[dfs.State == st]
        z.append(sum(df4['Potentially Excess Deaths'][(df['Locality'] == 'All')][(df['Cause of Death'] == 'Stroke')]))

    fig = go.Figure(data=go.Choropleth(
    locations=State,  # Spatial coordinates
    z=z,  # Data to be color-coded
    locationmode='USA-states',  # set of locations match entries in `locations`
    colorscale='Reds',
    colorbar_title="人数",
    ))

    fig.update_layout(
        title_text='2005-2015年美国各州中风潜在死亡人数',
        geo_scope='usa',  # limite map scope to USA
    )

    py.offline.plot(fig, filename="us.html", auto_open=False)
    with open("us.html", encoding="utf8", mode="r") as f:
        plot_all2 = "".join(f.readlines())

    #with open("render1.html", encoding="utf8", mode="r") as f:
        #plot_all3 = "".join(f.readlines())


    data_str = df.to_html()

    return render_template('results3.html',
                           the_plot_all2 = plot_all2,
                            the_res = data_str,
                            the_select_region=Locality_available,
                           )
Esempio n. 21
0
def interactive_results(y_train, y_train_pred, y_test, y_test_pred):
    pio.renderers.default = 'colab'
    cf.set_config_file(theme='pearl')
    fig = make_subplots(rows=2, cols=1, shared_xaxes=False)

    enum_x_train = list(range(len(y_train)))
    enum_x_test = list(range(len(y_test)))

    fig.append_trace(
        {
            'x': enum_x_train,
            'y': y_train,
            'type': 'scatter',
            'name': 'Real | Train'
        }, 1, 1)
    fig.append_trace(
        {
            'x': enum_x_train,
            'y': y_train_pred,
            'type': 'scatter',
            'opacity': 0.7,
            'name': 'Predicted | Train'
        }, 1, 1)
    fig.append_trace(
        {
            'x': enum_x_test,
            'y': y_test,
            'type': 'scatter',
            'name': 'Real | Test'
        }, 2, 1)
    fig.append_trace(
        {
            'x': enum_x_test,
            'y': y_test_pred,
            'type': 'scatter',
            'opacity': 0.7,
            'name': 'Predicted | Test'
        }, 2, 1)
    #fig['layout'].update(title=title+ ' | RMSE: '+str(RMSE))
    iplot(fig)
Esempio n. 22
0
def plot_plotly(df):
    """
    pip install plotly # Plotly is a pre-requisite before installing cufflinks
pip install cufflinks

    #importing Pandas
import pandas as pd
#importing plotly and cufflinks in offline mode
import cufflinks as cf
import plotly.offline
cf.go_offline()
cf.set_config_file(offline=False, world_readable=True)


    :param df:
    :return:
    """
    import cufflinks as cf
    import plotly.offline

    cf.go_offline()
    cf.set_config_file(offline=False, world_readable=True)
    df.iplot()
Esempio n. 23
0
def plot_timeseries(ds: DataStream, user_id: str, y_axis_column: str = None):
    """
    line plot of timeseries data

    Args:
        ds (DataStream):
        user_id (str): uuid of a user
        y_axis_column (str): x axis column is hard coded as timestamp column. only y-axis can be passed as a param
    """
    pdf = ds_to_pdf(ds, user_id)
    cf.set_config_file(offline=True, world_readable=True, theme='ggplot')
    init_notebook_mode(connected=True)
    ts = pdf['timestamp']
    pdf = _remove_cols(pdf)
    if y_axis_column:
        data = [go.Scatter(x=ts, y=pdf[str(y_axis_column)])]
        iplot(data, filename='time-series-plot')
    else:
        iplot([{
            'x': ts,
            'y': pdf[col],
            'name': col
        } for col in pdf.columns],
              filename='time-series-plot')
Esempio n. 24
0
def zd_jr_response() -> 'html':
    jf_available = ['高收入国家','低收入国家']  # 列表下拉值赋予给regions_available
    cf.set_config_file(offline=True, theme="ggplot")
    py.offline.init_notebook_mode()
    the_jf = request.form["the_jf_selected"]
    dfs = df.query("Country=='{}'".format(the_jf))

    # 数据循环模块
    def line_markline() -> Line:
        a = []
        times = []
        for i in range(1960, 2018):
            a.append(int(int(dfs[str(i)]) / 100000000))
            times.append(str(i))
        c = (
            Line()
                .add_xaxis(times)
                .add_yaxis(
                "{}".format(the_jf),
                a,
                markline_opts=opts.MarkLineOpts(data=[opts.MarkLineItem(type_="average")]),
            )

                .set_global_opts(title_opts=opts.TitleOpts(title="{}军费占比趋势".format(the_jf)))
        )
        return c

    line_markline().render()
    with open("render.html", encoding="utf8", mode="r") as f:
        plot_all = "".join(f.readlines())
    data_str = dfs[:40].to_html()
    return render_template('zd_jf.html',
                            the_plot_all=plot_all,
                            the_res = data_str,
                            the_select_jf=jf_available,
                           )
Esempio n. 25
0
git show HEAD^:presentation.pptx > temp.pptx #ひとつ前のコミットを別ファイルとして取りだし+-
git add -A 全ての変更をステージング
git commit -m "コメント" ステージングした変更をコミット
git push リモートに反映

git reset --soft "HEAD^"  コミットの削除 --softは変更はそのままにするという意味

"""
#---------------------------辞書 dict ------------------------------------
d = {}
d['k3'] = 3
#---------------------------import lib library------------------------------------
%matplotlib inline
import pandas as pd
import cufflinks as cf
cf.set_config_file(offline=True, theme="white", offline_show_link=False)
cf.go_offline()
"""
ライブラリのリロード
"""
import importlib
importlib.reload(foo)

"""
inf弾く
"""
import numpy as np
df.replace([np.inf, -np.inf], np.nan)


"""
Esempio n. 26
0
#     from jupyter_dash import JupyterDash
# except:
#     import os
#     os.system("conda install -c conda-forge -c plotly jupyter-dash")
#     from jupyter_dash import JupyterDash

## PLOTLY IMPORTS/PARAMS
import plotly.express as px
import plotly.graph_objects as go
import plotly.io as pio
pio.templates.default = "plotly_dark"

## Acitvating Cufflinks
import cufflinks as cf
cf.go_offline()
cf.set_config_file(sharing='public', theme='solar', offline=True)

## Importing Dash
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output

## Load Functions and Data
from functions import CoronaData, plot_states, get_state_ts, plot_group_ts

## LOAD DATA AND SAVE DFs
corona_data = CoronaData(verbose=False, run_workflow=True)
df = corona_data.df_us.copy()
df_world = corona_data.df.copy()
Esempio n. 27
0
hc.fit(mat)

labels = hc.labels_
results = pd.DataFrame([dfdif.T.index,labels])
display(results.loc[:0,results.iloc[1]==0])
display(results.loc[:0,results.iloc[1]==1])
display(results.loc[:0,results.iloc[1]==2])


# My controls are 
# * WT: I12, J12
# * KO: I13, J13
# * HET: I14, J14
# 
# So you can identify your genotyping results by looking at: to which control they cluster.

# Ploting with plot.ly, so you can look at individual lines for better pattern recognition
# In[ ]:
import plotly.plotly as py
import cufflinks as cf
import plotly.graph_objs as go

cf.set_config_file(offline=False, world_readable=True, theme='ggplot')

dfpy = dfdif.set_index(df_melt.iloc[:,0])

# Plot and embed in ipython notebook!
dfpy.iplot(kind='scatter', filename='pyHRM')


Esempio n. 28
0
import cufflinks as cf
import numpy as np
import pandas as pd
import plotly
import plotly.graph_objs as go
from plotly import tools

from UCB_MIDS_W205.Project.api.great_schools import GreatSchools
from UCB_MIDS_W205.Project.api.population import Population
from UCB_MIDS_W205.Project.data_models import Datamodel
from UCB_MIDS_W205.Project.mission_control import MissionControl
from UCB_MIDS_W205.Project.postgresql_handler import Postgresql

print(plotly.__version__)  # version 1.9.x required
plotly.offline.init_notebook_mode()  # run at the start of every notebook
cf.set_config_file(offline=True, world_readable=False)


class Plotter:
    def __init__(self, min_price=150000, max_price=300000, top_percentage=0.25, top_max_num_entries=30):
        self.MIN_PRICE = min_price
        self.MAX_PRICE = max_price
        self.TOP_PERCENTAGE = top_percentage
        self.TOP_MAX_NUM_ENTRIES = top_max_num_entries

        datamodel = Datamodel()
        self.time_series_postgres = self._initialize_postgres(datamodel.zipcode_timeseries())
        self.population_postgres = self._initialize_postgres(datamodel.population())
        self.great_schools_postgres = self._initialize_postgres(datamodel.great_schools())

        self.zipcode_timeseries = None
Esempio n. 29
0
import plotly as plty
import plotly.graph_objs as go
import cufflinks as cf

# Before using this, the following changes should be made to the offline.py file in the environment's plotly installation:
# * To get to plotly offline install, eg /Users/eczech/anaconda/envs/research3.5/lib/python3.5/site-packages/plotly/offline
# - Add the following lines to offline.py in _plot_html after the line "config = {}":
#   config['modeBarButtonsToRemove'] = ['sendDataToCloud'] # Added manually to remove save icon
#   config['displaylogo'] = False # Added manually to remove plotly icon
#
# After doing this, the extra cleaning logic in "plotly_clean_html" is no longer necessary but it is still left
# here because it is harmless otherwise and at least strips save icons from serialized plots if the manual edits
# above have not been made.

# Initialize Jupyter notebook mode
cf.set_config_file(offline=True, theme='white', offline_link_text=None, offline_show_link=False)

def plotly_clean_html(plotly_filename, auto_open=True):
    """ Strips Save icon from plot.ly html visualizations """

    # Read in source html for viz
    with open(plotly_filename, 'r') as of:
        html = of.read()

    # Replace the target strings (removes "Save" icon)
    html = html.replace('displaylogo:!0', 'displaylogo:!1')
    html = html.replace('modeBarButtonsToRemove:[]', 'modeBarButtonsToRemove:["sendDataToCloud"]')

    # Re-write source html
    with open(plotly_filename, 'w') as of:
        of.write(html)
Esempio n. 30
0
from plotly import tools
from plotly.offline.offline import _plot_html

import cufflinks as cf
import numpy as np
import pandas as pd
import plotly.graph_objs as go
import colorlover as cl

# local
from .episem import episem, lastepiday


cf.set_config_file(theme='white')


def ethio_ts(df=pd.DataFrame, scale_id=int, year=int):
    cols = [
        'Testes positivos',
        'Influenza A',
        'Influenza B',
        'VSR',
        'Adenovirus',
        'Parainfluenza 1',
        'Parainfluenza 2',
        'Parainfluenza 3',
    ]
    trace = []

    if scale_id == 2:
        ytitle = 'Casos'
import pandas as pd
import numpy as np
import csv
import os
import matplotlib.pyplot as plt
import cufflinks as cf
import plotly
import plotly.offline as py
from plotly.offline.offline import _plot_html
import plotly.graph_objs as go
from plotly.tools import FigureFactory as FF

cf.set_config_file(world_readable=False,offline=True)

plt.style.use('ggplot')
def plot(name, *, cols=[], plot_kind=None, start_date=None, end_date=None):
    """ Plots selected financial data of selected company which ranges over specified
    date range[start_date:end_date]. The plot is as specified by the plot_kind parameter.
    :param
          name: company's ticker
          cols: list of columns specifying data fields to plot.
          kind: type of plot. One of 'line', 'box', 'hexbin','scatter_matrix'.
          start_date: The data is indexed by the Date column. starting date specifies
                      the first date index row to be plotted.
          end_date: end_date specifies the last date index row to be plotted.
    """
    header = ['Date','Total Transactions','Traded Shares','TotalTraded Amount',
              'Maximum Price','Minimum Price','Closing Price']

    plottypes = ['line', 'box', 'hexbin','scatter_matrix']
import plotly.graph_objs as go
from plotly.offline import init_notebook_mode, iplot
import plotly.io as pio
pio.orca.config.executable = '/u/fs1/vatj2/.local/bin//orca'
pio.orca.config.save()

import pandas as pd
import numpy as np
from plotly.colors import DEFAULT_PLOTLY_COLORS
import cufflinks as cf
import itertools

# In[ ]:

init_notebook_mode(connected=True)
cf.set_config_file(offline=True)

figure_dir = os.path.join(os.getcwd(), '..', 'figures')
if not os.path.exists(figure_dir):
    os.mkdir(figure_dir)

data_dir = os.path.join(os.getcwd(), "..", "data", "V" + ipa.__version__)
if not os.path.exists(data_dir):
    os.mkdir(data_dir)

# In[ ]:

p = dict()

p["n_genes"] = 3
p["low_colour"] = 0
Esempio n. 33
0
import html

from flask import Flask, render_template, request
import pandas as pd
import cufflinks as cf
import plotly as py
import plotly.graph_objs as go

app = Flask(__name__)

# 准备工作
df = pd.read_csv('douban_movie.csv', encoding='utf-8', delimiter="\t")
cf.set_config_file(offline=True, theme="ggplot")
regions_available = list(df.concluding.dropna().unique())



print(regions_available) # 读取数据确认


@app.route('/',methods=['GET'])
def douban_2019():
    data_str = df.to_html()
    return render_template('results.html',
                           the_res = data_str,
                           the_select_region=regions_available,

                           )
    # 初始表格置入选择

Esempio n. 34
0
def plot_model(model, plot='2d'):
    """
      
    Description:
    ------------
    This function takes a model dataframe returned by create_model() function. 
    '2d' and '3d' plots are available.

        Example:
        --------
        
        rule1 = create_model(metric='confidence', threshold=0.7, min_support=0.05)
        plot_model(rule1, plot='2d')
        plot_model(rule1, plot='3d')

    Parameters
    ----------

    model : DataFrame, default = none
    DataFrame returned by trained model using create_model(). 

    plot : string, default = '2d'
    Enter abbreviation of type of plot. The current list of plots supported are:

    Name                                 Abbreviated String     
    ---------                            ------------------     
    Support, Confidence and Lift (2d)    '2d'
    Support, Confidence and Lift (3d)    '3d'
  
    
    Returns:
    --------

    Visual Plot:  Prints the visual plot. 
    ------------
    
    """

    #loading libraries
    import numpy as np
    import pandas as pd
    import plotly.express as px
    from IPython.display import display, HTML, clear_output, update_display

    #import cufflinks
    import cufflinks as cf
    cf.go_offline()
    cf.set_config_file(offline=False, world_readable=True)

    #copy dataframe
    data_ = model.copy()

    antecedents = []
    for i in data_['antecedents']:
        i = str(i)
        a = i.split(sep="'")
        a = a[1]
        antecedents.append(a)

    data_['antecedents'] = antecedents

    antecedents_short = []

    for i in antecedents:
        a = i[:10]
        antecedents_short.append(a)

    data_['antecedents_short'] = antecedents_short

    consequents = []
    for i in data_['consequents']:
        i = str(i)
        a = i.split(sep="'")
        a = a[1]
        consequents.append(a)

    data_['consequents'] = consequents

    if plot == '2d':

        fig = px.scatter(
            data_,
            x="support",
            y="confidence",
            text="antecedents_short",
            log_x=True,
            size_max=600,
            color='lift',
            hover_data=['antecedents', 'consequents'],
            opacity=0.5,
        )

        fig.update_traces(textposition='top center')
        fig.update_layout(plot_bgcolor='rgb(240,240,240)')

        fig.update_layout(height=800,
                          title_text='2D Plot of Support, Confidence and Lift')

        fig.show()

    if plot == '3d':

        fig = px.scatter_3d(data_,
                            x='support',
                            y='confidence',
                            z='lift',
                            color='antecedent support',
                            title='3d Plot for Rule Mining',
                            opacity=0.7,
                            width=900,
                            height=800,
                            hover_data=['antecedents', 'consequents'])
        fig.show()
Esempio n. 35
0
"""
If you want to make a plot, change the folder name 
after installing plotly,cufflink and run the following code.
folder_name='new_results'
"""
import pandas as pd
import os, time
import glob
import cufflinks as cf
import plotly.offline
cf.go_offline()
cf.set_config_file(offline=True, world_readable=True)
import torchvision.models as models
MODEL_LIST = {
    'mnasnet': models.mnasnet.__all__[1:],
    'resnet': models.resnet.__all__[1:],
    'densenet': models.densenet.__all__[1:],
    'squeezenet': models.squeezenet.__all__[1:],
    'vgg': models.vgg.__all__[1:],
    #'mobilenet':[m for m in models.mobilenet.__all__[1:] if m.islower()],
    'mobilenet': ['mobilenet_v2', 'mobilenet_v3_large', 'mobilenet_v3_small'],
    'shufflenetv2': models.shufflenetv2.__all__[1:]
}
setattr(plotly.offline, "__PLOTLY_OFFLINE_INITIALIZED", True)
folder_name = 'result/'
csv_list = glob.glob(folder_name + '/*.csv')
columes = []
for key, values in MODEL_LIST.items():
    for i in values:
        columes.append((key, i))
for csv in csv_list:
Esempio n. 36
0
from plotly.offline.offline import _plot_html

import cufflinks as cf
import pandas as pd

cf.set_config_file(theme='pearl', offline=True)


class ReportCityCharts:
    @classmethod
    def create_incidence_chart(
        cls, df: pd.DataFrame, year_week: int, threshold_pre_epidemic: float,
        threshold_pos_epidemic: float, threshold_epidemic: float
    ) -> 'Plotly_HTML':
        """

        @see: https://stackoverflow.com/questions/45526734/
            hide-legend-entries-in-a-plotly-figure

        :param df:
        :param year_week:
        :param threshold_pre_epidemic: float,
        :param threshold_pos_epidemic: float
        :param threshold_epidemic: float
        :return:
        """
        df = df.reset_index()[[
            'SE', 'incidência', 'casos notif.', 'level_code'
        ]]

        # 200 = 2 years