Example #1
0
def test_repeat():
    # wrapped repeat
    chart1 = (alt.Chart("data.csv").mark_point().encode(
        x=alt.X(alt.repeat(), type="quantitative"),
        y="y:Q",
    ).repeat(["A", "B", "C", "D"], columns=2))

    dct1 = chart1.to_dict()

    assert dct1["repeat"] == ["A", "B", "C", "D"]
    assert dct1["columns"] == 2
    assert dct1["spec"]["encoding"]["x"]["field"] == {"repeat": "repeat"}

    # explicit row/col repeat
    chart2 = (alt.Chart("data.csv").mark_point().encode(
        x=alt.X(alt.repeat("row"), type="quantitative"),
        y=alt.Y(alt.repeat("column"), type="quantitative"),
    ).repeat(row=["A", "B", "C"], column=["C", "B", "A"]))

    dct2 = chart2.to_dict()

    assert dct2["repeat"] == {
        "row": ["A", "B", "C"],
        "column": ["C", "B", "A"]
    }
    assert "columns" not in dct2
    assert dct2["spec"]["encoding"]["x"]["field"] == {"repeat": "row"}
    assert dct2["spec"]["encoding"]["y"]["field"] == {"repeat": "column"}
Example #2
0
def test_repeat():
    # wrapped repeat
    chart1 = alt.Chart('data.csv').mark_point().encode(
        x=alt.X(alt.repeat(), type='quantitative'),
        y='y:Q',
    ).repeat(['A', 'B', 'C', 'D'], columns=2)

    dct1 = chart1.to_dict()

    assert dct1['repeat'] == ['A', 'B', 'C', 'D']
    assert dct1['columns'] == 2
    assert dct1['spec']['encoding']['x']['field'] == {'repeat': 'repeat'}

    # explicit row/col repeat
    chart2 = alt.Chart('data.csv').mark_point().encode(
        x=alt.X(alt.repeat('row'), type='quantitative'),
        y=alt.Y(alt.repeat('column'),
                type='quantitative')).repeat(row=['A', 'B', 'C'],
                                             column=['C', 'B', 'A'])

    dct2 = chart2.to_dict()

    assert dct2['repeat'] == {
        'row': ['A', 'B', 'C'],
        'column': ['C', 'B', 'A']
    }
    assert 'columns' not in dct2
    assert dct2['spec']['encoding']['x']['field'] == {'repeat': 'row'}
    assert dct2['spec']['encoding']['y']['field'] == {'repeat': 'column'}
Example #3
0
def test_chart_infer_types():
    data = pd.DataFrame({'x': pd.date_range('2012', periods=10, freq='Y'),
                         'y': range(10),
                         'c': list('abcabcabca')})

    def _check_encodings(chart):
        dct = chart.to_dict()
        assert dct['encoding']['x']['type'] == 'temporal'
        assert dct['encoding']['x']['field'] == 'x'
        assert dct['encoding']['y']['type'] == 'quantitative'
        assert dct['encoding']['y']['field'] == 'y'
        assert dct['encoding']['color']['type'] == 'nominal'
        assert dct['encoding']['color']['field'] == 'c'

    # Pass field names by keyword
    chart = alt.Chart(data).mark_point().encode(x='x', y='y', color='c')
    _check_encodings(chart)

    # pass Channel objects by keyword
    chart = alt.Chart(data).mark_point().encode(x=alt.X('x'), y=alt.Y('y'),
                                                color=alt.Color('c'))
    _check_encodings(chart)

    # pass Channel objects by value
    chart = alt.Chart(data).mark_point().encode(alt.X('x'), alt.Y('y'),
                                                alt.Color('c'))
    _check_encodings(chart)

    # override default types
    chart = alt.Chart(data).mark_point().encode(alt.X('x', type='nominal'),
                                                alt.Y('y', type='ordinal'))
    dct = chart.to_dict()
    assert dct['encoding']['x']['type'] == 'nominal'
    assert dct['encoding']['y']['type'] == 'ordinal'
