Example #1
0
def XPlineplot(selectedPlayer):
    """Create individual player XP line plot.
    """
    plotdata = activityToPointsMapper(selectedPlayer).sum(axis=1).reset_index()
    plotdata.columns = ['semana', 'XP']
    plotdata['semana'] = plotdata['semana'].apply(pd.to_datetime)
    XPlineplot = alt.Chart(
        plotdata,
        width=697,
        height=400,
        title='XP semanal - {}'.format(selectedPlayer)).mark_area(
            point={
                'color': '#744a98',
                'size': 70
            },
            line={
                'color': '#744a98'
            },
            color=alt.Gradient(gradient='linear',
                               stops=[
                                   alt.GradientStop(color='#23ac76', offset=0),
                                   alt.GradientStop(color='#23ac7640',
                                                    offset=1)
                               ],
                               x1=1.5,
                               x2=1.25,
                               y1=1,
                               y2=0.1)).encode(
                                   alt.X('semana:T',
                                         axis=alt.Axis(values=list(
                                             plotdata['semana'].array),
                                                       format='%d/%m',
                                                       grid=False)),
                                   alt.Y('XP:Q'))
    return XPlineplot
Example #2
0
def get_line(data_dict, sampling_freq, **kwargs):
    source = pd.DataFrame(list(data_dict))

    source.ts = source.ts.astype("datetime64[ms]")

    source = source.set_index("ts").resample(sampling_freq).mean().reset_index().bfill()

    base_chart = (
        alt.Chart(source)
        .mark_area(
            line={"color": "darkgreen"},
            color=alt.Gradient(
                gradient="linear",
                stops=[
                    alt.GradientStop(color="white", offset=0),
                    alt.GradientStop(color="darkgreen", offset=1),
                ],
                x1=1,
                x2=1,
                y1=1,
                y2=0,
            ),
        )
        .encode(
            x=alt.X("ts:T"),
            y=alt.Y(
                "price:Q",
                scale=alt.Scale(domain=[source.price.min(), source.price.max()]),
            ),
        )
    )

    return base_chart
Example #3
0
    def return_chart(self, start, end):
        source = self.calculate_log_return(start, end)

        chart = (
            alt.Chart(source)
            .mark_area(
                line={"color": "darkblue"},
                color=alt.Gradient(
                    gradient="linear",
                    stops=[
                        alt.GradientStop(color="white", offset=0),
                        alt.GradientStop(color="darkblue", offset=1),
                    ],
                    x1=1,
                    x2=1,
                    y1=1,
                    y2=0,
                ),
            )
            .encode(
                x=alt.X("Date:T", axis=alt.Axis(format="%Y/%m")),
                y=alt.Y("Cum Return:Q", title="Cumulative Return"),
            )
        )
        return chart
Example #4
0
def type_gradient(df, type, color):
    return alt.Chart(df).transform_filter(
        f'datum.symbol==="{type}"').mark_area(
            line={
                'color': color
            },
            color=alt.Gradient(
                gradient='linear',
                stops=[
                    alt.GradientStop(color='white', offset=0),
                    alt.GradientStop(color=color, offset=1)
                ],
                x1=1,
                x2=1,
                y1=1,
                y2=0)).encode(x=alt.X('date:T',
                                      axis=alt.Axis(title='Weeks',
                                                    titleFontSize=18,
                                                    titlePadding=20,
                                                    titleColor='gray')),
                              y=alt.Y('number:Q',
                                      axis=alt.Axis(title='Number of Cases',
                                                    titleFontSize=18,
                                                    titlePadding=20,
                                                    titleColor='gray')))
Example #5
0
def Charts(df,clm,C):
    chart=alt.Chart(df[df.Legend==clm]).mark_area(line={'color':C},
        color=alt.Gradient(    gradient='linear',
        stops=[alt.GradientStop(color='white', offset=.01),
               alt.GradientStop(color=C, offset=1)] ,
        x1=1,
        x2=1,
        y1=1,
        y2=0)
        ).encode(
        x='Days',
        y='% of Population:Q',
        
        tooltip='% of Population',
        opacity=alt.value(.5)).properties(
        height=300,
        width=730).interactive()
    return chart 
