Exemple #1
0
    def to_mimebundle(self, fig_dict):
        from plotly.io import write_html

        # Make iframe size slightly larger than figure size to avoid
        # having iframe have its own scroll bar.
        iframe_buffer = 20
        layout = fig_dict.get('layout', {})

        if layout.get('width', False):
            iframe_width = str(layout['width'] + iframe_buffer) + 'px'
        else:
            iframe_width = '100%'

        if layout.get('height', False):
            iframe_height = layout['height'] + iframe_buffer
        else:
            iframe_height = str(525 + iframe_buffer) + 'px'

        # Build filename using ipython cell number
        ip = IPython.get_ipython()
        cell_number = list(ip.history_manager.get_tail(1))[0][1] + 1
        dirname = 'iframe_figures'
        filename = '{dirname}/figure_{cell_number}.html'.format(
            dirname=dirname, cell_number=cell_number)

        # Make directory for
        os.makedirs(dirname, exist_ok=True)

        write_html(
            fig_dict,
            filename,
            config=self.config,
            auto_play=self.auto_play,
            include_plotlyjs='directory',
            include_mathjax='cdn',
            auto_open=False,
            post_script=self.post_script,
            animation_opts=self.animation_opts,
            default_width='100%',
            default_height=525,
            validate=False,
        )

        # Build IFrame
        iframe_html = """\
<iframe
    scrolling="no"
    width="{width}"
    height="{height}"
    src="{src}"
    frameborder="0"
    allowfullscreen
></iframe>
""".format(width=iframe_width, height=iframe_height, src=filename)

        return {'text/html': iframe_html}
Exemple #2
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)
    lat="LAT",
    lon="LONG",
    color="INC",
    size="INC",
    animation_frame='DATA',
    animation_group='INC',
    mapbox_style='dark',
    color_continuous_scale=px.colors.sequential.Inferno,
    range_color=(0, 9000),  # closed issue #1 
    size_max=60,
    hover_name='CONCELHO',
    hover_data=['DATA', 'CONCELHO', 'INC'],
    title='COVID-19 EM PORTUGAL')

# Update the layout

fig.update_layout(
    font_size=16,
    title={
        'xanchor': 'center',
        'yanchor': 'top',
        'y': 0.2,
        'x': 0.5,
    },
    title_font_size=54,
    mapbox_style="mapbox://styles/vostpt/cko3z46ny0qm817qsgr6a516d")

# Write to HTML file

pio.write_html(fig, file="index.html", auto_open=True)
                    textfont=dict(size=18),
                    marker={'colors':['white','#EF7F73','#F1948A','#F4A9A1','#F6BEB8']},
                    showlegend=True)]

fig =go.Figure(data=loans_data)

# Create / update the figure layout
fig.update_layout(
                  title={'text': "Loans & Bad Debts", 'y':0.9, 'x':0.9, 'font': {'size': 25}},
                  margin = dict(t=0, l=0, r=0, b=0),
                  legend=dict(font_size=25, x=1, y=0.5),
                  # Add annotations in the center of the donut pies.
                  annotations=[dict(text='Bad Debts', x=0.4, y=0.7, font_size=18, font_color = 'white', showarrow=False),
                  dict(text='Good Loans', x=0.8, y=0.5, font_size=18, font_color = 'white', showarrow=False)])

pio.write_html(fig, file='Pie_loans_fig.html', auto_open=True) # as interactive plot with .html page

# Plot the distribution of categorical columns to check for imbalance
fig, axes = plt.subplots(2, 3, figsize=(20, 12))

loans['Gender'].value_counts(normalize=True).plot.bar(ax=axes[0][0], fontsize=20 , color='#ce295e') 
axes[0][0].set_title("GENDER", fontsize=24)

loans['Ownership'].value_counts(normalize=True).plot.bar(ax=axes[0][1], fontsize=20, color='#ce295e') 
axes[0][1].set_title("OWNERSHIP", fontsize=24)

loans['Age Range'].value_counts(normalize=True).plot.bar(ax=axes[0][2], fontsize=20,  color='#ce295e') 
axes[0][2].set_title("AGE RANGE", fontsize=24)

