Python altair.Bin() Examples

The following are 7 code examples of altair.Bin(). 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: core.py    From starborn with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def violinplot(x=None, y=None, data=None, orient=None):
    # TODO: automatically infer orientation

    if orient is None or orient == 'v':
        kwargs = dict(
                    x=alt.X('count(*):Q',
                            axis=alt.Axis(grid=False, labels=False),
                            stack='center',
                            title=''),
                    y=alt.Y('{y}:Q'.format(y=y), bin=alt.Bin(maxbins=100)),
                    column='{x}:N'.format(x=x),
                    color='{x}:N'.format(x=x)
        )
    else:
        kwargs = dict(
                    y=alt.Y('count(*):Q',
                            axis=alt.Axis(grid=False, labels=False),
                            stack='center',
                            title=''),
                    x=alt.X('{x}:Q'.format(x=x), bin=alt.Bin(maxbins=100)),
                    row='{y}:N'.format(y=y),
                    color='{y}:N'.format(y=y)
        )
    chart = alt.Chart(data).mark_area().encode(**kwargs)
    return chart 
Example #2
Source File: _core.py    From altair_pandas with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def hist(self, bins=None, orientation="vertical", **kwargs):
        data = self._preprocess_data(with_index=False)
        column = data.columns[0]
        if isinstance(bins, int):
            bins = alt.Bin(maxbins=bins)
        elif bins is None:
            bins = True
        if orientation == "vertical":
            Indep, Dep = alt.X, alt.Y
        elif orientation == "horizontal":
            Indep, Dep = alt.Y, alt.X
        else:
            raise ValueError("orientation must be 'horizontal' or 'vertical'.")

        mark = self._get_mark_def({"type": "bar", "orient": orientation}, kwargs)
        return alt.Chart(data, mark=mark).encode(
            Indep(column, title=None, bin=bins), Dep("count()", title="Frequency")
        ) 
Example #3
Source File: test_core.py    From pdvega with MIT License 5 votes vote down vote up
def test_df_hexbin():
    df = pd.DataFrame({"x": range(10), "y": range(10), "C": range(10)})
    gridsize = 10
    plot = df.vgplot.hexbin(x="x", y="y", gridsize=gridsize)
    assert plot.mark == "rect"
    utils.check_encodings(plot, x="x", y="y", color=utils.IGNORE)
    assert plot["encoding"]["x"]["bin"] == alt.Bin(maxbins=gridsize)
    assert plot["encoding"]["y"]["bin"] == alt.Bin(maxbins=gridsize)
    assert plot["encoding"]["color"]["aggregate"] == "count" 
Example #4
Source File: test_core.py    From pdvega with MIT License 5 votes vote down vote up
def test_df_hexbin_C():
    df = pd.DataFrame({"x": range(10), "y": range(10), "C": range(10)})
    gridsize = 10
    plot = df.vgplot.hexbin(x="x", y="y", C="C", gridsize=gridsize)
    assert plot.mark == "rect"
    utils.check_encodings(plot, x="x", y="y", color="C")
    assert plot["encoding"]["x"]["bin"] == alt.Bin(maxbins=gridsize)
    assert plot["encoding"]["y"]["bin"] == alt.Bin(maxbins=gridsize)
    assert plot["encoding"]["color"]["aggregate"] == "mean" 
Example #5
Source File: explore.py    From gobbli with Apache License 2.0 5 votes vote down vote up
def show_document_length_distribution(tokens: List[List[str]]):
    st.header("Document Length Distribution")
    document_lengths = get_document_lengths(tokens)
    doc_lengths = pd.DataFrame({"Token Count": document_lengths})
    doc_length_chart = (
        alt.Chart(doc_lengths, height=500, width=700)
        .mark_bar()
        .encode(
            alt.X("Token Count", bin=alt.Bin(maxbins=30)),
            alt.Y("count()", type="quantitative"),
        )
    )

    st.altair_chart(doc_length_chart) 
Example #6
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 #7
Source File: _core.py    From altair_pandas with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def hist(self, bins=None, stacked=None, orientation="vertical", **kwargs):
        data = self._preprocess_data(with_index=False)
        if isinstance(bins, int):
            bins = alt.Bin(maxbins=bins)
        elif bins is None:
            bins = True
        if orientation == "vertical":
            Indep, Dep = alt.X, alt.Y
        elif orientation == "horizontal":
            Indep, Dep = alt.Y, alt.X
        else:
            raise ValueError("orientation must be 'horizontal' or 'vertical'.")

        mark = self._get_mark_def({"type": "bar", "orient": orientation}, kwargs)
        chart = (
            alt.Chart(data, mark=mark)
            .transform_fold(list(data.columns), as_=["column", "value"])
            .encode(
                Indep("value:Q", title=None, bin=bins),
                Dep("count()", title="Frequency", stack=stacked),
                color="column:N",
            )
        )

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

        return chart