Example #1
0
    def Plot_Gantt_Chart(self):
        # ------------------------------- Ploting the results by using Plotly Gantt Chart ---------------------------------------------- #
        print(
            f'{"The shape of the OutputData_Of_Lines:  "}{self.OutputData_Of_Lines.shape[0]}'
        )
        color_dict = dict(
            zip(self.OutputData_Of_Lines.Resource.unique(), [
                'rgb({},{},{})'.format(i[0], i[1], i[2]) for i in list(
                    np.random.randint(255,
                                      size=(len(self.OutputData_Of_Lines.
                                                Resource.unique()), 3)))
            ]))
        fig = ff.create_gantt(
            self.OutputData_Of_Lines.to_dict(orient='records'),
            colors=color_dict,
            index_col="Resource",
            title="Genetic Algorithm based Optimization",
            show_colorbar=True,
            bar_width=0.3,
            showgrid_x=False,
            showgrid_y=True,
            show_hover_fill=True)

        fig_html = pio.to_html(fig)
        # fig.show()
        # print(fig_html)
        # fig.write_image(r"CLS_GanttChart.png")
        return fig_html
Example #2
0
def _plot_di(di_results):
    html = ''

    for K in ('cdi', 'cmdi'):
        X = di_results['%s1' % K]
        Y = di_results['%s2' % K]

        tail1 = di_results['sampnames1'][0].replace(di_results['basenames'][0],
                                                    '').strip()
        tail2 = di_results['sampnames2'][0].replace(di_results['basenames'][0],
                                                    '').strip()
        for S1, S2 in zip(di_results['sampnames1'], di_results['sampnames2']):
            assert S1.endswith(tail1)
            assert S2.endswith(tail2)

        T = dict(
            type='scatter',
            mode='markers',
            marker={
                'size': 18,
                'opacity': 0.75,
                'color': '#000000'
            },
            x=X,
            y=Y,
            text=di_results['basenames'],
        )
        Z = np.min([np.max(X), np.max(Y)])
        layout = go.Layout(
            template='plotly_white',
            xaxis={
                'title': f'{tail1} {K.upper()} (bits)',
                'range': (0, 1.1 * np.max(X))
            },
            yaxis={
                'title': f'{tail2} {K.upper()} (bits)',
                'range': (0, 1.1 * np.max(Y))
            },
            shapes=[dict(
                type='line',
                x0=0,
                x1=Z,
                y0=0,
                y1=Z,
            )],
        )
        fig = go.Figure(data=T, layout=layout)

        html += pio.to_html(fig,
                            include_plotlyjs=False,
                            full_html=False,
                            config={
                                'showLink': True,
                                'toImageButtonOptions': {
                                    'format': 'svg',
                                    'width': 600,
                                    'height': 400,
                                },
                            })
    return html
Example #3
0
def plot(request):
    df = pd.DataFrame()
    df['year'] = [1990, 2000, 2010, 2020]
    df['lifeExp'] = [65, 70, 75, 50]
    fig = px.line(df, x="year", y="lifeExp", title='Life expectancy in Turkey')
    div = pio.to_html(fig, include_plotlyjs=False, full_html=False)
    return render(request, "plotly_demo.html", {"my_plot": div})
def _plot_diversity_indices(div_idxs, sampnames, outf):
    figs = []
    html = ''

    titles = {
        'cdi': 'Clone diversity index',
        'cmdi': 'Clone and mutation diversity index',
        'sdi': 'Shannon diversity index',
    }

    for name in div_idxs.keys():
        traces = dict(
            type='bar',
            name=name,
            x=sampnames,
            y=div_idxs[name],
        )
        layout = go.Layout(
            template='plotly_white',
            xaxis={'title': 'Sample'},
            yaxis={'title': f'{titles[name]}<br>(bits)'},
        )
        fig = go.Figure(data=traces, layout=layout)
        html = pio.to_html(fig, include_plotlyjs='cdn', full_html=False)
        print(html, file=outf)
    def evaluateNode(self,
                     result,
                     nodeDic,
                     nodeId,
                     dims=None,
                     rows=None,
                     columns=None,
                     summaryBy="sum",
                     bottomTotal=False,
                     rightTotal=False,
                     fromRow=0,
                     toRow=0):
        fig = result
        if not "layout" in fig or not "margin" in fig[
                "layout"] or fig["layout"]["margin"]["b"] is None:
            fig.update_layout(margin=dict(b=10))
        if not "layout" in fig or not "margin" in fig[
                "layout"] or fig["layout"]["margin"]["t"] is None:
            fig.update_layout(margin=dict(t=10))
        if not "layout" in fig or not "margin" in fig[
                "layout"] or fig["layout"]["margin"]["l"] is None:
            fig.update_layout(margin=dict(l=10))

        res = dict()
        res["result"] = pio.to_html(fig,
                                    full_html=False,
                                    include_plotlyjs=False)
        return json.dumps(res)
