Example #1
0
 def plot_propagation(self) -> None:
     Figure(
         data=[self.get_single_propagation_scatter()],
         layout=Layout(
             template="plotly_white",
             title=Title(
                 text=
                 f"Tweets propagation, root: {self.unique_id}, {self.tweet_type}",
                 x=0.5),
             yaxis=YAxis(title="Cumulative number of retweets"),
             xaxis=XAxis(title="Delay since root tweet"),
         )).show()
Example #2
0
def setup_figure(data, datetimes, use_gradient, show_yaxis_ticks, height):
    """Create figure."""
    n_channels = data.shape[1]
    datetimes = [
        dt.utcfromtimestamp((datetime + np.timedelta64(3, 'h')).tolist() / 1e9)
        for datetime in datetimes
    ]
    domains = np.linspace(1, 0, n_channels + 1)

    fig = tools.make_subplots(
        rows=n_channels,
        cols=1,
        # specs=[[{}]] * n_channels,
        shared_xaxes=True,
        shared_yaxes=True,
        vertical_spacing=-5,
        print_grid=False)

    traces = create_traces(data, datetimes, n_channels, use_gradient)
    logger.info("Appending traces")
    # for i, trace in tqdm(enumerate(traces), desc='Appending traces to figure'):
    #     fig.append_trace(trace, i + 1, 1)
    for i, trace in tqdm(enumerate(traces), desc='Updating layout'):
        fig['layout'].update({
            f'yaxis{i + 1}':
            YAxis({
                'domain': np.flip(domains[i:i + 2], axis=0),
                'showticklabels': show_yaxis_ticks,
                'zeroline': False,
                'showgrid': False,
                'automargin': False
            }),
            'showlegend':
            False,
            'margin': {
                't': 0,
                'l': 0
            }
        })

    fig['data'] = traces

    if not show_yaxis_ticks:
        annotations = create_annotations(data, n_channels)
        fig['layout'].update(annotations=annotations)

    fig['layout'].update(autosize=False, height=height)
    # fig['layout']['xaxis'].update(side='top')
    # fig['layout']['xaxis'].update(tickformat='%H:%M:%S:%L')
    # fig['layout']['xaxis'].update(mirror='allticks', side='bottom')

    logger.info("Figure set up")
    return fig
Example #3
0
def plot_all_tweets_propagation(all_tweets: List[Tweet]) -> None:
    colors = {TweetType.TRUE: "green", TweetType.FALSE: "red"}

    all_tweets.sort(key=lambda tweet: tweet.tweet_type)

    Figure(
        data=[
            tweet.get_single_propagation_scatter(colors[tweet.tweet_type])
            for tweet in all_tweets
            if tweet.tweet_type in {TweetType.TRUE, TweetType.FALSE}
        ],
        layout=Layout(
            template="plotly_white",
            title=Title(text="Tweets propagation", x=0.5),
            yaxis=YAxis(title="Skumulowana liczba tweetów"),
            xaxis=XAxis(title="Czas od pojawiania się pierwszego wpisu [s]"),
        )).show()
Example #4
0
def plot_explained_variance(pca):
    import plotly
    from plotly.graph_objs import Bar, Line
    from plotly.graph_objs import Scatter, Layout
    from plotly.graph_objs.scatter import Marker
    from plotly.graph_objs.layout import XAxis, YAxis
    plotly.offline.init_notebook_mode() # run at the start of every notebook

    explained_var = pca.explained_variance_ratio_
    cum_var_exp = np.cumsum(explained_var)

    plotly.offline.iplot({
        "data": [Bar(y=explained_var, name='individual explained variance'),
                 Scatter(y=cum_var_exp, name='cumulative explained variance')
            ],
        "layout": Layout(xaxis=XAxis(title='Principal components'), yaxis=YAxis(title='Explained variance ratio'))
    })