Example #6
0
def alt_ploting(df):
    df.reset_index(inplace=True)
    df['Dates'] = df.Dates.dt.date
    col_names = df.columns
    # print(col_names)
    c = alt.Chart(df).mark_area(line={
        'color': 'darkgreen'
    },
                                color=alt.Gradient(
                                    gradient='linear',
                                    stops=[
                                        alt.GradientStop(color='white',
                                                         offset=0),
                                        alt.GradientStop(color='darkred',
                                                         offset=1)
                                    ],
                                    x1=1,
                                    x2=1,
                                    y1=1,
                                    y2=0)).encode(alt.X('Dates:T'),
                                                  alt.Y('LR_Prediction:Q'))
    st.altair_chart(c, use_container_width=True)
Example #7
0
def returns_chart(self, start=None, end=None):
    returns = self.check_returns(returns)
    returns_chart = (
        alt.Chart(returns)
        .mark_area(
            line={"color": "darkgreen"},
            color=alt.Gradient(
                gradient="linear",
                stops=[
                    alt.GradientStop(color="white", offset=0),
                    alt.GradientStop(color="darkgreen", offset=1),
                ],
                x1=1,
                x2=1,
                y1=1,
                y2=0,
            ),
        )
        .encode(
            x=alt.X("Date:T", axis=alt.Axis(format="%Y/%m/%d")),
            y=alt.Y("Cum Return:Q", title="Cumulative Return"),
        )
    )
    return returns_chart
"""
Area Chart with Gradient
------------------------
This example shows how to make an area chart with a gradient fill. 
For more information about gradient options see the Vega-Lite `Gradient documentation <https://vega.github.io/vega-lite/docs/types.html#gradient>`_.
"""
# category: area charts

import altair as alt
from vega_datasets import data

source = data.stocks()

alt.Chart(source).transform_filter(
    'datum.symbol==="GOOG"'
).mark_area(
    line={'color':'darkgreen'},
    color=alt.Gradient(
        gradient='linear', 
        stops=[alt.GradientStop(color='white', offset=0), 
               alt.GradientStop(color='darkgreen', offset=1)], 
        x1=1, 
        x2=1, 
        y1=1, 
        y2=0
    )
).encode(
    alt.X('date:T'), 
    alt.Y('price:Q')
)
def altairEdgePercentageHistoram(df):
    """
    Construct an altair area plot for dodo price edge histogram. 

    Parameters
    ----------
    df : pandas.core.frame.DataFrame
        pandas dataframe containing the stored historical price data for dodo and 
        chainlink for a given currency pair.

    Returns
    -------
    chart : altair.vegalite.v4.api.LayerChart
        altair composite chart containing histogram data of price advantage percentage.

    """
    source = pd.DataFrame()
    currentEdge = df.dodoPriceEdgePercentage.values[-1]
    #define vertical line data for zero and for current (most recent) edge value
    verticals = pd.DataFrame([{"zero": 0, "currentEdge": currentEdge}])
    yy = df.dodoPriceEdgePercentage
    x = np.linspace(np.min(yy), np.max(yy), 200)
    #use scipy stats module to build kde histogram function, rather than dealing with bins:
    y = stats.gaussian_kde(yy)(x)
    #get the symmetric x limits based on max mag data value:
    maxmag = np.max(np.abs(yy))
    xlims = (-maxmag, maxmag)
    source['percentEdge'] = x
    source['kdeWeight'] = y

    #build positive edge histogram (green):
    histPos = alt.Chart(source).transform_filter(
        alt.datum.percentEdge >= 0).mark_area(
            line={
                'color': 'darkgreen'
            },
            color=alt.Gradient(gradient='linear',
                               stops=[
                                   alt.GradientStop(color='lightGreen',
                                                    offset=0),
                                   alt.GradientStop(color='darkGreen',
                                                    offset=1)
                               ],
                               x1=1,
                               x2=1,
                               y1=1,
                               y2=0)).encode(
                                   alt.X('percentEdge:Q',
                                         scale=alt.Scale(domain=xlims)),
                                   alt.Y('kdeWeight:Q')).interactive()

    #build negative edge histogram (red)
    histNeg = alt.Chart(source).transform_filter(
        alt.datum.percentEdge < 0).mark_area(
            line={
                'color': '#8b0000'
            },
            color=alt.Gradient(
                gradient='linear',
                stops=[
                    alt.GradientStop(color='#E6676B', offset=0),
                    alt.GradientStop(color='#8b0000', offset=1)
                ],
                x1=1,
                x2=1,
                y1=1,
                y2=0)).encode(
                    alt.X('percentEdge:Q',
                          axis=alt.Axis(title="DODO % Price Edge",
                                        titleFontWeight=500,
                                        titleFontSize=20),
                          scale=alt.Scale(domain=xlims)),
                    alt.Y('kdeWeight:Q',
                          axis=alt.Axis(title="historical distribution",
                                        labels=False,
                                        titleFontWeight=500,
                                        titleFontSize=20))).interactive()

    #add vertical line at zero for visual reference
    zeroRule = alt.Chart(verticals).mark_rule(color="white").encode(
        alt.X("zero:Q", axis=alt.Axis(title='')))
    #add vertical line at current edge value in yellow for visual reference
    currentEdgeRule = alt.Chart(verticals).mark_rule(color="yellow").encode(
        alt.X("currentEdge:Q", axis=alt.Axis(title=''))).interactive()
    #construct chart as composite of components charts and lines
    chart = (zeroRule + currentEdgeRule + histNeg + histPos).interactive()
    return chart