Example #6
0
def outliers(request):
    global ppd
    print("outliers function")
    if request.method == 'POST':
        print("POST data")
        print(request.POST['outlier'])
        ppd.remove_feature_outlier_data(request.POST['outlier'])

    numeric_data = ppd.get_numeric_data()
    numeric_features_name = ppd.get_numeric_features_name()
    feature_box_plot = {}

    # Calculate Quartile
    # ppd.cal_quartile()

    for i in numeric_features_name:
        fig = px.box(numeric_data.loc[numeric_data[i].notnull(), i],
                     y=i,
                     points='all',
                     width=600)
        feature_box_plot[i] = {
            'box_plot':
            pio.to_html(fig=fig, full_html=False, include_plotlyjs=False),
            'num_outlier':
            ppd.get_feature_num_outlier(i),
            'have_missing':
            ppd.check_feature_missing(i)
        }

    context = {'feature_box_plot': feature_box_plot}
    return render(request, 'data_cleaning_app/outliers.html', context=context)
def plotBarChart(statementlist,mainBranches,df,titlelist,x_axistitle):
    counter = 0
    data = []
    for datapoint in statementlist:
        data.append(go.Bar(
            x=mainBranches,
            y=getattr(df, datapoint),
            name=titlelist[counter]
        ))
        counter += 1
    layout = go.Layout(
        barmode='group',
        autosize=True,
        width=1200,
        height=800,
        hovermode="x unified",
        xaxis=dict(
        title=x_axistitle
        )
    )
    config = {
        'scrollZoom': True
    }
    fig = go.Figure(data=data, layout=layout)
    bar = pop.to_html(fig, config=config)
    return bar
def plotStackChart(statementlist,mainBranches,df,titlelist,x_axistitle):
    stackCounter = 0
    dataStack = []
    for datapoint in statementlist:
        dataStack.append(go.Bar(
            x=mainBranches,
            y=getattr(df, datapoint),
            name=titlelist[stackCounter]
        ))
        stackCounter += 1
    layoutStack = go.Layout(
        barmode='relative',
        autosize=True,
        width=1200,
        height=800,
        hovermode="x unified",
        xaxis=dict(
        title=x_axistitle
        )
    )
    configStack = {
        'scrollZoom': True
    }
    figStack = go.Figure(data=dataStack, layout=layoutStack)
    stack = pop.to_html(figStack, config=configStack)
    return stack
def plotWorldMap():
    df_confirm = pd.read_csv("https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv")
    df_confirm = df_confirm.drop(columns=['Province/State', 'Lat', 'Long'])
    df_confirm = df_confirm.groupby('Country/Region').agg('sum')

    date_list = list(df_confirm.columns)
    df_confirm['country'] = df_confirm.index
    df_confirm['code'] = df_confirm['country'].apply(get_country_code)

    # Transform the dataset in a long format
    df_long = pd.melt(df_confirm, id_vars=['country', 'code'], value_vars=date_list, var_name='Date')
    fig = px.choropleth(df_long,  # Input Dataframe
                       locations="code",  # identify country code column
                        color="value",  # identify representing column
                        hover_name="country",  # identify hover name
                        animation_frame="Date",  # identify date column
                        projection="natural earth",  # select projection
                        color_continuous_scale='Peach',  # select prefer color scale
                       range_color=[0, 50000]  # select range of dataset
                        )
    fig.update_layout(margin={'r': 0, 't': 0, 'l': 0, 'b': 0})
    content = pop.to_html(fig)

    #Get Top 5 Covid Country
    covid_df = pd.read_csv("./csv/covid-19-dataset-2.csv")
    covid_country = covid_df.groupby('Country_Region').sum()[['Confirmed']]
    coviddf = (covid_country.nlargest(5, 'Confirmed'))
    pairs = [(country, confirmed) for country,confirmed in zip(coviddf.index, coviddf['Confirmed'])]

    return render_template("Worldmap.html", content=content, table=coviddf, pairs=pairs)