loans['District'].value_counts(normalize=True).plot.bar(ax=axes[1][0], fontsize=20, color='#ce295e') 
axes[1][0].set_title("DISTRICT", fontsize=24)
       ]
       
Cell 11:
layout = dict(
    title = 'Average Temperature by Country, 1910',
    geo = dict(showframe = False,
               showocean = True,
               oceancolor = 'rgb(0,255,255)',
               projection = dict(type = 'orthographic'),
              )
             )
             
Cell 12:
fig = dict(data = data, layout = layout)

Cell 13:
pio.write_html(fig, file = 'graph1.html', auto_open = True)

Cell 14:
data_slider = []

Cell 15:
for each_y in temp_hist_by_country.Year.unique():
    data_one_year = dict(type = 'choropleth',
                         colorscale = scl,
                         autocolorscale = False,
                         locations = countries,
                         text = "Year: " + str(each_y),
                         z = temp_hist_by_country.loc[temp_hist_by_country["Year"] == each_y, "Average Temperature (Celsius)"],
                         zmin = -20,
                         zmax = 30,
                         locationmode = 'country names',
         y1=1,
         xref='x',
         x0='2020-07-03',
         x1='2020-07-03',
         line=dict(color='Red', width=1, dash='dashdot')))

fig.add_annotation(text="Día sin IVA #2",
                   x='2020-07-01',
                   y=totalAcum['Acumulado'].max(),
                   showarrow=False,
                   textangle=270)
fig.show()

#Crea archivo HTML para la visualizacion
import plotly.io as pio
pio.write_html(fig, file='V1.html', auto_open=True)

#####################################################
#Genera grafico
fig = px.line(totalAcum, x='FechaDiag', y='NroCasosDia')

fig.add_shape(
    dict(type='line',
         yref='paper',
         y0=0,
         y1=1,
         xref='x',
         x0='2020-06-20',
         x1='2020-06-20',
         line=dict(color='Red', width=1, dash='dashdot')))
import plotly.graph_objects as go
import plotly.io as pio
import pandas as pd

world = pd.read_csv('data/Global_Mobility_Report.csv',
                    dtype={'sub_region_2': object})

by_country = world.groupby(['country_region_code',
                            'country_region']).mean().reset_index()
print(by_country.head())

data = dict(type='choropleth',
            locations=by_country['country_region'],
            locationmode='country names',
            z=by_country['residential_percent_change_from_baseline'],
            text=by_country['country_region'],
            colorbar={'title': 'Residential Change from baseline'},
            colorscale='blues')

layout = dict(title='Google Mobility from baseline',
              geo=dict(showframe=True, projection={'type': 'natural earth'}))

choromap = go.Figure(data=[data], layout=layout)

pio.write_html(choromap, 'output/covid_mobility.html', auto_open=True)
Exemple #8
0
def plot_category_bdc(filename, categories, bdc_vals_dict):
    #
    # `bdc_vals_dict` should of the form:
    #       bdc_vals_dict = {"cpu": [[a1, b1, ..., d1], [a1, b1, ..., d1], ..., [a1, b1, ..., d1]],
    #                         "gpu": [[a2, b2, ..., d2], [a2, b2, ..., d2], ..., [a2, b2, ..., d2]],
    #                                   ...
    #                         "gpu": [[aM, bM, ..., dM], [aM, bM, ..., dM], ..., [aM, bM, ..., dM]}
    #
    # `stages` should be of form:
    #       stages = ["S1", "S2", ..., "SN"]
    #

    # Squash individual stage BDCs into 1 bdc per category
    data = []
    for (_, hw) in bdc_vals_dict.items():
        accs = []
        for cat in hw:
            acc = 0
            for stage in cat:
                acc += stage
            accs.append(acc)
        data.append(accs)

    hws = list(bdc_vals_dict.keys())

    # Wrap around first category
    categories.append(categories[0])

    fig = go.Figure()
    for i in range(len(hws)):

        # Wrap around first data point
        data[i].append(data[i][0])

        fig.add_trace(
            go.Scatterpolar(name=hws[i],
                            r=data[i],
                            theta=categories,
                            mode='lines'))

    # Fonts
    axis_tick_font = dict(size=14, family='Calibri', color='black')
    legend_font = axis_tick_font

    fig.update_layout(polar=dict(radialaxis=dict(showticklabels=False,
                                                 showline=False,
                                                 showgrid=True,
                                                 gridwidth=1,
                                                 gridcolor='rgba(0,0,0,0.1)'),
                                 angularaxis=dict(showgrid=True,
                                                  gridwidth=1,
                                                  gridcolor='rgba(0,0,0,0.3)',
                                                  tickfont=axis_tick_font),
                                 bgcolor='white'),
                      showlegend=True)

    # To generate HTML output:
    pio.write_html(fig,
                   file=filename + ".html",
                   auto_open=False,
                   include_plotlyjs="cdn")

    logging.info("Plot generated at: {}".format(filename))

    # To generate image file output:
    fig.write_image(filename + ".pdf")
    fig.write_image(filename + ".png")

    logging.info("Plot generated at: {}".format(filename))