Example #10
0
                                       y=alt.Y("Aminoacid", sort="-x"))
st.altair_chart(p)

########################
# Predictor results
########################
# Area Chart for predictor
df_predictor = pd.DataFrame({
    "Scores":
    data[selected_protein]["predictors"][selected_predictor]['scores']
})
df_predictor['Pos'] = list(range(1, df_predictor.shape[0] + 1))

st.subheader("Results form {} predictor".format(selected_predictor))
p = alt.Chart(df_predictor).mark_area(
    line={
        "color": 'darkblue'
    },
    color=alt.Gradient(gradient="linear",
                       stops=[
                           alt.GradientStop(color='white', offset=0),
                           alt.GradientStop(color='darkblue', offset=1)
                       ],
                       x1=1,
                       x2=1,
                       y1=1,
                       y2=0)).encode(alt.X("Pos", title="Position"),
                                     alt.Y("Scores")).properties(width=600,
                                                                 height=180)
st.altair_chart(p)
Example #11
0
def bv_areaPlot(data, engine, xlabel, ylabel1, ylabel2):
    data = data.copy() 
    data.rename(columns={'plotY':ylabel1, 'plotX1':ylabel2}, inplace=True)

    if engine == 'Static':
        fig, axes = plt.subplots(figsize=(9,6))

        _index = data.index.tolist()

        axes.fill_between(_index, data[ylabel1].values)
        axes.legend([ylabel1], loc=0)
        axes_r = axes.twinx()
        axes_r.fill_between(_index, data[ylabel2].values, color='orange')
        axes_r.legend([ylabel2], loc=0)

        axes.set_xlabel(xlabel, fontsize = 15)
        axes.set_ylabel(ylabel1, fontsize = 15)
        axes_r.set_ylabel(ylabel2, fontsize = 15)
        axes.grid(b=True, which='major', color='k', linewidth=0.25)
                
        plt.close()
        return pn.pane.Matplotlib(fig, tight=True)
    
    elif engine == 'Interactive':
        data=data.dropna()
        # Selection Brush
        brush = alt.selection(type='interval', encodings=['x'], name='isel')
        # Base Plot
        base = alt.Chart(data.reset_index())
        base = base.encode(x = alt.X('{0}:T'.format(data.index.name), title=''),
                        tooltip = ylabel1)
        base = base.properties(width = 580, height = 275)
        # Upper Plot
        upper1 = base.mark_area(line={'color':'#3d84ba'},
                                    color=alt.Gradient(
                                        gradient='linear',
                                        stops=[alt.GradientStop(color='white', offset=0),
                                            alt.GradientStop(color='#3d84ba', offset=1)],
                                        x1=1, x2=1,
                                        y1=1, y2=0
                                    ))
        upper1 = upper1.encode(x = alt.X('{0}:T'.format(data.index.name), scale=alt.Scale(domain=brush), title=''),
                               y = alt.Y('{0}:Q'.format(ylabel1), scale=alt.Scale(zero=False), axis=alt.Axis(format='~s')))
        upper2 = base.mark_area(line={'color':'#f57542'},
                                    color=alt.Gradient(
                                        gradient='linear',
                                        stops=[alt.GradientStop(color='white', offset=0),
                                            alt.GradientStop(color='#f57542', offset=1)],
                                        x1=1, x2=1,
                                        y1=1, y2=0
                                    ))
        upper2 = upper2.encode(x = alt.X('{0}:T'.format(data.index.name), scale=alt.Scale(domain=brush), title=''),
                            y = alt.Y('{0}:Q'.format(ylabel2), scale=alt.Scale(zero=False), axis=alt.Axis(format='~s')))
        # Lower Plot
        lower = base.mark_area(line={'color':'darkgray'},
            color=alt.Gradient(
                gradient='linear',
                stops=[alt.GradientStop(color='white', offset=0),
                    alt.GradientStop(color='darkgray', offset=1)],
                x1=1, x2=1,
                y1=1, y2=0
            ))

        lower = lower.encode(y=alt.Y('{0}:Q'.format(ylabel1), title='', axis=None))
        lower = lower.properties(height=20)
        lower = lower.add_selection(brush)
        lower.encoding.x.title = 'Interval Selection'

        # Base Statistics1
        base_stat1 = upper1.transform_filter(brush)
        base_stat1 = base_stat1.transform_aggregate(Mean1='mean({0})'.format(ylabel1),
                                                    StdDev1='stdev({0})'.format(ylabel1),
                                                    Var1='variance({0})'.format(ylabel1))
        label_stat1 = base_stat1.transform_calculate(stat_label1="'Mean = ' + format(datum.Mean1, '~s') + \
                                                    '; Standard Deviation = ' + format(datum.StdDev1, '~s') +\
                                                    '; Variance = ' + format(datum.Var1, '~s')")
        label_stat1 = label_stat1.mark_text(align='left', baseline='bottom', color='#3d84ba')
        label_stat1 = label_stat1.encode(x=alt.value(0.0), y=alt.value(12.0), text=alt.Text('stat_label1:N'))
        # Base Statistics2
        base_stat2 = upper2.transform_filter(brush)
        base_stat2 = base_stat2.transform_aggregate(Mean2='mean({0})'.format(ylabel2),
                                                    StdDev2='stdev({0})'.format(ylabel2),
                                                    Var2='variance({0})'.format(ylabel2))
        label_stat2 = base_stat2.transform_calculate(stat_label1="'Mean = ' + format(datum.Mean2, '~s') + \
                                                    '; Standard Deviation = ' + format(datum.StdDev2, '~s') +\
                                                    '; Variance = ' + format(datum.Var2, '~s')")
        label_stat2 = label_stat2.mark_text(align='left', baseline='bottom', color='#f57542')
        label_stat2 = label_stat2.encode(x=alt.value(0.0), y=alt.value(25.0), text=alt.Text('stat_label1:N'))

        upper1 = upper1 + label_stat1
        upper2 = upper2 + label_stat2
        upper = (upper1+upper2).resolve_scale(y='independent')

        ## Y LABEL 1
        # Values
        _ymean_uu1 = data[ylabel1].max()
        _ymean1 = data[ylabel1].mean()
        # Inspired from :- https://stats.stackexchange.com/a/350278
        _maxvar_in_slice1 = ((data[ylabel1].max()-data[ylabel1].min())/2)**2
        _ystd_uu1 = np.sqrt(_maxvar_in_slice1)
        _ystd1 = data[ylabel1].std()
        _yvar_uu1 = _maxvar_in_slice1
        _yvar1 = data[ylabel1].var()
        # Stat Bar Base
        stats_barbase1 = base_stat1.mark_bar(color='#3d84ba')
        stats_barbase1 = stats_barbase1.properties(width = 188, height = 20)
        # Mean Bar
        mean_bar1 = stats_barbase1.encode(x=alt.X('Mean1:Q', title='',
                                                scale=alt.Scale(domain=[-_ymean_uu1,_ymean_uu1]),
                                                axis=alt.Axis(format='~s')), y=alt.value(10.5))
        totmean_line1 = alt.Chart(pd.DataFrame({'x': [_ymean1]}))
        totmean_line1 = totmean_line1.mark_rule(color='red', size=5)
        totmean_line1 = totmean_line1.encode(x='x')
        mean_bar1 += totmean_line1
        # Standard Deviation Bar
        std_bar1 = stats_barbase1.encode(x=alt.X('StdDev1:Q', title='',
                                                scale=alt.Scale(domain=[-_ystd_uu1,_ystd_uu1]),
                                                axis=alt.Axis(format='~s')), y=alt.value(10.5))
        totstd_line1 = alt.Chart(pd.DataFrame({'x': [_ystd1]}))
        totstd_line1 = totstd_line1.mark_rule(color='red', size=5)
        totstd_line1 = totstd_line1.encode(x='x')
        std_bar1 += totstd_line1
        # Variance Bar
        var_bar1 = stats_barbase1.encode(x=alt.X('Var1:Q', title='',
                                                scale=alt.Scale(domain=[-_yvar_uu1,_yvar_uu1]),
                                                axis=alt.Axis(format='~s')), y=alt.value(10.5))
        totvar_line1 = alt.Chart(pd.DataFrame({'x': [_yvar1]}))
        totvar_line1 = totvar_line1.mark_rule(color='red', size=5)
        totvar_line1 = totvar_line1.encode(x='x')
        var_bar1 += totvar_line1

        ## Y LABEL 2
        # Values
        _ymean_uu2 = data[ylabel2].max()
        _ymean2 = data[ylabel2].mean()
        # Inspired from :- https://stats.stackexchange.com/a/350278
        _maxvar_in_slice2 = ((data[ylabel2].max()-data[ylabel2].min())/2)**2
        _ystd_uu2 = np.sqrt(_maxvar_in_slice2)
        _ystd2 = data[ylabel2].std()
        _yvar_uu2 = _maxvar_in_slice2
        _yvar2 = data[ylabel2].var()
        # Stat Bar Base
        stats_barbase2 = base_stat2.mark_bar(color='#f57542')
        stats_barbase2 = stats_barbase2.properties(width = 188, height = 20)
        # Mean Bar
        mean_bar2 = stats_barbase2.encode(x=alt.X('Mean2:Q', title='Mean',
                                                scale=alt.Scale(domain=[-_ymean_uu2,_ymean_uu2]),
                                                axis=alt.Axis(format='~s')), y=alt.value(10.5))
        totmean_line2 = alt.Chart(pd.DataFrame({'x': [_ymean2]}))
        totmean_line2 = totmean_line2.mark_rule(color='red', size=5)
        totmean_line2 = totmean_line2.encode(x='x')
        mean_bar2 += totmean_line2
        # Standard Deviation Bar
        std_bar2 = stats_barbase2.encode(x=alt.X('StdDev2:Q', title='Std',
                                                scale=alt.Scale(domain=[-_ystd_uu2,_ystd_uu2]),
                                                axis=alt.Axis(format='~s')), y=alt.value(10.5))
        totstd_line2 = alt.Chart(pd.DataFrame({'x': [_ystd2]}))
        totstd_line2 = totstd_line2.mark_rule(color='red', size=5)
        totstd_line2 = totstd_line2.encode(x='x')
        std_bar2 += totstd_line2
        # Variance Bar
        var_bar2 = stats_barbase2.encode(x=alt.X('Var2:Q', title='Var',
                                                scale=alt.Scale(domain=[-_yvar_uu2,_yvar_uu2]),
                                                axis=alt.Axis(format='~s')), y=alt.value(10.5))
        totvar_line2 = alt.Chart(pd.DataFrame({'x': [_yvar2]}))
        totvar_line2 = totvar_line2.mark_rule(color='red', size=5)
        totvar_line2 = totvar_line2.encode(x='x')
        var_bar2 += totvar_line2

        # Concatenated
        # p = alt.vconcat(upper+label_stat, mean_bar|std_bar|var_bar, lower).configure_concat(spacing=2)
        p = alt.vconcat(upper, mean_bar1|std_bar1|var_bar1, mean_bar2|std_bar2|var_bar2, lower).configure_concat(spacing=2)
        p = p.configure_axisLeft(labelColor = '#3d84ba', titleColor = '#3d84ba')
        p = p.configure_axisRight(labelColor = '#f57542', titleColor = '#f57542')

        return p