Example #10
0
    def to_mimebundle(self, fig_dict):

        from plotly.io import to_html

        if self.requirejs:
            include_plotlyjs = 'require'
            include_mathjax = False
        elif self.connected:
            include_plotlyjs = 'cdn'
            include_mathjax = 'cdn'
        else:
            include_plotlyjs = True
            include_mathjax = 'cdn'

        # build post script
        post_script = ["""
var gd = document.getElementById('{plot_id}');
var x = new MutationObserver(function (mutations, observer) {{
        var display = window.getComputedStyle(gd).display;
        if (!display || display === 'none') {{
            console.log([gd, 'removed!']);
            Plotly.purge(gd);
            observer.disconnect();
        }}
}});

// Listen for the removal of the full notebook cells
var notebookContainer = gd.closest('#notebook-container');
if (notebookContainer) {{
    x.observe(notebookContainer, {childList: true});
}}

// Listen for the clearing of the current output cell
var outputEl = gd.closest('.output');
if (outputEl) {{
    x.observe(outputEl, {childList: true});
}}
"""]

        # Add user defined post script
        if self.post_script:
            if not isinstance(self.post_script, (list, tuple)):
                post_script.append(self.post_script)
            else:
                post_script.extend(self.post_script)

        html = to_html(
            fig_dict,
            config=self.config,
            auto_play=self.auto_play,
            include_plotlyjs=include_plotlyjs,
            include_mathjax=include_mathjax,
            post_script=post_script,
            full_html=self.full_html,
            animation_opts=self.animation_opts,
            default_width='100%',
            default_height=525,
        )

        return {'text/html': html}
Example #11
0
def write_figs(figs, outfn, export_dims=None):
    plot = ''
    if export_dims is None:
        export_dims = {}
    else:
        # Duplicate, give that we modify it
        export_dims = dict(export_dims)

    for fname, fig in figs.items():
        if fname not in export_dims:
            export_dims[fname] = (750, 450)
        #print(pio.to_json(fig))
        plot += pio.to_html(
            fig,
            include_plotlyjs='cdn',
            config={
                'showLink': False,
                'toImageButtonOptions': {
                    'format': 'svg',
                    'width': export_dims[fname][0],
                    'height': export_dims[fname][1],
                    'filename': fname,
                },
            },
        )

    with open(outfn, 'w') as outf:
        print(plot, file=outf)
Example #12
0
    def get_figure1(df):
        fig = go.Figure()
        fig.add_trace(
            go.Box(x=df['sodium_dv'].dropna() * 100,
                   name='Sodium',
                   boxmean=True))
        fig.add_trace(
            go.Box(x=df['totalfat_dv'].dropna() * 100,
                   name='Total Fat',
                   boxmean=True))
        fig.add_trace(
            go.Box(x=df['sugar'].dropna(), name='Sugar', boxmean=True))

        fig.update_layout(barmode='stack')
        fig.update_traces(opacity=0.75)

        fig['layout']['xaxis'].update(range=[0, 100])
        fig.update_layout(
            xaxis_title="Daily Value (%)",
            margin=dict(
                l=0,
                r=0,
                b=50,
                t=50,
            ),
            title={
                'text': 'Distribution of Select Nutrients (Stores Combined)',
                'x': 0.5,
                'xanchor': 'center',
                'yanchor': 'top'
            },
            height=400)
        return to_html(fig, include_plotlyjs=False, full_html=False)
Example #13
0
 def plot_html_to_stream(self) -> StringIO:
     output = StringIO()
     for fig in self.figures:
         output.write(pio.to_html(fig, include_plotlyjs="cdn", full_html=False))
         output.write("\n")
     output.write(self.appendix)
     return output
def plotLineChart(statementlist,mainBranches,df,titlelist,x_axistitle):
    lineCounter = 0
    dataLine = []
    for datapoint in statementlist:
        dataLine.append(go.Scatter(
            x=mainBranches,
            y=getattr(df, datapoint),
            name=titlelist[lineCounter],
            mode='lines'
        ))
        lineCounter += 1
    layoutLine = go.Layout(
        autosize=True,
        width=1200,
        height=800,
        hovermode="x unified",
        xaxis=dict(
        title=x_axistitle
        )
    )
    configLine = {
        'scrollZoom': True
    }
    figLine = go.Figure(data=dataLine, layout=layoutLine)
    line = pop.to_html(figLine, config=configLine)
    return line
Example #15
0
    def to_mimebundle(self, fig_dict):

        from plotly.io import to_html

        if self.requirejs:
            include_plotlyjs = "require"
            include_mathjax = False
        elif self.connected:
            include_plotlyjs = "cdn"
            include_mathjax = "cdn"
        else:
            include_plotlyjs = True
            include_mathjax = "cdn"

        html = to_html(
            fig_dict,
            config=self.config,
            auto_play=self.auto_play,
            include_plotlyjs=include_plotlyjs,
            include_mathjax=include_mathjax,
            full_html=self.full_html,
            animation_opts=self.animation_opts,
            default_width="100%",
            default_height=525,
            validate=False,
        )

        return {"text/html": html}