Exemple #9
0
def plot_category_bdc_bars(filename, categories, bdc_vals_dict, style=0):
    #
    # `bdc_vals_dict` should of the form:
    #       bdc_vals_dict = {"cpu": [[a1, b1, ..., d1], [a1, b1, ..., d1], ..., [a1, b1, ..., d1]],
    #                         "gpu": [[a2, b2, ..., d2], [a2, b2, ..., d2], ..., [a2, b2, ..., d2]],
    #                                   ...
    #                         "gpu": [[aM, bM, ..., dM], [aM, bM, ..., dM], ..., [aM, bM, ..., dM]}
    #
    # `stages` should be of form:
    #       stages = ["S1", "S2", ..., "SN"]
    #

    # Squash individual stage BDCs into 1 bdc per category
    data = []
    for (_, hw) in bdc_vals_dict.items():
        accs = []
        for cat in hw:
            acc = 0
            for stage in cat:
                acc += stage
            accs.append(acc)
        data.append(accs)

    hws = list(bdc_vals_dict.keys())

    fig = go.Figure()
    for i in range(len(hws)):

        fig.add_trace(go.Bar(x=categories, y=data[i], name=hws[i]))

    # Fonts
    axis_tick_font = dict(size=12, family='Calibri', color='black')
    legend_font = axis_tick_font
    axis_title_font = axis_tick_font

    fig.update_layout(
        barmode='group',
        bargap=0.3,
        showlegend=True,
        xaxis=dict(  #title_text='BDC Categories', 
            showline=True,
            linewidth=2,
            linecolor='black',
            title_font=axis_title_font,
            tickfont=axis_tick_font),
        yaxis=dict(title_text='Backend Development Cost',
                   showline=True,
                   linewidth=2,
                   linecolor='black',
                   showgrid=False,
                   gridcolor='black',
                   gridwidth=1,
                   title_font=axis_title_font,
                   tickfont=axis_tick_font),
    )

    # To generate HTML output:
    pio.write_html(fig,
                   file=filename + ".html",
                   auto_open=False,
                   include_plotlyjs="cdn")

    logging.info("Plot generated at: {}".format(filename))

    # To generate image file output:
    fig.write_image(filename + ".pdf")
    fig.write_image(filename + ".png")

    logging.info("Plot generated at: {}".format(filename))
        fig.update_layout(template='plotly_white')

        fig.update_layout(xaxis=dict(tickformat="%m-%d"))
        fig.update_xaxes(range=['2020-03-01', None])

        fig.update_layout(annotations=annotations)

        fig.update_layout(hovermode="x")
        fig.update_layout(showlegend=False)

        fig.update_layout(autosize=True, height=400, margin=dict(l=0, r=0))

        fig.add_shape(
            dict(type="line",
                 x0=today,
                 y0=0,
                 x1=today,
                 y1=5,
                 line=dict(color='rgb(65, 65, 69)', width=0.7)))

        # fig.show()

        pio.write_html(fig,
                       file='html/us_' + state_name.replace(" ", "_") +
                       '_fuel_demand.html',
                       config={'displayModeBar': False},
                       auto_open=True,
                       include_plotlyjs='cdn',
                       full_html=False)