Example #5
0
def plot_colored_table(
    master_values: np.ndarray,
    branch_values: np.ndarray,
    row_labels: List[str],
    col_labels: List[str],
    tab_data: np.ndarray,
) -> str:
    """Create an annotated heatmap of shape (H,W), where there are H metrics, and W benchmark datasets.

    Args:
        master_values: array of shape (H,W), representing values in master
        branch_values: array of shape (H,W), representing values in new branch
        col_labels: list of length (W), representing labels for each column (column names) in the "x" direction.
        row_labels: list of length (H), representing labels for each row (row names) in the "y" direction.
        tab_data: (H,W) 2d matrix, representing table data. Entries of the table represent percentage changes
            from a value for a metric on the master branch. Values can be considered in the "z" direction.

    Returns:
        string representing HTML code for the generated Plotly table.
    """
    if tab_data.size == 0:
        return ""
    # Clip "Z" to -20% and +20%. The clipping is only for the color -- the text will still display the correct numbers.
    tab_data_clipped = np.clip(tab_data,
                               a_min=MIN_RENDERABLE_PERCENT_CHANGE,
                               a_max=MAX_RENDERABLE_PERCENT_CHANGE)

    H, W = tab_data.shape
    hovertext_table = np.empty((H, W), dtype=object)
    for i in range(H):
        for j in range(W):
            cell_text = f"Master: {master_values[i,j]}<br />"
            cell_text += f"Branch: {branch_values[i,j]} <br />"
            cell_text += f"Percentage: {tab_data[i,j]}"
            hovertext_table[i, j] = cell_text

    redgreen = [RED_HEX, PALE_YELLOW_HEX, GREEN_HEX]
    colorscale = colorscale_from_list(redgreen)
    trace = go.Heatmap(
        z=tab_data_clipped,
        x=col_labels,
        y=row_labels,
        colorscale=colorscale,
        hoverinfo="text",
        text=hovertext_table.tolist(),
        zmin=-MIN_RENDERABLE_PERCENT_CHANGE,
        zmax=MAX_RENDERABLE_PERCENT_CHANGE,
    )

    layout = go.Layout(
        title="Percentage Change",
        font=Font(family="Balto, sans-serif", size=12, color="rgb(68,68,68)"),
        showlegend=False,
        xaxis=XAxis(title="", showgrid=True, side="top", tickangle=-45),
        yaxis=YAxis(
            title="",
            autorange="reversed",
            showgrid=True,
        ),
        autosize=False,
        height=HEATMAP_HEIGHT,
        width=HEATMAP_WIDTH,
        margin=Margin(l=135, r=40, b=85, t=170),
    )

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

    annotations = []
    num_rows, num_cols = tab_data.shape
    for i in range(num_rows):
        for j in range(num_cols):
            annotations.append(
                Annotation(
                    text=str(np.round(tab_data[i, j], 1)) + "%",
                    x=col_labels[j],
                    y=row_labels[i],
                    xref="x1",
                    yref="y1",
                    font=dict(color="rgb(25,25,25)"),
                    showarrow=False,
                ))
    fig["layout"].update(annotations=annotations)
    return fig.to_html(full_html=False, include_plotlyjs="cdn")