Example #16
0
def ganttChart(dataFileName):

    df = pd.read_excel(open(dataFileName, 'rb'), sheet_name='SchAug3-11')
    # MaterialNo_H

    df = df.rename(
        columns={
            "Family": "Resource",
            "BasicStartDate": "Start",
            "BasicEndDate": "Finish",
            "LineName": "Task"
        })
    df = df.sort_values(by=['Task', 'Start'])
    color_dict = dict(
        zip(df.Resource.unique(), [
            'rgb({},{},{})'.format(i[0], i[1], i[2]) for i in list(
                np.random.randint(255, size=(len(df.Resource.unique()), 3)))
        ]))

    fig = ff.create_gantt(df.to_dict(orient='records'),
                          colors=color_dict,
                          index_col="Resource",
                          title="Gantt Chart for Table SchAug3-11",
                          show_colorbar=True,
                          bar_width=0.3,
                          showgrid_x=False,
                          showgrid_y=True,
                          show_hover_fill=True)
    # fig.show()
    # fig.write_image(r"CLS_GanttChart.png")

    fig_html = pio.to_html(fig)

    return fig_html
Example #17
0
def buy_sell():
    fig = go.Figure()

    t = round(time.time())

    pairs = ['BTC-USD']
    for i in pairs:
        bitcoin = pd.read_csv(
            'https://query1.finance.yahoo.com/v7/finance/download/{}?period1=1586613499&period2={}&interval=1d&events=history&includeAdjustedClose=true'
            .format(i, t),
            index_col='Date',
            parse_dates=True)
        data = bitcoin.copy()  #créer une copie du dataframe bitcoin
        data['Buy'] = np.zeros(len(
            data))  #on crée une colonne buy et on l'initialise avec des zeros
        data['Sell'] = np.zeros(len(
            data))  #on crée une colonne sell et on l'initialise avec des zeros
        '''cela nous donne la ligne au milieu'''
        #on crée un colonne RollingMax
        #rolling(window=28).max() permet de calculer le max sur les 28 dernier jour du data['Close']
        data['RollingMax'] = data['Close'].shift(1).rolling(window=28).max()
        #on crée un colonne RollingMin
        #rolling(window=28).min() permet de calculer le min sur les 28 dernier jour du data['Close']
        #on décale le signal d'un jour par shift(1) pour que je puisse vendre ou acheter le bitcoin
        data['RollingMin'] = data['Close'].shift(1).rolling(window=28).min()
        #on utilise le boolean indexing lorsque la valeur du close est supérieure au max des 28 dernier jour c'est un signe qu'il faut acheter
        #on écrit 1 a l'intérieure de la colonne Buy si la max est inférieure a la valeur close
        data.loc[data['RollingMax'] < data['Close'], 'Buy'] = 1
        #lorsque la valeur du close est inférieure au min des 28 dernier jour c'est un signe qu'il faut vendre nos action
        #on écrit -1 a l'intérieure de la colonne Sell si la min est supérieure a la valeur close
        data.loc[data['RollingMin'] > data['Close'], 'Sell'] = -1
        '''cette partie permet de générer le graphe avec plotly'''
        start = '2020'
        end = '2021'
    fig.add_trace(
        go.Scatter(x=data.index, y=data['Buy'][start:end], name='Buy'))

    fig.add_trace(
        go.Scatter(x=data.index, y=data['Sell'][start:end], name='Sell'))
    fig.update_layout(autosize=True,
                      width=1000,
                      margin=dict(l=20, r=5, t=28, b=20),
                      title={
                          'text': "Buy/Sell",
                          'y': 0.988,
                          'x': 0.5,
                          'xanchor': 'center',
                          'yanchor': 'top'
                      },
                      height=500,
                      paper_bgcolor="#58aa4d",
                      plot_bgcolor="#111444")

    config = dict({'scrollZoom': True})
    py.plot(fig, filename='buy&sell.html', config=config, auto_open=True)

    div = pio.to_html(fig, include_plotlyjs=False)

    return div
Example #18
0
 def plot(self, fig, **kwargs):
     """
     Generate HTML with plotly chart
     Params:
         fig: plotly fig
     """
     import plotly.io as pio
     return pio.to_html(fig, full_html=False, **kwargs)
