Python altair.value() Examples

The following are 16 code examples of altair.value(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module altair , or try the search function .
Example #1
Source File: plot.py    From retentioneering-tools with Mozilla Public License 2.0 6 votes vote down vote up
def altair_step_matrix(diff, plot_name=None, title='', vmin=None, vmax=None, font_size=12, **kwargs):
    heatmap_data = diff.reset_index().melt('index')
    heatmap_data.columns = ['y', 'x', 'z']
    table = alt.Chart(heatmap_data).encode(
        x=alt.X('x:O', sort=None),
        y=alt.Y('y:O', sort=None)
    )
    heatmap = table.mark_rect().encode(
        color=alt.Color(
            'z:Q',
            scale=alt.Scale(scheme='blues'),
        )
    )
    text = table.mark_text(
        align='center', fontSize=font_size
    ).encode(
        text='z',
        color=alt.condition(
            abs(alt.datum.z) < 0.8,
            alt.value('black'),
            alt.value('white'))
    )
    heatmap_object = (heatmap + text).properties(
        width=3 * font_size * len(diff.columns),
        height=2 * font_size * diff.shape[0]
    )
    return heatmap_object, plot_name, None, diff.retention.retention_config 
Example #2
Source File: test_core.py    From altair with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_infer_encoding_types(channels):
    expected = dict(
        x=channels.X("xval"),
        y=channels.YValue("yval"),
        strokeWidth=channels.StrokeWidthValue(value=4),
    )

    # All positional args
    args, kwds = _getargs(
        channels.X("xval"), channels.YValue("yval"), channels.StrokeWidthValue(4)
    )
    assert infer_encoding_types(args, kwds, channels) == expected

    # All keyword args
    args, kwds = _getargs(x="xval", y=alt.value("yval"), strokeWidth=alt.value(4))
    assert infer_encoding_types(args, kwds, channels) == expected

    # Mixed positional & keyword
    args, kwds = _getargs(
        channels.X("xval"), channels.YValue("yval"), strokeWidth=alt.value(4)
    )
    assert infer_encoding_types(args, kwds, channels) == expected 
Example #3
Source File: test_core.py    From altair with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_infer_dtype(value, expected_type):
    assert infer_dtype(value) == expected_type 
Example #4
Source File: test_core.py    From altair with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_infer_encoding_types_with_condition(channels):
    args, kwds = _getargs(
        x=alt.condition("pred1", alt.value(1), alt.value(2)),
        y=alt.condition("pred2", alt.value(1), "yval"),
        strokeWidth=alt.condition("pred3", "sval", alt.value(2)),
    )
    expected = dict(
        x=channels.XValue(2, condition=channels.XValue(1, test="pred1")),
        y=channels.Y("yval", condition=channels.YValue(1, test="pred2")),
        strokeWidth=channels.StrokeWidthValue(
            2, condition=channels.StrokeWidth("sval", test="pred3")
        ),
    )
    assert infer_encoding_types(args, kwds, channels) == expected 
Example #5
Source File: mixins.py    From traffic with MIT License 5 votes vote down vote up
def area(self) -> float:
        """Returns the area of the shape, in square meters.
        The shape is projected to an equivalent local projection before
        computing a value.
        """
        return self.project_shape().area

    # --- Representations --- 
Example #6
Source File: mixins.py    From traffic with MIT License 5 votes vote down vote up
def geoencode(self) -> alt.Chart:  # coverage: ignore
        """Returns an `altair <http://altair-viz.github.io/>`_ encoding of the
        shape to be composed in an interactive visualization.
        """
        return (
            alt.Chart(self.data)
            .mark_circle()
            .encode(
                longitude="longitude:Q",
                latitude="latitude:Q",
                size=alt.value(3),
                color=alt.value("steelblue"),
            )
        ) 
Example #7
Source File: covid19_dataviz.py    From traffic with MIT License 5 votes vote down vote up
def airline_chart(
    source: alt.Chart, subset: List[str], name: str, loess=True
) -> alt.Chart:

    chart = source.transform_filter(
        alt.FieldOneOfPredicate(field="airline", oneOf=subset)
    )

    highlight = alt.selection(
        type="single", nearest=True, on="mouseover", fields=["airline"]
    )

    points = (
        chart.mark_point()
        .encode(
            x="day",
            y=alt.Y("rate", title="# of flights (normalized)"),
            color=alt.Color("airline", legend=alt.Legend(title=name)),
            tooltip=["day", "airline", "count"],
            opacity=alt.value(0.3),
        )
        .add_selection(highlight)
    )

    lines = chart.mark_line().encode(
        x="day",
        y="rate",
        color="airline",
        size=alt.condition(~highlight, alt.value(1), alt.value(3)),
    )
    if loess:
        lines = lines.transform_loess(
            "day", "rate", groupby=["airline"], bandwidth=0.2
        )

    return lines + points 
Example #8
Source File: covid19_dataviz.py    From traffic with MIT License 5 votes vote down vote up
def airport_chart(source: alt.Chart, subset: List[str], name: str) -> alt.Chart:

    chart = source.transform_filter(
        alt.FieldOneOfPredicate(field="airport", oneOf=subset)
    )

    highlight = alt.selection(
        type="single", nearest=True, on="mouseover", fields=["airport"]
    )

    points = (
        chart.mark_point()
        .encode(
            x="day",
            y=alt.Y("count", title="# of departing flights"),
            color=alt.Color("airport", legend=alt.Legend(title=name)),
            tooltip=["day", "airport", "city", "count"],
            opacity=alt.value(0.3),
        )
        .add_selection(highlight)
    )

    lines = (
        chart.mark_line()
        .encode(
            x="day",
            y="count",
            color="airport",
            size=alt.condition(~highlight, alt.value(1), alt.value(3)),
        )
        .transform_loess("day", "count", groupby=["airport"], bandwidth=0.2)
    )

    return lines + points 
Example #9
Source File: iplot.py    From spectrum_utils with Apache License 2.0 5 votes vote down vote up
def mirror(spec_top: MsmsSpectrum, spec_bottom: MsmsSpectrum,
           spectrum_kws: Optional[Dict] = None, *_) -> altair.LayerChart:
    """
    Mirror plot two MS/MS spectra.

    Parameters
    ----------
    spec_top : MsmsSpectrum
        The spectrum to be plotted on the top.
    spec_bottom : MsmsSpectrum
        The spectrum to be plotted on the bottom.
    spectrum_kws : Optional[Dict], optional
        Keyword arguments for `iplot.spectrum`.
    *_
        Ignored, for consistency with the `plot.mirror` API.

    Returns
    -------
    altair.LayerChart
        The Altair chart instance with the plotted spectrum.
    """
    if spectrum_kws is None:
        spectrum_kws = {}
    # Top spectrum.
    spec_plot = spectrum(spec_top, mirror_intensity=False, **spectrum_kws)
    # Mirrored bottom spectrum.
    spec_plot += spectrum(spec_bottom, mirror_intensity=True, **spectrum_kws)

    spec_plot += (altair.Chart(pd.DataFrame({'sep': [0]}))
                  .mark_rule(size=3).encode(
                      y='sep', color=altair.value('lightGray')))

    return spec_plot 
Example #10
Source File: core.py    From starborn with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def heatmap(data, vmin=None, vmax=None, annot=None, fmt='.2g'):

    # We always want to have a DataFrame with semantic information
    if not isinstance(data, pd.DataFrame):
        matrix = np.asarray(data)
        data = pd.DataFrame(matrix)

    melted = data.stack().reset_index(name='Value')

    x = data.columns.name
    y = data.index.name

    heatmap = alt.Chart(melted).mark_rect().encode(
        alt.X('{x}:O'.format(x=x), scale=alt.Scale(paddingInner=0)),
        alt.Y('{y}:O'.format(y=y), scale=alt.Scale(paddingInner=0)),
        color='Value:Q'
    )
    
    if not annot:
        return heatmap

    # Overlay text
    text = alt.Chart(melted).mark_text(baseline='middle').encode(
        x='{x}:O'.format(x=x),
        y='{y}:O'.format(y=y),
        text=alt.Text('Value', format=fmt),
        color=alt.condition(alt.expr.datum['Value'] > 70,
                            alt.value('black'),
                            alt.value('white'))
    )
    return heatmap + text 
Example #11
Source File: _core.py    From pdvega with MIT License 4 votes vote down vote up
def line(self, alpha=None, width=450, height=300, ax=None, **kwds):
        """Line plot for Series data

        >>> series.vgplot.line()  # doctest: +SKIP

        Parameters
        ----------
        alpha : float, optional
            transparency level, 0 <= alpha <= 1
        width : int, optional
            the width of the plot in pixels
        height : int, optional
            the height of the plot in pixels
        ax: altair.Chart, optional
            chart to be overlayed with this vis (convinience method for `chart1 + chart2`)

        Returns
        -------
        chart : altair.Chart
            The altair plot representation
        """
        df = self._data.reset_index()
        df.columns = map(str, df.columns)
        x, y = df.columns

        chart = self._plot(
            data=df,
            width=width,
            height=height,
            title=kwds.pop("title", ""),
            figsize=kwds.pop("figsize", None),
            dpi=kwds.pop("dpi", None),
        )

        chart = chart.mark_line().encode(x=_x(x, df), y=_y(y, df))

        if alpha is not None:
            assert 0 <= alpha <= 1
            chart = chart.encode(opacity=alt.value(alpha))

        if ax is not None:
            return ax + chart

        warn_if_keywords_unused("line", kwds)
        return chart 
Example #12
Source File: _core.py    From pdvega with MIT License 4 votes vote down vote up
def area(self, alpha=None, width=450, height=300, ax=None, **kwds):
        """Area plot for Series data

        >>> series.vgplot.area()  # doctest: +SKIP

        Parameters
        ----------
        alpha : float, optional
            transparency level, 0 <= alpha <= 1
        width : int, optional
            the width of the plot in pixels
        height : int, optional
            the height of the plot in pixels
        ax: altair.Chart, optional
            chart to be overlayed with this vis (convinience method for `chart1 + chart2`)

        Returns
        -------
        chart : alt.Chart
            altair chart representation
        """
        df = self._data.reset_index()
        df.columns = map(str, df.columns)
        x, y = df.columns

        chart = self._plot(
            data=df,
            width=width,
            height=height,
            title=kwds.pop("title", ""),
            figsize=kwds.pop("figsize", None),
            dpi=kwds.pop("dpi", None),
        ).mark_area().encode(
            x=_x(x, df), y=_y(y, df)
        )

        if alpha is not None:
            assert 0 <= alpha <= 1
            chart = chart.encode(opacity=alt.value(alpha))

        if ax is not None:
            return ax + chart

        warn_if_keywords_unused("area", kwds)
        return chart 
Example #13
Source File: _core.py    From pdvega with MIT License 4 votes vote down vote up
def bar(self, alpha=None, width=450, height=300, ax=None, **kwds):
        """Bar plot for Series data

        >>> series.vgplot.bar()  # doctest: +SKIP

        Parameters
        ----------
        alpha : float, optional
            transparency level, 0 <= alpha <= 1
        width : int, optional
            the width of the plot in pixels
        height : int, optional
            the height of the plot in pixels
        ax: altair.Chart, optional
            chart to be overlayed with this vis (convinience method for `chart1 + chart2`)

        Returns
        -------
        chart : alt.Chart
            altair chart representation
        """

        df = self._data.reset_index()
        df.columns = map(str, df.columns)
        x, y = df.columns

        chart = self._plot(
            data=df,
            width=width,
            height=height,
            title=kwds.pop("title", ""),
            figsize=kwds.pop("figsize", None),
            dpi=kwds.pop("dpi", None),
        ).mark_bar().encode(
            x=_x(x, df), y=_y(y, df)
        )

        if alpha is not None:
            assert 0 <= alpha <= 1
            chart = chart.encode(opacity=alt.value(alpha))

        if ax is not None:
            return ax + chart

        warn_if_keywords_unused("bar", kwds)
        return chart 
Example #14
Source File: _core.py    From pdvega with MIT License 4 votes vote down vote up
def scatter(
        self, x, y, c=None, s=None, alpha=None, width=450, height=300, ax=None, **kwds
    ):
        """Scatter plot for DataFrame data

        >>> dataframe.vgplot.scatter(x, y)  # doctest: +SKIP

        Parameters
        ----------
        x : string
            the column to use as the x-axis variable.
        y : string
            the column to use as the y-axis variable.
        c : string, optional
            the column to use to encode the color of the points
        s : string, optional
            the column to use to encode the size of the points
        alpha : float, optional
            transparency level, 0 <= alpha <= 1
        width : int, optional
            the width of the plot in pixels
        height : int, optional
            the height of the plot in pixels
        ax: altair.Chart, optional
            chart to be overlayed with this vis (convinience method for `chart1 + chart2`)

        Returns
        -------
        chart : alt.Chart
            altair chart representation
        """
        df = self._data

        chart = self._plot(
            width=width,
            height=height,
            title=kwds.pop("title", ""),
            figsize=kwds.pop("figsize", None),
            dpi=kwds.pop("dpi", None),
        ).mark_point().encode(
            x=_x(x, df, ordinal_threshold=0), y=_y(y, df, ordinal_threshold=0)
        )

        if alpha is not None:
            assert 0 <= alpha <= 1
            chart = chart.encode(opacity=alt.value(alpha))

        if c is not None:
            chart.encoding["color"] = {"field": c, "type": infer_vegalite_type(df[c])}

        if s is not None:
            chart.encoding["size"] = {"field": s, "type": infer_vegalite_type(df[s])}

        if ax is not None:
            return ax + chart

        warn_if_keywords_unused("scatter", kwds)
        return chart 
Example #15
Source File: core.py    From starborn with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def boxplot_vertical(x=None, y=None, hue=None, data=None, order=None):

    # orientation_mapper = {'v': {'x': 'x', 'y': 'y'},
    #                       'h': {'x': 'y', 'y': 'x'}}

    # Define aggregate fields
    lower_box = 'q1({value}):Q'.format(value=y)
    lower_whisker = 'min({value}):Q'.format(value=y)
    upper_box = 'q3({value}):Q'.format(value=y)
    upper_whisker = 'max({value}):Q'.format(value=y)
    
    kwargs = {'x': '{x}:O'.format(x=x)}

    if hue is not None:
        kwargs['color'] = '{hue}:N'.format(hue=hue)
        # Swap x for column
        column, kwargs['x'] = kwargs['x'], '{hue}:N'.format(hue=hue)

    base = alt.Chart().encode(
        **kwargs
    )

    # Compose each layer individually
    lower_whisker = base.mark_rule().encode(
        y=alt.Y(lower_whisker, axis=alt.Axis(title=y)),
        y2=lower_box,
    )
    
    middle_bar_kwargs = dict(
        y=lower_box,
        y2=upper_box,
    )
    if hue is None:
        middle_bar_kwargs['color'] = 'year:O'

    middle_bar = base.mark_bar(size=10.0).encode(**middle_bar_kwargs)

    upper_whisker = base.mark_rule().encode(
        y=upper_whisker,
        y2=upper_box,
    )
    
    middle_tick = base.mark_tick(
        color='white',
        size=10.0
    ).encode(
        y='median({value}):Q'.format(value=y),
    )
    
    chart = (lower_whisker + upper_whisker + middle_bar + middle_tick)

    if hue is None:
        chart.data = data
        return chart
    else:
        return chart.facet(column=column, data=data) 
Example #16
Source File: _misc.py    From altair_pandas with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def scatter_matrix(
    df,
    color: Union[str, None] = None,
    alpha: float = 1.0,
    tooltip: Union[List[str], tooltipList, None] = None,
    **kwargs
) -> alt.Chart:
    """ plots a scatter matrix

    At the moment does not support neither histogram nor kde;
    Uses f-f scatterplots instead. Interactive and with a cusotmizable
    tooltip

    Parameters
    ----------
    df : DataFame
        DataFame to be used for scatterplot. Only numeric columns will be included.
    color : string [optional]
        Can be a column name or specific color value (hex, webcolors).
    alpha : float
        Opacity of the markers, within [0,1]
    tooltip: list [optional]
        List of specific column names or alt.Tooltip objects. If none (default),
        will show all columns.
    """
    dfc = _preprocess_data(df)
    tooltip = _process_tooltip(tooltip) or dfc.columns.tolist()
    cols = dfc._get_numeric_data().columns.tolist()

    chart = (
        alt.Chart(dfc)
        .mark_circle()
        .encode(
            x=alt.X(alt.repeat("column"), type="quantitative"),
            y=alt.X(alt.repeat("row"), type="quantitative"),
            opacity=alt.value(alpha),
            tooltip=tooltip,
        )
        .properties(width=150, height=150)
    )

    if color:
        color = str(color)

        if color in dfc:
            color = alt.Color(color)
            if "colormap" in kwargs:
                color.scale = alt.Scale(scheme=kwargs.get("colormap"))
        else:
            color = alt.value(color)
        chart = chart.encode(color=color)

    return chart.repeat(row=cols, column=cols).interactive()