Example #12
0
def uv_candlestickPlot(data, engine, xlabel, ylabel):
    data = data.copy()
    if engine == 'Static':
        fig, _ = mpf.plot(data,
                          type='candlestick',
                          figsize=(9, 6),
                          volume=True,
                          style='charles',
                          returnfig=True)
        plt.close()
        return pn.pane.Matplotlib(fig, tight=True)

    elif engine == 'Interactive':
        data.columns = [k.lower() for k in data.columns]
        # Selection Brush
        brush = alt.selection(type='interval', encodings=['x'])
        open_close_color = alt.condition("datum.open <= datum.close",
                                         alt.value("#06982d"),
                                         alt.value("#ae1325"))
        base = alt.Chart(data.reset_index())
        base = base.encode(alt.X('{0}:T'.format(data.index.name),
                                 title='',
                                 axis=None,
                                 scale=alt.Scale(domain=brush)),
                           color=open_close_color,
                           tooltip=['open', 'high', 'low', 'close'])
        # Rule
        rule = base.mark_rule()
        rule = rule.encode(
            alt.Y('low:Q', title='Price', scale=alt.Scale(zero=False)),
            alt.Y2('high:Q'))
        # Bars
        bar = base.mark_bar()
        bar = bar.encode(alt.Y('open:Q'), alt.Y2('close:Q'))
        # Candlestick Chart
        candlestick_chart = rule + bar
        candlestick_chart = candlestick_chart.properties(width=600, height=280)
        candlestick_chart = candlestick_chart.transform_filter(brush)
        # Volume Chart
        volume_chart = alt.Chart(data.reset_index())
        volume_chart = volume_chart.mark_bar()
        volume_chart = volume_chart.encode(alt.X(
            '{0}:T'.format(data.index.name),
            title='',
            scale=alt.Scale(domain=brush)),
                                           alt.Y('volume:Q',
                                                 axis=alt.Axis(format='~s')),
                                           color=open_close_color)
        volume_chart = volume_chart.transform_filter(brush)
        volume_chart = volume_chart.properties(width=600, height=60)
        # Selection Chart
        lower = alt.Chart(data.reset_index())
        lower = lower.mark_area(line={'color': 'darkgray'},
                                color=alt.Gradient(
                                    gradient='linear',
                                    stops=[
                                        alt.GradientStop(color='white',
                                                         offset=0),
                                        alt.GradientStop(color='darkgray',
                                                         offset=1)
                                    ],
                                    x1=1,
                                    x2=1,
                                    y1=1,
                                    y2=0))
        lower = lower.encode(x=alt.X('{0}:T'.format(data.index.name)),
                             y=alt.Y('{0}:Q'.format('close'), title=''))
        lower = lower.properties(height=20, width=600)
        lower = lower.add_selection(brush)
        lower.encoding.x.title = 'Interval Selection'
        # Concatenated Chart
        p = alt.vconcat(candlestick_chart, volume_chart,
                        lower).configure_concat(spacing=0)
        return p