Example #19
0
async def serve(q: Q):
    if not q.client.initialized:  # First visit
        q.client.initialized = True
        q.client.points = 25
        q.client.plotly_controls = False

        q.page['controls'] = ui.form_card(box='1 1 4 2',
                                          items=[
                                              ui.slider(name='points',
                                                        label='Points',
                                                        min=5,
                                                        max=50,
                                                        step=1,
                                                        value=q.client.points,
                                                        trigger=True),
                                              ui.toggle(
                                                  name='plotly_controls',
                                                  label='Plotly Controls',
                                                  trigger=True),
                                          ])
        q.page['plot'] = ui.frame_card(box='1 3 4 5', title='', content='')

    if q.args.points:
        q.client.points = q.args.points

    if q.args.plotly_controls is not None:
        q.client.plotly_controls = q.args.plotly_controls

    n = q.client.points

    # Create plot with plotly
    fig = go.Figure(data=go.Scatter(
        x=np.random.rand(n),
        y=np.random.rand(n),
        mode='markers',
        marker=dict(size=(8 * np.random.rand(n))**2, color=np.random.rand(n)),
        opacity=0.8,
    ))
    _ = fig.update_layout(
        margin=dict(l=10, r=10, t=10, b=10),
        paper_bgcolor='rgb(255, 255, 255)',
        plot_bgcolor='rgb(255, 255, 255)',
    )
    config = {
        'scrollZoom': q.client.plotly_controls,
        'showLink': q.client.plotly_controls,
        'displayModeBar': q.client.plotly_controls
    }
    html = pio.to_html(fig,
                       validate=False,
                       include_plotlyjs='cdn',
                       config=config)

    q.page['plot'].content = html

    # Save page
    await q.page.save()
Example #20
0
def plot_ul(request):
    df = pd.read_csv("static/regionaldata.csv", header=0)
    df.info(verbose=True)
    fig = px.scatter(df,
                     x="reg",
                     y="ul",
                     title="Regional ultrasound device distribution in Turkey")
    div = pio.to_html(fig, include_plotlyjs=False, full_html=False)
    return render(request, "plotly_demo.html", {"my_plot": div})
Example #21
0
def plot_amb(request):
    df = pd.read_csv("static/citydata.csv", header=0)
    df.info(verbose=True)
    fig = px.bar(df,
                 x="City",
                 y="AmbP",
                 title="Number of ambulance per 1.000.000 people")
    div = pio.to_html(fig, include_plotlyjs=False, full_html=False)
    return render(request, "plotly_demo.html", {"my_plot": div})
Example #22
0
def plot_dis(request):
    df = pd.read_csv("static/regionaldata.csv", header=0)
    df.info(verbose=True)
    fig = px.line(df,
                  x="reg",
                  y="dis1",
                  title="Regional dental clinic distribution in Turkey")
    div = pio.to_html(fig, include_plotlyjs=False, full_html=False)
    return render(request, "plotly_demo.html", {"my_plot": div})
Example #23
0
def __plot(request):
    #df = pd.DataFrame()
    df = pd.read_csv("static/data.csv", header=0)
    df.info(verbose=True)
    #df['year'] = [1990, 2000, 2010, 2020]
    #df['lifeExp'] = [65, 70, 75, 50]
    fig = px.line(df, x="year", y="lifeExp", title='Life expectancy in Turkey')
    div = pio.to_html(fig, include_plotlyjs=False, full_html=False)
    return render(request, "plotly_demo.html", {"my_plot": div})
Example #24
0
def allcoins():
    altcoins = [
        'BTC_ETH', 'BTC_LTC', 'USDC_BTC', 'BTC_ETC', 'BTC_STR', 'BTC_BCH',
        'BTC_XMR'
    ]

    altcoin_data = {}  #création d'un dictionnaire vide
    for altcoin in altcoins:
        coinpair = altcoin
        crypto_price_df = get_crypto_data(
            coinpair
        )  #Récupérer les données de crypto-monnaie de la liste altcoins du site poloniex
        altcoin_data[
            altcoin] = crypto_price_df  #ajouter les donnés de chaque crypto-monnaie au dictionnaire altcoin_data
    #on affecte a df_eth la valeur du dictionnaire correspondant à la clé 'BTC_ETH' et on fait la méme chose por les autres crypto-monnaie
    df_eth = altcoin_data['BTC_ETH']
    df_ltc = altcoin_data['BTC_LTC']
    df_usd = altcoin_data['USDC_BTC']
    df_etc = altcoin_data['BTC_ETC']
    df_bch = altcoin_data['BTC_BCH']
    df_xmr = altcoin_data['BTC_XMR']
    #Nous fusionnons les cours de clôture  ETH, LTC,USD,ETC,BCH et XMR dans une Dataframe
    df = pd.DataFrame({
        'ETH': df_eth.close,
        'LTC': df_ltc.close,
        'USD': 1 / df_usd.close,
        'ETC': df_etc.close,
        'BCH': df_bch.close,
        'XMR': df_xmr.close
    })
    #plot des altcoins
    df = df.fillna(0)
    fig = px.line(df)
    fig.update_layout(
        paper_bgcolor="#1188fc",
        plot_bgcolor="#111111",
        title={
            'text':
            "Evolution of some cryptocurrencies in terms of Bitcoin since 2015",
            'y': 0.989,
            'x': 0.5,
            'xanchor': 'center',
            'yanchor': 'top'
        },
        title_font_size=25,
        title_font_color='#fff',
        autosize=True,
        margin=dict(l=20, r=50, t=28.5, b=20),
        width=1300,
        xaxis_showgrid=False,
        yaxis_showgrid=False,
        height=600)
    config = dict({'scrollZoom': True})
    py.plot(fig, filename='allcoins.html', auto_open=True, config=config)
    div = pio.to_html(fig, include_plotlyjs=False)
    return div