Example #6
0
def draw_traces_nograph(traces, on_map=False, map_style='basic', showlegend=True, figsize=1,
                aspectratio='auto', filename='temp-plot.html'):
    """
    plots all the traces (which can be created using :func:`create_bus_trace`, :func:`create_line_trace`,
    :func:`create_trafo_trace`)
    to PLOTLY (see https://plot.ly/python/)

    INPUT:
        **traces** - list of dicts which correspond to plotly traces
        generated using: `create_bus_trace`, `create_line_trace`, `create_trafo_trace`

    OPTIONAL:
        **on_map** (bool, False) - enables using mapbox plot in plotly

        **map_style** (str, 'basic') - enables using mapbox plot in plotly

            - 'streets'
            - 'bright'
            - 'light'
            - 'dark'
            - 'satellite'

        **showlegend** (bool, 'True') - enables legend display

        **figsize** (float, 1) - aspectratio is multiplied by it in order to get final image size

        **aspectratio** (tuple, 'auto') - when 'auto' it preserves original aspect ratio of the
            network geodata any custom aspectration can be given as a tuple, e.g. (1.2, 1)

        **filename** (str, "temp-plot.html") - plots to a html file called filename

    OUTPUT:
        **figure** (graph_objs._figure.Figure) figure object without showing the graph. The graph values
            will be stored as variables.
    """

    if on_map:
        try:
            on_map = _on_map_test(traces[0]['x'][0], traces[0]['y'][0])
        except:
            logger.warning("Test if geo-data are in lat/long cannot be performed using geopy -> "
                           "eventual plot errors are possible.")

        if on_map is False:
            logger.warning("Existing geodata are not real lat/lon geographical coordinates. -> "
                           "plot on maps is not possible.\n"
                           "Use geo_data_to_latlong(net, projection) to transform geodata from specific projection.")

    if on_map:
        # change traces for mapbox
        # change trace_type to scattermapbox and rename x to lat and y to lon
        for trace in traces:
            trace['lat'] = trace.pop('x')
            trace['lon'] = trace.pop('y')
            trace['type'] = 'scattermapbox'
            if "line" in trace and isinstance(trace["line"], Line):
                # scattermapboxplot lines do not support dash for some reason, make it a red line instead
                if "dash" in trace["line"]._props:
                    _prps = dict(trace["line"]._props)
                    _prps.pop("dash", None)
                    _prps["color"] = "red"
                    trace["line"] = scmLine(_prps)
                else:
                    trace["line"] = scmLine(dict(trace["line"]._props))
            elif "marker" in trace and isinstance(trace["marker"], Marker):
                trace["marker"] = scmMarker(trace["marker"]._props)

    # setting Figure object
    fig = Figure(data=traces,  # edge_trace
                 layout=Layout(
                     titlefont=dict(size=16),
                     showlegend=showlegend,
                     autosize=(aspectratio == 'auto'),
                     hovermode='closest',
                     margin=dict(b=5, l=5, r=5, t=5),
                     # annotations=[dict(
                     #     text="",
                     #     showarrow=False,
                     #     xref="paper", yref="paper",
                     #     x=0.005, y=-0.002)],
                     xaxis=XAxis(showgrid=False, zeroline=False, showticklabels=False),
                     yaxis=YAxis(showgrid=False, zeroline=False, showticklabels=False),
                     # legend=dict(x=0, y=1.0)
                 ), )

    # check if geodata are real geographical lat/lon coordinates using geopy

    if on_map:
        try:
            mapbox_access_token = _get_mapbox_token()
        except Exception:
            logger.exception('mapbox token required for map plots. '
                             'Get Mapbox token by signing in to https://www.mapbox.com/.\n'
                             'After getting a token, set it to pandapower using:\n'
                             'pandapower.plotting.plotly.mapbox_plot.set_mapbox_token(\'<token>\')')
            raise MapboxTokenMissing

        fig['layout']['mapbox'] = dict(accesstoken=mapbox_access_token,
                                       bearing=0,
                                       center=dict(lat=pd.Series(traces[0]['lat']).dropna().mean(),
                                                   lon=pd.Series(traces[0]['lon']).dropna().mean()),
                                       style=map_style,
                                       pitch=0,
                                       zoom=11)

    # default aspectratio: if on_map use auto, else use 'original'
    aspectratio = 'original' if not on_map and aspectratio == 'auto' else aspectratio

    if aspectratio != 'auto':
        if aspectratio == 'original':
            # TODO improve this workaround for getting original aspectratio
            xs = []
            ys = []
            for trace in traces:
                xs += trace['x']
                ys += trace['y']
            x_dropna = pd.Series(xs).dropna()
            y_dropna = pd.Series(ys).dropna()
            xrange = x_dropna.max() - x_dropna.min()
            yrange = y_dropna.max() - y_dropna.min()
            ratio = xrange / yrange
            if ratio < 1:
                aspectratio = (ratio, 1.)
            else:
                aspectratio = (1., 1 / ratio)

        aspectratio = np.array(aspectratio) / max(aspectratio)
        fig['layout']['width'], fig['layout']['height'] = ([ar * figsize * 700 for ar in aspectratio])

    # check if called from ipynb or not in order to consider appropriate plot function
    if _in_ipynb():
        from plotly.offline import init_notebook_mode, iplot as plot
        init_notebook_mode()
    else:
        from plotly.offline import plot as plot

    # delete the plot function here.
    # plot(fig, filename=filename)

    return fig
Example #7
0
def offline_plotly_scatter_bubble(
    df,
    x='x',
    y='y',
    size_col='size',
    text_col='text',
    category_col='category',
    possible_categories=None,
    filename=None,
    config={'displaylogo': False},
    xscale=None,
    yscale='log',
    layout={
        'hovermode': 'closest',
        'showlegend': False,
        'autosize': True
    },
    marker={'sizemode': 'area'},
    min_size=10,
):
    r"""Interactive scatterplot of a DataFrame with the size and color of circles linke to two columns

    config keys:
      fillFrame setBackground displaylogo sendData showLink linkText staticPlot scrollZoom plot3dPixelRatio displayModeBar
      showTips workspace doubleClick autosizable editable

    layout keys:
      angularaxis annotations autosize bargap bargroupgap barmode barnorm boxgap boxgroupgap boxmode calendar
      direction dragmode font geo height hiddenlabels hiddenlabelssrc hidesources hovermode images legend
      mapbox margin orientation paper_bgcolor plot_bgcolor radialaxis scene separators shapes showlegend sliders smith
      ternary title titlefont updatemenus width xaxis yaxis

    marker keys:
      autocolorscale blend border cauto cmax cmin color colorbar colors colorscale colorsrc colorssrc line maxdisplayed
      opacity opacitysrc outliercolor reversescale showscale size sizemax sizemin sizemode sizeref sizesrc symbol symbolsrc

    marker['sizeref'] gives the denominator of the circle scaling factor.
      Typically it should be about a tenth of the minimum 'size' column value

    >>> from nlpia.data.loaders import get_data
    >>> df = get_data('cities_us_wordvectors_pca2_meta').iloc[:100]
    >>> html = offline_plotly_scatter_bubble(
    ...     df.sort_values('population', ascending=False)[:350].copy().sort_values('population'),
    ...     x='x', y='y',
    ...     size_col='population', text_col='name', category_col='timezone',
    ...     xscale=None, yscale=None,  # 'log' or None
    ...     layout={}, marker={'sizeref': 3000})
    """
    config_default = dict(DEFAULT_PLOTLY_CONFIG)
    marker_default = {
        'size': size_col or min_size,
        'sizemode': 'area',
        'sizeref': int(df[size_col].min() * .8) if size_col else min_size
    }
    marker_default.update(marker)
    size_col = marker_default.pop('size')
    layout_default = {
        'xaxis': XAxis(title=x, type=xscale),
        'yaxis': YAxis(title=y, type=yscale),
    }
    layout_default.update(**layout)
    if config is not None:
        config_default.update(config)
    df.columns = clean_columns(df.columns)
    if possible_categories is None and category_col is not None:
        if category_col in df.columns:
            category_labels = df[category_col]
        else:
            category_labels = np.array(category_col)
        possible_categories = list(set(category_labels))
    possible_categories = [
        None
    ] if possible_categories is None else possible_categories
    if category_col and category_col in df:
        masks = [
            np.array(df[category_col] == label)
            for label in possible_categories
        ]
    else:
        masks = [np.array([True] * len(df))] * len(possible_categories)
    data = {
        'data': [
            Scatter(x=df[x][mask].values,
                    y=df[y][mask].values,
                    text=df[text_col][mask].values,
                    marker=Marker(size=df[size_col][mask]
                                  if size_col in df.columns else size_col,
                                  **marker_default),
                    mode='markers',
                    name=str(category_name))
            for (category_name, mask) in zip(possible_categories, masks)
        ],
        'layout':
        Layout(**layout_default)
    }
    return offline_plotly_data(data, filename=filename, config=config_default)