Example #13
0
def uv_expSmoothPlot(data, engine, xlabel, ylabel):
    # Data Prep
    data = data.copy()
    data.rename(columns={'plotX1': ylabel}, inplace=True)
    _config_expspan = TSMAD_CONFIGS['plotting.uv.exp_span']
    if isinstance(_config_expspan, float):
        exp_span = max([int(_config_expspan * data.shape[0]), 3])
    elif isinstance(_config_expspan, int):
        exp_span = _config_expspan

    exp_colname = 'Moving Average ({0})'.format(exp_span)
    data[exp_colname] = data[ylabel].ewm(span=exp_span).mean()

    if engine == 'Static':

        fig = data[[ylabel, exp_colname]].plot(figsize=(9, 6),
                                               legend=True).figure
        plt.xlabel(xlabel, fontsize=15)
        plt.ylabel(ylabel, fontsize=15)
        plt.grid(b=True, which='major', color='k', linewidth=0.25)
        plt.grid(b=True, which='minor', color='k', linewidth=0.125)
        plt.close()
        return pn.pane.Matplotlib(fig, tight=True)

    elif engine == 'Interactive':
        # Selection Brush
        brush = alt.selection(type='interval', encodings=['x'], name='isel')
        # Base Plot
        base = alt.Chart(data.reset_index()).mark_line()
        base = base.encode(x=alt.X('{0}:T'.format(data.index.name), title=''),
                           tooltip=ylabel)
        base = base.properties(width=620, height=360)
        # Upper Plot
        x_ecoder = x = alt.X('{0}:T'.format(data.index.name),
                             scale=alt.Scale(domain=brush),
                             title='')
        upper = base.encode(x=x_ecoder,
                            y=alt.Y('{0}:Q'.format(ylabel),
                                    scale=alt.Scale(zero=False),
                                    axis=alt.Axis(format='~s')),
                            tooltip=[ylabel])
        # Exponential Smoothing Line
        exp_line = upper.encode(x=alt.X('{0}:T'.format(data.index.name),
                                        scale=alt.Scale(domain=brush),
                                        title=''),
                                color=alt.ColorValue('red'),
                                y=alt.Y('{0}:Q'.format(exp_colname),
                                        scale=alt.Scale(zero=False),
                                        axis=alt.Axis(format='~s')))
        # Lower Plot
        lower = base.mark_area(line={'color': 'darkgray'},
                               color=alt.Gradient(
                                   gradient='linear',
                                   stops=[
                                       alt.GradientStop(color='white',
                                                        offset=0),
                                       alt.GradientStop(color='darkgray',
                                                        offset=1)
                                   ],
                                   x1=1,
                                   x2=1,
                                   y1=1,
                                   y2=0))
        lower = lower.encode(
            y=alt.Y('{0}:Q'.format(ylabel), title='', axis=None))
        lower = lower.properties(height=20)
        lower = lower.add_selection(brush)
        lower.encoding.x.title = 'Interval Selection'
        # Concatenated
        p = alt.vconcat(upper + exp_line, lower).configure_concat(spacing=2)

        return p