Example #25
0
def tsne_validation(embeddings, paint, paint_name, plot_dir, plot_name):
    print(f"t-SNE on input shape {embeddings.shape}")
    tsne_embeddings = compute_tsne(embeddings)
    fig = plot_tsne_plotly(tsne_embeddings,
                           df_dict={paint_name: paint},
                           color=paint_name)
    html_string = to_html(fig)
    time_stamp = time.strftime(f"{plot_name}-%Y%m%d-%H%M%S.html")
    with open(plot_dir.joinpath(time_stamp), "w") as f:
        f.write(html_string)
Example #26
0
def html_from_data(data,pred,title):
    x=[]
    y=[]
    for i in range(len(data)):
        x.append(data[i][0])
        y.append(data[i][1])

    fig = px.scatter(x=x,y=y,color=pred)
    fig.update_layout(title=title)
    return pio.to_html(fig)
    def set_figure(self, fig=None):
        self.temp_file.seek(0)

        if fig:
            self.temp_file.write(to_html(fig, config={'responsive': True}))
        else:
            self.temp_file.write("")

        self.temp_file.truncate()
        self.temp_file.seek(0)
        self.load(QUrl.fromLocalFile(self.temp_file.name))
Example #28
0
def category_nutrient_distribution_plot(df: pd.DataFrame):
    def over_15(row):
        return 1 if row > 0.15 else 0

    nutrients = ['sodium_dv', 'saturatedfat_dv', 'sugar']
    nutrient_map = {
        'sodium_dv': 'Sodium',
        'saturatedfat_dv': 'Saturated Fat',
        'sugar': 'Sugar'
    }
    categories = [
        'Beverages', 'Cereals and Other Grain Products',
        'Dairy Products and Substitutes',
        'Meat and Poultry, Products and Substitutes', 'Snacks'
    ]

    category_labels = ['<br>'.join(wrap(c, 20)) for c in categories]

    plot_df = df.loc[df['category_text'].isin(categories)]

    for n in nutrients:
        plot_df[f'{n}_count'] = plot_df[n].apply(lambda row: over_15(row))

    plot_df = plot_df[['category_text'] +
                      [f'{n}_count' for n in nutrients]].groupby(
                          'category_text').sum().reindex(categories)

    data = [
        go.Bar(name=nutrient_map[nutrient],
               x=category_labels,
               y=plot_df[f'{nutrient}_count']) for nutrient in nutrients
    ]

    layout = dict(
        width=1100,
        font_size=18,
        margin=dict(
            l=100,
            r=20,
            b=20,
            t=30,
        ),
        yaxis_title='Products Exceeding Threshold',
        xaxis=dict(
            title='Food Category',
            showgrid=True,
            tickson='boundaries',
            tickangle=0,
        ),
    )

    fig = go.Figure(data=data, layout=layout)

    return to_html(fig, include_plotlyjs=False, full_html=False)
Example #29
0
def test(request):
    #print(request.args)
    #print(request.files)
    query1 = request.args.get('query1', '')
    query2 = request.args.get('query2', '')
    file_name = request.args.get('file_name', '')
    try:
        fig = calc(FILES_DICT[file_name], query1, query2)
        html = pio.to_html(fig)
        return response.html(html)
    except:
        return response.text('no graph')
Example #30
0
def convert_plot_to_html(fig, include_plotlyjs, validate):
    """
        Converts given plotly figure object to an HTML string representation

        :param fig: Figure object or dict representing a figure
        :param include_plotlyjs: bool or string (default True)
                                Specifies how the plotly.js library is included/loaded in the output div string.
        :param validate: True if the figure should be validated before being converted to JSON, False otherwise.

        :return: Representation of figure as an HTML div string
        """
    return to_html(fig, validate=validate, include_plotlyjs=include_plotlyjs)
Example #31
0
 def render(self, fig_dict):
     from plotly.io import to_html
     html = to_html(
         fig_dict,
         config=self.config,
         auto_play=self.auto_play,
         include_plotlyjs=True,
         include_mathjax='cdn',
         post_script=self.post_script,
         full_html=True,
         animation_opts=self.animation_opts,
         default_width='100%',
         default_height='100%',
         validate=False,
     )
     open_html_in_browser(html, self.using, self.new, self.autoraise)