Example #4
0
def _make_chart_type(chart_type):
    data = pd.DataFrame({
        "x": [28, 55, 43, 91, 81, 53, 19, 87],
        "y": [43, 91, 81, 53, 19, 87, 52, 28],
        "color": list("AAAABBBB"),
    })
    base = alt.Chart(data).mark_point().encode(
        x="x",
        y="y",
        color="color",
    )

    if chart_type in ["layer", "hconcat", "vconcat", "concat"]:
        func = getattr(alt, chart_type)
        return func(base.mark_square(), base.mark_circle())
    elif chart_type == "facet":
        return base.facet("color")
    elif chart_type == "facet_encoding":
        return base.encode(facet="color")
    elif chart_type == "repeat":
        return base.encode(alt.X(alt.repeat(),
                                 type="quantitative")).repeat(["x", "y"])
    elif chart_type == "chart":
        return base
    else:
        raise ValueError(
            "chart_type='{}' is not recognized".format(chart_type))
Example #5
0
def _make_chart_type(chart_type):
    data = pd.DataFrame({
        'x': [28, 55, 43, 91, 81, 53, 19, 87],
        'y': [43, 91, 81, 53, 19, 87, 52, 28],
        'color': list('AAAABBBB'),
    })
    base = alt.Chart(data).mark_point().encode(
        x='x',
        y='y',
        color='color',
    )

    if chart_type in ['layer', 'hconcat', 'vconcat', 'concat']:
        func = getattr(alt, chart_type)
        return func(base.mark_square(), base.mark_circle())
    elif chart_type == 'facet':
        return base.facet('color')
    elif chart_type == 'facet_encoding':
        return base.encode(facet='color')
    elif chart_type == 'repeat':
        return base.encode(alt.X(alt.repeat(),
                                 type='quantitative')).repeat(['x', 'y'])
    elif chart_type == 'chart':
        return base
    else:
        raise ValueError(
            "chart_type='{}' is not recognized".format(chart_type))
Example #6
0
 def deco(ch):
     h = ch.mark_line().encode(
         x=A.X(x, title=x),
         y=A.Y(y, title=y, **yargs),
         color=color,
         tooltip=[color, x, y],
     )
     return h
    def make_ridge_chart(self):
        self.plot_df['year'] = pd.to_datetime(
            self.plot_df['year'].astype(str) + '-01-01')
        brush = alt.selection_interval(encodings=['x'])
        step = 18
        overlap = 7
        # Topic selection
        selection = alt.selection_multi(fields=['Topic'])

        # смена цвета на выборе темы -- всё что не выделили делается серым
        color = alt.condition(
            selection,
            alt.Color('Topic:N',
                      legend=None,
                      scale=alt.Scale(scheme="rainbow")),
            alt.value('lightgray'))

        a = alt.hconcat(
            alt.Chart(self.plot_df).mark_area(
                fillOpacity=0.6, interpolate='monotone').encode(
                    x=alt.X('year:T'),
                    y=alt.Y('rate:Q',
                            scale=alt.Scale(range=[0, -overlap * (step + 1)]),
                            axis=None),
                    row=alt.Row('Topic:N',
                                header=alt.Header(title=None,
                                                  labelPadding=0,
                                                  labelFontSize=0)),
                    color=color).add_selection(selection).properties(
                        width=800,
                        height=step,
                        bounds='flush',
                    ).transform_filter(brush),
            alt.Chart(self.plot_df,
                      height=500).mark_point().encode(
                          y=alt.Y('Topic:N', axis=alt.Axis(orient='right')),
                          color=color).add_selection(selection))

        b = alt.Chart(self.plot_df).mark_area(interpolate='monotone').encode(
            y='sum(rate):Q',
            x='year:T',
        ).properties(width=800, height=100).add_selection(brush)

        if self.add_data_names != ['All']:
            add_charts = [
                self.make_add_data_chart(i, brush) for i in self.add_data_names
            ]
            chart = alt.vconcat(a, *add_charts, b, padding=0,
                                spacing=0).configure_view(
                                    stroke=None).configure_axis(grid=False)
            return chart
        else:
            chart = alt.vconcat(a, b, padding=0, spacing=0).configure_view(
                stroke=None).configure_axis(grid=False)
            return chart