Example #14
0
def uv_linePlot(data, engine, xlabel, ylabel):
    data = data.copy()
    data.rename(columns={'plotX1': ylabel}, inplace=True)
    if engine == 'Static':

        fig = data[ylabel].plot(figsize=(9, 6), legend=True).figure
        plt.xlabel(xlabel, fontsize=15)
        plt.ylabel(ylabel, fontsize=15)
        plt.grid(b=True, which='major', color='k', linewidth=0.25)
        plt.grid(b=True, which='minor', color='k', linewidth=0.125)

        plt.close()
        return pn.pane.Matplotlib(fig, tight=True)

    elif engine == 'Interactive':

        # Selection Brush
        brush = alt.selection(type='interval', encodings=['x'], name='isel')
        # Base Plot
        base = alt.Chart(data.dropna().reset_index()).mark_line()
        base = base.encode(x=alt.X('{0}:T'.format(data.index.name), title=''),
                           tooltip=ylabel)
        base = base.properties(width=612, height=300)
        # Upper Plot
        upper = base.encode(x=alt.X('{0}:T'.format(data.index.name),
                                    scale=alt.Scale(domain=brush),
                                    title=''),
                            y=alt.Y('{0}:Q'.format(ylabel),
                                    scale=alt.Scale(zero=False),
                                    axis=alt.Axis(format='~s')))
        # Lower Plot
        lower = base.mark_area(line={'color': 'darkgray'},
                               color=alt.Gradient(
                                   gradient='linear',
                                   stops=[
                                       alt.GradientStop(color='white',
                                                        offset=0),
                                       alt.GradientStop(color='darkgray',
                                                        offset=1)
                                   ],
                                   x1=1,
                                   x2=1,
                                   y1=1,
                                   y2=0))
        lower = lower.encode(
            y=alt.Y('{0}:Q'.format(ylabel), title='', axis=None))
        lower = lower.properties(height=20)
        lower = lower.add_selection(brush)
        lower.encoding.x.title = 'Interval Selection'
        # Base Statistics
        base_stat = upper.transform_filter(brush)
        base_stat = base_stat.transform_aggregate(
            Mean='mean({0})'.format(ylabel),
            StdDev='stdev({0})'.format(ylabel),
            Var='variance({0})'.format(ylabel))
        # Label Statistics
        label_stat = base_stat.transform_calculate(
            stat_label="'Mean = ' + format(datum.Mean, '~s') + \
            '; Standard Deviation = ' + format(datum.StdDev, '~s') +\
            '; Variance = ' + format(datum.Var, '~s')")
        label_stat = label_stat.mark_text(align='left', baseline='bottom')
        label_stat = label_stat.encode(x=alt.value(0.0),
                                       y=alt.value(12.0),
                                       text=alt.Text('stat_label:N'))
        # Values
        _ymean_uu = data[ylabel].max()
        _ymean = data[ylabel].mean()
        # Inspired from :- https://stats.stackexchange.com/a/350278
        _maxvar_in_slice = ((data[ylabel].max() - data[ylabel].min()) / 2)**2
        _ystd_uu = np.sqrt(_maxvar_in_slice)
        _ystd = data[ylabel].std()
        _yvar_uu = _maxvar_in_slice
        _yvar = data[ylabel].var()
        # Stat Bar Base
        stats_barbase = base_stat.mark_bar()
        stats_barbase = stats_barbase.properties(width=200, height=20)
        # Mean Bar
        mean_bar = stats_barbase.encode(x=alt.X(
            'Mean:Q',
            title='Mean',
            scale=alt.Scale(domain=[-_ymean_uu, _ymean_uu]),
            axis=alt.Axis(format='~s')),
                                        y=alt.value(10.5))
        totmean_line = alt.Chart(pd.DataFrame({'x': [_ymean]}))
        totmean_line = totmean_line.mark_rule(color='red', size=5)
        totmean_line = totmean_line.encode(x='x')
        mean_bar += totmean_line
        # Standard Deviation Bar
        std_bar = stats_barbase.encode(x=alt.X(
            'StdDev:Q',
            title='Std',
            scale=alt.Scale(domain=[-_ystd_uu, _ystd_uu]),
            axis=alt.Axis(format='~s')),
                                       y=alt.value(10.5))
        totstd_line = alt.Chart(pd.DataFrame({'x': [_ystd]}))
        totstd_line = totstd_line.mark_rule(color='red', size=5)
        totstd_line = totstd_line.encode(x='x')
        std_bar += totstd_line
        # Variance Bar
        var_bar = stats_barbase.encode(x=alt.X(
            'Var:Q',
            title='Var',
            scale=alt.Scale(domain=[-_yvar_uu, _yvar_uu]),
            axis=alt.Axis(format='~s')),
                                       y=alt.value(10.5))
        totvar_line = alt.Chart(pd.DataFrame({'x': [_yvar]}))
        totvar_line = totvar_line.mark_rule(color='red', size=5)
        totvar_line = totvar_line.encode(x='x')
        var_bar += totvar_line
        # Concatenated
        p = alt.vconcat(upper + label_stat, mean_bar | std_bar | var_bar,
                        lower).configure_concat(spacing=2)

        return p