Python altair.Color() Examples

The following are 13 code examples of altair.Color(). 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: BubbleDiachronicVisualization.py    From scattertext with Apache License 2.0 8 votes vote down vote up
def visualize(display_df):
        viridis = ['#440154', '#472c7a', '#3b518b', '#2c718e', '#21908d', '#27ad81', '#5cc863', '#aadc32', '#fde725']
        import altair as alt
        color_scale = alt.Scale(
            domain=(display_df.dropna().trending.min(),
                    0,
                    display_df.dropna().trending.max()),
            range=[viridis[0], viridis[len(viridis) // 2], viridis[-1]]
        )

        return alt.Chart(display_df).mark_circle().encode(
            alt.X('variable'),
            alt.Y('term'),
            size='frequency',
            color=alt.Color('trending:Q', scale=color_scale),
        ) 
Example #2
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 #3
Source File: plot.py    From retentioneering-tools with Mozilla Public License 2.0 6 votes vote down vote up
def altair_cluster_tsne(data, clusters, target, plot_name=None, **kwargs):
    if hasattr(data.retention, '_tsne'):
        tsne = data.retention._tsne.copy()
    else:
        tsne = data.retention.learn_tsne(clusters, **kwargs)
    tsne['color'] = clusters
    tsne.columns = ['x', 'y', 'color']

    scatter = alt.Chart(tsne).mark_point().encode(
        x='x',
        y='y',
        color=alt.Color(
            'color',
            scale=alt.Scale(scheme='plasma')
        )
    ).properties(
        width=800,
        height=600
    )
    return scatter, plot_name, tsne, data.retention.retention_config 
Example #4
Source File: circle.py    From timesketch with Apache License 2.0 6 votes vote down vote up
def generate(self):
        """Generate the chart.

        Returns:
            Instance of altair.Chart
        """
        chart = self._get_chart_with_transform()
        self._add_url_href(self.encoding)

        if self.chart_title:
            chart = chart.mark_circle(filled=True, size=100).properties(
                title=self.chart_title)
        else:
            chart = chart.mark_circle(filled=True, size=100)
        field = self.encoding.get('y', {}).get('field', 'count')
        color = alt.Color(field=field, type='quantitative')
        chart.encoding = alt.FacetedEncoding.from_dict(self.encoding)
        chart.encoding.color = color
        return chart 
Example #5
Source File: explore.py    From gobbli with Apache License 2.0 5 votes vote down vote up
def st_heatmap(
    heatmap_df: pd.DataFrame, x_col_name: str, y_col_name: str, color_col_name: str
):
    heatmap = (
        alt.Chart(heatmap_df, height=700, width=700)
        .mark_rect()
        .encode(alt.X(x_col_name), alt.Y(y_col_name), alt.Color(color_col_name))
    )
    st.altair_chart(heatmap) 
Example #6
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 #7
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 #8
Source File: core.py    From starborn with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def jointplot(x, y, data, kind='scatter', hue=None, xlim=None, ylim=None):
    if xlim is None:
        xlim = get_limit_tuple(data[x])
    if ylim is None:
        ylim = get_limit_tuple(data[y])
    xscale = alt.Scale(domain=xlim)
    yscale = alt.Scale(domain=ylim)
 
    points = scatterplot(x, y, data, hue=hue, xlim=xlim, ylim=ylim)

    area_args = {'opacity': .3, 'interpolate': 'step'}

    blank_axis = alt.Axis(title='')

    top_hist = alt.Chart(data).mark_area(**area_args).encode(
        alt.X('{x}:Q'.format(x=x),
              # when using bins, the axis scale is set through
              # the bin extent, so we do not specify the scale here
              # (which would be ignored anyway)
              bin=alt.Bin(maxbins=20, extent=xscale.domain),
              stack=None,
              axis=blank_axis,
             ),
        alt.Y('count()', stack=None, axis=blank_axis),
        alt.Color('{hue}:N'.format(hue=hue)),
    ).properties(height=60)

    right_hist = alt.Chart(data).mark_area(**area_args).encode(
        alt.Y('{y}:Q'.format(y=y),
              bin=alt.Bin(maxbins=20, extent=yscale.domain),
              stack=None,
              axis=blank_axis,
             ),
        alt.X('count()', stack=None, axis=blank_axis),
        alt.Color('{hue}:N'.format(hue=hue)),
    ).properties(width=60)

    return top_hist & (points | right_hist) 
Example #9
Source File: _core.py    From altair_pandas with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _xy(self, mark, x=None, y=None, stacked=False, subplots=False, **kwargs):
        data = self._preprocess_data(with_index=True)

        if x is None:
            x = data.columns[0]
        else:
            x = _valid_column(x)
            assert x in data.columns

        if y is None:
            y_values = list(data.columns[1:])
        else:
            y = _valid_column(y)
            assert y in data.columns
            y_values = [y]

        chart = (
            alt.Chart(data, mark=self._get_mark_def(mark, kwargs))
            .transform_fold(y_values, as_=["column", "value"])
            .encode(
                x=x,
                y=alt.Y("value:Q", title=None, stack=stacked),
                color=alt.Color("column:N", title=None),
                tooltip=[x] + y_values,
            )
            .interactive()
        )

        if subplots:
            nrows, ncols = _get_layout(len(y_values), kwargs.get("layout", (-1, 1)))
            chart = chart.encode(facet=alt.Facet("column:N", title=None)).properties(
                columns=ncols
            )

        return chart 
Example #10
Source File: explore.py    From gobbli with Apache License 2.0 4 votes vote down vote up
def show_label_distribution(
    sample_labels: Union[List[str], List[List[str]]],
    all_labels: Optional[Union[List[str], List[List[str]]]] = None,
):
    if sample_labels is not None:
        st.header("Label Distribution")
        label_counts = _collect_label_counts(sample_labels)

        if all_labels is None:
            label_chart = (
                alt.Chart(label_counts, height=500, width=700)
                .mark_bar()
                .encode(
                    alt.X("Label", type="nominal"),
                    alt.Y("Proportion", type="quantitative"),
                )
            )
        else:
            label_counts["Label Set"] = "Sample"
            all_label_counts = _collect_label_counts(all_labels)
            all_label_counts["Label Set"] = "All Documents"
            label_counts = pd.concat([label_counts, all_label_counts])

            label_chart = (
                alt.Chart(label_counts, width=100)
                .mark_bar()
                .encode(
                    alt.X(
                        "Label Set",
                        type="nominal",
                        title=None,
                        sort=["Sample", "All Documents"],
                    ),
                    alt.Y("Proportion", type="quantitative"),
                    alt.Column(
                        "Label", type="nominal", header=alt.Header(labelAngle=0)
                    ),
                    alt.Color("Label Set", type="nominal", legend=None),
                )
            )

        st.altair_chart(label_chart) 
Example #11
Source File: group.py    From errudite with GNU General Public License v2.0 4 votes vote down vote up
def visualize_models(self, 
        instance_hash: Dict[InstanceKey, Instance]={},
        instance_hash_rewritten: Dict[InstanceKey, Instance]={},
        filtered_instances: List[InstanceKey]=None,
        models: List[str]=[]):
        """
        Visualize the group distribution. 
        It's a one-bar histogram that displays the count of instances in the group, and
        the proportion of incorrect predictions.
        Because of the incorrect prediction proportion, this historgram is different
        for each different model. 
        
        Parameters
        ----------
        instance_hash : Dict[InstanceKey, Instance]
            A dict that saves all the *original* instances, by default {}. 
            It denotes by the corresponding instance keys.
            If ``{}``, resolve to ``Instance.instance_hash``.
        instance_hash_rewritten : Dict[InstanceKey, Instance]
            A dict that saves all the *rewritten* instances, by default {}. 
            It denotes by the corresponding instance keys.
            If ``{}``, resolve to ``Instance.instance_hash_rewritten``.
        filtered_instances : List[InstanceKey], optional
            A selected list of instances. If given, only display the distribution
            of the selected instances, by default None
        models : List[str], optional
            A list of instances, with the bars for each group concated vertically.
            By default []. If [], resolve to ``[ Instance.model ]``.
        
        Returns
        -------
        alt.Chart
            An altair chart object. 
        """
        instance_hash = instance_hash or Instance.instance_hash
        instance_hash_rewritten = instance_hash_rewritten or Instance.instance_hash_rewritten
        models = models or [ Instance.resolve_default_model(None) ]
        output = []
        for model in models:
            #Instance.set_default_model(model=model)
            data = self.serialize(instance_hash, instance_hash_rewritten, filtered_instances, model)
            for correctness, count in data["counts"].items():
                output.append({
                    "correctness": correctness,
                    "count": count,
                    "model": model
                })
        
        df = pd.DataFrame(output)
        chart = alt.Chart(df).mark_bar().encode(
            y=alt.Y('model:N'),
            x=alt.X('count:Q', stack="zero"),
            color=alt.Color('correctness:N', scale=alt.Scale(domain=["correct", "incorrect"])),
            tooltip=['model:N', 'count:Q', 'correctness:N']
        ).properties(width=100)#.configure_facet(spacing=5)#
        return chart 
Example #12
Source File: rewrite.py    From errudite with GNU General Public License v2.0 4 votes vote down vote up
def visualize_models(self, 
        instance_hash: Dict[InstanceKey, Instance]={},
        instance_hash_rewritten: Dict[InstanceKey, Instance]={},
        filtered_instances: List[InstanceKey]=None,
        models: str=[]):
        """
        Visualize the rewrite distribution. 
        It's a one-bar histogram that displays the count of instances rewritten, and
        the proportion of "flip_to_correct", "flip_to_incorrect", "unflip"
        Because of the flipping proportion, this historgram is different
        for each different model. 
        
        Parameters
        ----------
        instance_hash : Dict[InstanceKey, Instance]
            A dict that saves all the *original* instances, by default {}. 
            It denotes by the corresponding instance keys.
            If ``{}``, resolve to ``Instance.instance_hash``.
        instance_hash_rewritten : Dict[InstanceKey, Instance]
            A dict that saves all the *rewritten* instances, by default {}. 
            It denotes by the corresponding instance keys.
            If ``{}``, resolve to ``Instance.instance_hash_rewritten``.
        filtered_instances : List[InstanceKey], optional
            A selected list of instances. If given, only display the distribution
            of the selected instances, by default None
        models : List[str], optional
            A list of instances, with the bars for each group concated vertically.
            By default []. If [], resolve to ``[ Instance.model ]``.
        
        Returns
        -------
        alt.Chart
            An altair chart object. 
        """
        model = models or [ Instance.model ]
        instance_hash = instance_hash or Instance.instance_hash
        instance_hash_rewritten = instance_hash_rewritten or Instance.instance_hash_rewritten
        if not models:
            models = [ Instance.resolve_default_model(None) ]
        output = []
        for model in models:
            #Instance.set_default_model(model=model)
            data = self.serialize(instance_hash, instance_hash_rewritten, filtered_instances, model)
            for flip, count in data["counts"].items():
                output.append({
                    "flip": flip,
                    "count": count,
                    "model": model
                })
        df = pd.DataFrame(output)
        chart = alt.Chart(df).mark_bar().encode(
            y=alt.Y('model:N'),
            x=alt.X('count:Q', stack="zero"),
            color=alt.Color('flip:N', scale=alt.Scale(
                range=["#1f77b4", "#ff7f0e", "#c7c7c7"],
                domain=["flip_to_correct", "flip_to_incorrect", "unflip"])),
            tooltip=['model:N', 'count:Q', 'correctness:N']
        ).properties(width=100)#.configure_facet(spacing=5)#
        return chart 
Example #13
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()