Example #8
0
def test_chart_infer_types():
    data = pd.DataFrame({
        "x": pd.date_range("2012", periods=10, freq="Y"),
        "y": range(10),
        "c": list("abcabcabca"),
    })

    def _check_encodings(chart):
        dct = chart.to_dict()
        assert dct["encoding"]["x"]["type"] == "temporal"
        assert dct["encoding"]["x"]["field"] == "x"
        assert dct["encoding"]["y"]["type"] == "quantitative"
        assert dct["encoding"]["y"]["field"] == "y"
        assert dct["encoding"]["color"]["type"] == "nominal"
        assert dct["encoding"]["color"]["field"] == "c"

    # Pass field names by keyword
    chart = alt.Chart(data).mark_point().encode(x="x", y="y", color="c")
    _check_encodings(chart)

    # pass Channel objects by keyword
    chart = (alt.Chart(data).mark_point().encode(x=alt.X("x"),
                                                 y=alt.Y("y"),
                                                 color=alt.Color("c")))
    _check_encodings(chart)

    # pass Channel objects by value
    chart = alt.Chart(data).mark_point().encode(alt.X("x"), alt.Y("y"),
                                                alt.Color("c"))
    _check_encodings(chart)

    # override default types
    chart = (alt.Chart(data).mark_point().encode(alt.X("x", type="nominal"),
                                                 alt.Y("y", type="ordinal")))
    dct = chart.to_dict()
    assert dct["encoding"]["x"]["type"] == "nominal"
    assert dct["encoding"]["y"]["type"] == "ordinal"
Example #9
0
    def make_ridge_chart(self):
        self.plot_df['year'] = pd.to_datetime(self.plot_df['year'].astype(str) + '-01-01')
        brush = alt.selection(type='interval', encodings=['x'])
        step = 18
        overlap = 4
        a = alt.Chart(self.plot_df).mark_area(stroke='black', strokeWidth=0, fillOpacity=0.6).encode(
            x=alt.X('year:T'),
            y=alt.Y('rate:Q', scale=alt.Scale(range=[0, -overlap * (step + 1)]), axis=None),
            row=alt.Row('Topic:N', header=alt.Header(title=None, labelPadding=0, labelFontSize=0)),
            color='Topic:N'
        ).properties(
            width=800,
            height=step,
            bounds='flush',
        ).transform_filter(
            brush
        )
        b = alt.Chart(self.plot_df).mark_area().encode(
            y='sum(rate):Q',
            x='year:T',
        ).properties(
            width=800,
            height=100
        ).add_selection(
            brush
        )

        if self.add_data_names != ['All']:
            add_charts = [self.make_add_data_chart(i, brush) for i in self.add_data_names]
            chart = alt.vconcat(
                a, *add_charts, b, padding=0, spacing=0
            ).configure_view(
                stroke=None
            ).configure_axis(
                grid=False
            )
            return chart
        else:
            chart = alt.vconcat(
                a, b, padding=0, spacing=0
            ).configure_view(
                stroke=None
            ).configure_axis(
                grid=False
            )
            return chart
Example #10
0
def pl(
    pdf,
    color="state",
    x="date",
    y="positive",
    ii=True,
    logy=True,
    logx=False,
    tt=[],
):
    tt = list(tt)
    ykw = dict(scale=lgs) if logy else {}
    xkw = dict(scale=lgs) if logx else {}
    h = (A.Chart(pdf).mark_line().encode(
        x=A.X(x, title=x, **xkw),
        y=A.Y(y, title=y, **ykw),
        color=color,
        tooltip=[color, x, y] + tt,
    ))
    hh = h + h.mark_point()
    if ii:
        return hh.interactive()
    return hh
Example #11
0
def test_layer_encodings():
    chart = alt.LayerChart().encode(x="column:Q")
    assert chart.encoding.x == alt.X(shorthand="column:Q")
Example #12
0
    .rename(columns=lambda x: "p{:02}".format(int(x * 100)))
    .reset_index(drop=0)
    .sort_values("p05", ascending=True)
    .reset_index(drop=1)
)

# %% [markdown]
# Doubling rate: if the value is around 2, then expect the number of deaths to double every 2 days.

# %%
color = 'dvers'
x = 'state'
y = 'p50'

h = Chart(growth_dbl).mark_point().encode(
    x=A.X(x, title=x, sort=None),
    y=A.Y(y, title='Exponent'),
    tooltip=[x, y]
)

herr = h.mark_errorbar().encode(y=A.Y('p05', title='Exponent'), y2='p95')
# (h + h.mark_point()).interactive()
(herr + h).properties(title='Doubling rates')


# %%
# xs = np.arange(100)
# yx = np.exp(xs * .1)

# expdf = DataFrame(dict(x=xs, y=yx))
# ixs = np.searchsorted(expdf.y, [1, 2, 4, 8, 16])