data = [pneumo_size_m_trace, pneumo_size_f_trace]
fig = Figure(data=data, layout=layout)
iplot(fig)
pneumo_size_m_trace = Scatter(x=pneumothorax_df_m['patient_age'].values,
                              y=pneumothorax_df_m['pneumothorax_area'].values,
                              mode='markers',
                              name='Male')

pneumo_size_f_trace = Scatter(x=pneumothorax_df_f['patient_age'].values,
                              y=pneumothorax_df_f['pneumothorax_area'].values,
                              mode='markers',
                              name='Female')

layout = Layout(
    title='Pneumothorax Affected Area vs Age for Male and Female Population',
    yaxis=YAxis(title='Area (in sq mm)'),
    xaxis=XAxis(title='Age'))

data = [pneumo_size_m_trace, pneumo_size_f_trace]
fig = Figure(data=data, layout=layout)
iplot(fig)
size_m = pneumothorax_df_m['pneumothorax_area'].values
size_ref_m = 2. * max(size_m) / (40.**2)
size_f = pneumothorax_df_f['pneumothorax_area'].values
size_ref_f = 2. * max(size_f) / (40.**2)

pneumo_size_m_trace = Scatter(
    x=pneumothorax_df_m['patient_age'].values,
    y=pneumothorax_df_m['encoded_pixels_count'].values,
    marker=dict(size=size_m, sizemode='area', sizeref=size_ref_m, sizemin=4),
    mode='markers',
Example #9
0
)
trace5 = Scatter(
    x=[],
    y=[],
    name="PM2.5",
    stream=dict(token=stream_token_PM25, maxpoints=10000),
)
trace6 = Scatter(
    x=[],
    y=[],
    name="PM10.0",
    stream=dict(token=stream_token_PM10, maxpoints=10000),
)

layout = Layout(title='EnviroPi with ZIO QWIIC Sensors',
                yaxis=YAxis(title='Value'),
                yaxis2=YAxis(title='%'),
                yaxis3=YAxis(title='Lux'),
                yaxis4=YAxis(title='PM1'),
                yaxis5=YAxis(title='PM25'),
                yaxis6=YAxis(title='PM10'))
data = [trace1, trace2, trace3, trace4, trace5, trace6]
fig = Figure(data=data, layout=layout)

print py.plot(fig,
              filename='EnviroPi with ZIO QWIIC sensors',
              fileopt='extend')

stream_temp = py.Stream(stream_token_temp)
stream_temp.open()
Example #10
0
     'bgcolor': 'white',
     'font': {
         'color': 'grey'
     }
 },
 'paper_bgcolor':
 'white',
 'plot_bgcolor':
 'grey',
 'yaxis1':
 YAxis({
     'tickfont': {
         'color': 'grey'
     },
     'gridcolor': 'lightyellow',
     'titlefont': {
         'color': 'grey'
     },
     'zerolinecolor': 'lightyellow',
     'showgrid': True
 }),
 'xaxis1':
 XAxis({
     'tickfont': {
         'color': 'grey'
     },
     'gridcolor': 'lightyellow',
     'titlefont': {
         'color': 'grey'
     },
     'zerolinecolor': 'lightyellow',