Example #32
0
    def to_mimebundle(self, fig_dict):

        from plotly.io import to_html

        if self.requirejs:
            include_plotlyjs = 'require'
            include_mathjax = False
        elif self.connected:
            include_plotlyjs = 'cdn'
            include_mathjax = 'cdn'
        else:
            include_plotlyjs = True
            include_mathjax = 'cdn'

        # build post script
        post_script = ["""
var gd = document.getElementById('{plot_id}');
var x = new MutationObserver(function (mutations, observer) {{
        var display = window.getComputedStyle(gd).display;
        if (!display || display === 'none') {{
            console.log([gd, 'removed!']);
            Plotly.purge(gd);
            observer.disconnect();
        }}
}});

// Listen for the removal of the full notebook cells
var notebookContainer = gd.closest('#notebook-container');
if (notebookContainer) {{
    x.observe(notebookContainer, {childList: true});
}}

// Listen for the clearing of the current output cell
var outputEl = gd.closest('.output');
if (outputEl) {{
    x.observe(outputEl, {childList: true});
}}
"""]

        # Add user defined post script
        if self.post_script:
            if not isinstance(self.post_script, (list, tuple)):
                post_script.append(self.post_script)
            else:
                post_script.extend(self.post_script)

        html = to_html(
            fig_dict,
            config=self.config,
            auto_play=self.auto_play,
            include_plotlyjs=include_plotlyjs,
            include_mathjax=include_mathjax,
            post_script=post_script,
            full_html=self.full_html,
            animation_opts=self.animation_opts,
            default_width='100%',
            default_height=525,
            validate=False,
        )

        return {'text/html': html}
Example #33
0
def plot(figure_or_data, show_link=False, link_text='Export to plot.ly',
         validate=True, output_type='file', include_plotlyjs=True,
         filename='temp-plot.html', auto_open=True, image=None,
         image_filename='plot_image', image_width=800, image_height=600,
         config=None, include_mathjax=False, auto_play=True,
         animation_opts=None):
    """ Create a plotly graph locally as an HTML document or string.

    Example:
    ```
    from plotly.offline import plot
    import plotly.graph_objs as go

    plot([go.Scatter(x=[1, 2, 3], y=[3, 2, 6])], filename='my-graph.html')
    # We can also download an image of the plot by setting the image parameter
    # to the image format we want
    plot([go.Scatter(x=[1, 2, 3], y=[3, 2, 6])], filename='my-graph.html',
         image='jpeg')
    ```
    More examples below.

    figure_or_data -- a plotly.graph_objs.Figure or plotly.graph_objs.Data or
                      dict or list that describes a Plotly graph.
                      See https://plot.ly/python/ for examples of
                      graph descriptions.

    Keyword arguments:
    show_link (default=False) -- display a link in the bottom-right corner of
        of the chart that will export the chart to Plotly Cloud or
        Plotly Enterprise
    link_text (default='Export to plot.ly') -- the text of export link
    validate (default=True) -- validate that all of the keys in the figure
        are valid? omit if your version of plotly.js has become outdated
        with your version of graph_reference.json or if you need to include
        extra, unnecessary keys in your figure.
    output_type ('file' | 'div' - default 'file') -- if 'file', then
        the graph is saved as a standalone HTML file and `plot`
        returns None.
        If 'div', then `plot` returns a string that just contains the
        HTML <div> that contains the graph and the script to generate the
        graph.
        Use 'file' if you want to save and view a single graph at a time
        in a standalone HTML file.
        Use 'div' if you are embedding these graphs in an HTML file with
        other graphs or HTML markup, like a HTML report or an website.
    include_plotlyjs (True | False | 'cdn' | 'directory' | path - default=True)
        Specifies how the plotly.js library is included in the output html
        file or div string.

        If True, a script tag containing the plotly.js source code (~3MB)
        is included in the output.  HTML files generated with this option are
        fully self-contained and can be used offline.

        If 'cdn', a script tag that references the plotly.js CDN is included
        in the output. HTML files generated with this option are about 3MB
        smaller than those generated with include_plotlyjs=True, but they
        require an active internet connection in order to load the plotly.js
        library.

        If 'directory', a script tag is included that references an external
        plotly.min.js bundle that is assumed to reside in the same
        directory as the HTML file.  If output_type='file' then the
        plotly.min.js bundle is copied into the directory of the resulting
        HTML file. If a file named plotly.min.js already exists in the output
        directory then this file is left unmodified and no copy is performed.
        HTML files generated with this option can be used offline, but they
        require a copy of the plotly.min.js bundle in the same directory.
        This option is useful when many figures will be saved as HTML files in
        the same directory because the plotly.js source code will be included
        only once per output directory, rather than once per output file.

        If a string that ends in '.js', a script tag is included that
        references the specified path. This approach can be used to point
        the resulting HTML file to an alternative CDN.

        If False, no script tag referencing plotly.js is included. This is
        useful when output_type='div' and the resulting div string will be
        placed inside an HTML document that already loads plotly.js.  This
        option is not advised when output_type='file' as it will result in
        a non-functional html file.
    filename (default='temp-plot.html') -- The local filename to save the
        outputted chart to. If the filename already exists, it will be
        overwritten. This argument only applies if `output_type` is 'file'.
    auto_open (default=True) -- If True, open the saved file in a
        web browser after saving.
        This argument only applies if `output_type` is 'file'.
    image (default=None |'png' |'jpeg' |'svg' |'webp') -- This parameter sets
        the format of the image to be downloaded, if we choose to download an
        image. This parameter has a default value of None indicating that no
        image should be downloaded. Please note: for higher resolution images
        and more export options, consider making requests to our image servers.
        Type: `help(py.image)` for more details.
    image_filename (default='plot_image') -- Sets the name of the file your
        image will be saved to. The extension should not be included.
    image_height (default=600) -- Specifies the height of the image in `px`.
    image_width (default=800) -- Specifies the width of the image in `px`.
    config (default=None) -- Plot view options dictionary. Keyword arguments
        `show_link` and `link_text` set the associated options in this
        dictionary if it doesn't contain them already.
    include_mathjax (False | 'cdn' | path - default=False) --
        Specifies how the MathJax.js library is included in the output html
        file or div string.  MathJax is required in order to display labels
        with LaTeX typesetting.

        If False, no script tag referencing MathJax.js will be included in the
        output. HTML files generated with this option will not be able to
        display LaTeX typesetting.

        If 'cdn', a script tag that references a MathJax CDN location will be
        included in the output.  HTML files generated with this option will be
        able to display LaTeX typesetting as long as they have internet access.

        If a string that ends in '.js', a script tag is included that
        references the specified path. This approach can be used to point the
        resulting HTML file to an alternative CDN.
    auto_play (default=True) -- Whether to automatically start the animation
        sequence on page load if the figure contains frames. Has no effect if
        the figure does not contain frames.
    animation_opts (default=None) -- dict of custom animation parameters to be
        passed to the function Plotly.animate in Plotly.js. See
        https://github.com/plotly/plotly.js/blob/master/src/plots/animation_attributes.js
        for available options. Has no effect if the figure does not contain
        frames, or auto_play is False.

    Example:
    ```
    from plotly.offline import plot
    figure = {'data': [{'x': [0, 1], 'y': [0, 1]}],
              'layout': {'xaxis': {'range': [0, 5], 'autorange': False},
                         'yaxis': {'range': [0, 5], 'autorange': False},
                         'title': 'Start Title'},
              'frames': [{'data': [{'x': [1, 2], 'y': [1, 2]}]},
                         {'data': [{'x': [1, 4], 'y': [1, 4]}]},
                         {'data': [{'x': [3, 4], 'y': [3, 4]}],
                          'layout': {'title': 'End Title'}}]}
    plot(figure,animation_opts="{frame: {duration: 1}}")
    ```
    """
    import plotly.io as pio

    # Output type
    if output_type not in ['div', 'file']:
        raise ValueError(
            "`output_type` argument must be 'div' or 'file'. "
            "You supplied `" + output_type + "``")
    if not filename.endswith('.html') and output_type == 'file':
        warnings.warn(
            "Your filename `" + filename + "` didn't end with .html. "
            "Adding .html to the end of your file.")
        filename += '.html'

    # Config
    config = dict(config) if config else {}
    config.setdefault('showLink', show_link)
    config.setdefault('linkText', link_text)

    figure = tools.return_figure_from_figure_or_data(figure_or_data, validate)
    width = figure.get('layout', {}).get('width', '100%')
    height = figure.get('layout', {}).get('height', '100%')

    if width == '100%' or height == '100%':
        config.setdefault('responsive', True)

    # Handle image request
    post_script = build_save_image_post_script(
        image, image_filename, image_height, image_width, 'plot')

    if output_type == 'file':
        pio.write_html(
            figure,
            filename,
            config=config,
            auto_play=auto_play,
            include_plotlyjs=include_plotlyjs,
            include_mathjax=include_mathjax,
            post_script=post_script,
            full_html=True,
            validate=validate,
            animation_opts=animation_opts,
            auto_open=auto_open)
        return filename
    else:
        return pio.to_html(
            figure,
            config=config,
            auto_play=auto_play,
            include_plotlyjs=include_plotlyjs,
            include_mathjax=include_mathjax,
            post_script=post_script,
            full_html=False,
            validate=validate,
            animation_opts=animation_opts)