def test_selection_to_dict(): brush = alt.selection(type='interval') # test some value selections # Note: X and Y cannot have conditions alt.Chart('path/to/data.json').mark_point().encode( color=alt.condition(brush, alt.ColorValue('red'), alt.ColorValue('blue')), opacity=alt.condition(brush, alt.value(0.5), alt.value(1.0)), text=alt.condition(brush, alt.TextValue('foo'), alt.value('bar'))).to_dict() # test some field selections # Note: X and Y cannot have conditions # Conditions cannot both be fields alt.Chart('path/to/data.json').mark_point().encode( color=alt.condition(brush, alt.Color('col1:N'), alt.value('blue')), opacity=alt.condition(brush, 'col1:N', alt.value(0.5)), text=alt.condition(brush, alt.value('abc'), alt.Text('col2:N')), size=alt.condition(brush, alt.value(20), 'col2:N')).to_dict()
def test_add_selection(): selections = [alt.selection_interval(), alt.selection_single(), alt.selection_multi()] chart = alt.Chart().mark_point().add_selection( selections[0] ).add_selection( selections[1], selections[2] ) expected = {s.name: s.selection for s in selections} assert chart.selection == expected
def test_selection_to_dict(): brush = alt.selection(type="interval") # test some value selections # Note: X and Y cannot have conditions alt.Chart("path/to/data.json").mark_point().encode( color=alt.condition(brush, alt.ColorValue("red"), alt.ColorValue("blue")), opacity=alt.condition(brush, alt.value(0.5), alt.value(1.0)), text=alt.condition(brush, alt.TextValue("foo"), alt.value("bar")), ).to_dict() # test some field selections # Note: X and Y cannot have conditions # Conditions cannot both be fields alt.Chart("path/to/data.json").mark_point().encode( color=alt.condition(brush, alt.Color("col1:N"), alt.value("blue")), opacity=alt.condition(brush, "col1:N", alt.value(0.5)), text=alt.condition(brush, alt.value("abc"), alt.Text("col2:N")), size=alt.condition(brush, alt.value(20), "col2:N"), ).to_dict()
def make_add_data_chart(self, data_name, brush): data = pd.read_csv(f'src/add_data_cleaned/{data_name}.csv', encoding='utf-8') col_name = data.columns[-1] chart = alt.Chart(data).mark_line().encode( y=f'{col_name}:Q', x='year:T', ).properties(width=800, height=100, title=f'График {col_name}').transform_filter(brush) return chart
def test_facet_parse(): chart = alt.Chart('data.csv').mark_point().encode( x='x:Q', y='y:Q' ).facet( row='row:N', column='column:O' ) dct = chart.to_dict() assert dct['data'] == {'url': 'data.csv'} assert 'data' not in dct['spec'] assert dct['facet'] == {'column': {'field': 'column', 'type': 'ordinal'}, 'row': {'field': 'row', 'type': 'nominal'}}
def test_multiple_encodings(): encoding_dct = [{ 'field': 'value', 'type': 'quantitative' }, { 'field': 'name', 'type': 'nominal' }] chart1 = alt.Chart('data.csv').mark_point().encode( detail=['value:Q', 'name:N'], tooltip=['value:Q', 'name:N']) chart2 = alt.Chart('data.csv').mark_point().encode( alt.Detail(['value:Q', 'name:N']), alt.Tooltip(['value:Q', 'name:N'])) chart3 = alt.Chart('data.csv').mark_point().encode( [alt.Detail('value:Q'), alt.Detail('name:N')], [alt.Tooltip('value:Q'), alt.Tooltip('name:N')]) for chart in [chart1, chart2, chart3]: dct = chart.to_dict() assert dct['encoding']['detail'] == encoding_dct assert dct['encoding']['tooltip'] == encoding_dct
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
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'
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"
def test_multiple_encodings(args, kwargs): df = pd.DataFrame({ 'value': [1, 2, 3], 'name': ['A', 'B', 'C'], }) encoding_dct = [{ 'field': 'value', 'type': 'quantitative' }, { 'field': 'name', 'type': 'nominal' }] chart = alt.Chart(df).mark_point().encode(*args, **kwargs) dct = chart.to_dict() assert dct['encoding']['detail'] == encoding_dct assert dct['encoding']['tooltip'] == encoding_dct
def test_chart_from_dict(): base = alt.Chart('data.csv').mark_point().encode(x='x:Q', y='y:Q') charts = [ base, base + base, base | base, base & base, base.facet(row='c:N'), (base + base).facet(row='c:N', data='data.csv'), base.repeat(row=['c:N', 'd:N']) ] for chart in charts: chart_out = alt.Chart.from_dict(chart.to_dict()) assert type(chart_out) is type(chart) # test that an invalid spec leads to a schema validation error with pytest.raises(jsonschema.ValidationError): alt.Chart.from_dict({'invalid': 'spec'})
def test_filter_transform_selection_predicates(): selector1 = alt.selection_interval(name='s1') selector2 = alt.selection_interval(name='s2') base = alt.Chart('data.txt').mark_point() chart = base.transform_filter(selector1) assert chart.to_dict()['transform'] == [{'filter': {'selection': 's1'}}] chart = base.transform_filter(~selector1) assert chart.to_dict()['transform'] == [{'filter': {'selection': {'not': 's1'}}}] chart = base.transform_filter(selector1 & selector2) assert chart.to_dict()['transform'] == [{'filter': {'selection': {'and': ['s1', 's2']}}}] chart = base.transform_filter(selector1 | selector2) assert chart.to_dict()['transform'] == [{'filter': {'selection': {'or': ['s1', 's2']}}}]
def test_multiple_encodings(args, kwargs): df = pd.DataFrame({"value": [1, 2, 3], "name": ["A", "B", "C"]}) encoding_dct = [ { "field": "value", "type": "quantitative" }, { "field": "name", "type": "nominal" }, ] chart = alt.Chart(df).mark_point().encode(*args, **kwargs) dct = chart.to_dict() assert dct["encoding"]["detail"] == encoding_dct assert dct["encoding"]["tooltip"] == encoding_dct
def test_facet_parse(): chart = (alt.Chart("data.csv").mark_point().encode(x="x:Q", y="y:Q").facet( row="row:N", column="column:O")) dct = chart.to_dict() assert dct["data"] == {"url": "data.csv"} assert "data" not in dct["spec"] assert dct["facet"] == { "column": { "field": "column", "type": "ordinal" }, "row": { "field": "row", "type": "nominal" }, }
def test_subcharts_with_same_data(method, data): func = getattr(alt, method) point = alt.Chart(data).mark_point().encode(x="x:Q", y="y:Q") line = point.mark_line() text = point.mark_text() chart1 = func(point, line, text) assert chart1.data is not alt.Undefined assert all(c.data is alt.Undefined for c in getattr(chart1, method)) if method != "concat": op = OP_DICT[method] chart2 = op(op(point, line), text) assert chart2.data is not alt.Undefined assert all(c.data is alt.Undefined for c in getattr(chart2, method))
def test_geo_interface_feature_collection(): geom = { "type": "FeatureCollection", "features": [ { "geometry": { "coordinates": [[[6.90, 53.48], [5.98, 51.85], [6.07, 53.51], [6.90, 53.48]]], "type": "Polygon" }, "id": 27, "properties": { "type": "foo", "id": 1, "geometry": 1 }, "type": "Feature" }, { "geometry": { "coordinates": [[[8.90, 53.48], [7.98, 51.85], [8.07, 53.51], [8.90, 53.48]]], "type": "Polygon" }, "id": 28, "properties": { "type": "foo", "id": 2, "geometry": 1 }, "type": "Feature" }, ] } feat = geom_obj(geom) with alt.data_transformers.enable(consolidate_datasets=False): spec = alt.Chart(feat).mark_geoshape().to_dict() assert spec['data']['values'][0]['id'] == 1 assert spec['data']['values'][1]['id'] == 2 assert 'coordinates' in spec['data']['values'][0]['geometry'] assert 'coordinates' in spec['data']['values'][1]['geometry'] assert spec['data']['values'][0]['type'] == 'Feature' assert spec['data']['values'][1]['type'] == 'Feature'
def test_geo_interface_removal_empty_properties(): geom = { "geometry": { "coordinates": [[[6.90, 53.48], [5.98, 51.85], [6.07, 53.51], [6.90, 53.48]]], "type": "Polygon" }, "id": None, "properties": {}, "type": "Feature" } feat = geom_obj(geom) with alt.data_transformers.enable(consolidate_datasets=False): spec = alt.Chart(feat).mark_geoshape().to_dict() assert spec['data']['values']['type'] == 'Feature'
def test_geo_interface_reserved_members(): geom = { "geometry": { "coordinates": [ [[6.90, 53.48], [5.98, 51.85], [6.07, 53.51], [6.90, 53.48]] ], "type": "Polygon", }, "id": 27, "properties": {"type": "foo"}, "type": "Feature", } feat = geom_obj(geom) with alt.data_transformers.enable(consolidate_datasets=False): spec = alt.Chart(feat).mark_geoshape().to_dict() assert spec["data"]["values"]["type"] == "Feature"
def test_geo_interface_register_foreign_member(): geom = { "geometry": { "coordinates": [ [[6.90, 53.48], [5.98, 51.85], [6.07, 53.51], [6.90, 53.48]] ], "type": "Polygon", }, "id": 2, "properties": {"foo": "bah"}, "type": "Feature", } feat = geom_obj(geom) with alt.data_transformers.enable(consolidate_datasets=False): spec = alt.Chart(feat).mark_geoshape().to_dict() with pytest.raises(KeyError): spec["data"]["values"]["id"] assert spec["data"]["values"]["foo"] == "bah"
def test_themes(): chart = alt.Chart('foo.txt').mark_point() active = alt.themes.active try: alt.themes.enable('default') assert chart.to_dict()['config'] == {"mark": {"tooltip": None}, "view": {"width": 400, "height": 300}} alt.themes.enable('opaque') assert chart.to_dict()['config'] == {"background": "white", "mark": {"tooltip": None}, "view": {"width": 400, "height": 300}} alt.themes.enable('none') assert 'config' not in chart.to_dict() finally: # re-enable the original active theme alt.themes.enable(active)
def test_chart_from_dict(): base = alt.Chart("data.csv").mark_point().encode(x="x:Q", y="y:Q") charts = [ base, base + base, base | base, base & base, base.facet("c:N"), (base + base).facet(row="c:N", data="data.csv"), base.repeat(["c", "d"]), (base + base).repeat(row=["c", "d"]), ] for chart in charts: print(chart) chart_out = alt.Chart.from_dict(chart.to_dict()) assert type(chart_out) is type(chart) # test that an invalid spec leads to a schema validation error with pytest.raises(jsonschema.ValidationError): alt.Chart.from_dict({"invalid": "spec"})
def test_display_options(): chart = alt.Chart('data.csv').mark_point().encode(x='foo:Q') # check that there are no options by default with check_render_options(): chart.display() # check that display options are passed with check_render_options(embed_options={ 'tooltip': False, 'renderer': 'canvas' }): chart.display('canvas', tooltip=False) # check that above options do not persist with check_render_options(): chart.display() # check that display options augment rather than overwrite pre-set options with alt.renderers.enable(embed_options={ 'tooltip': True, 'renderer': 'svg' }): with check_render_options(embed_options={ 'tooltip': True, 'renderer': 'svg' }): chart.display() with check_render_options(embed_options={ 'tooltip': True, 'renderer': 'canvas' }): chart.display('canvas') # check that above options do not persist with check_render_options(): chart.display()
def test_display_options(): chart = alt.Chart("data.csv").mark_point().encode(x="foo:Q") # check that there are no options by default with check_render_options(): chart.display() # check that display options are passed with check_render_options(embed_options={ "tooltip": False, "renderer": "canvas" }): chart.display("canvas", tooltip=False) # check that above options do not persist with check_render_options(): chart.display() # check that display options augment rather than overwrite pre-set options with alt.renderers.enable(embed_options={ "tooltip": True, "renderer": "svg" }): with check_render_options(embed_options={ "tooltip": True, "renderer": "svg" }): chart.display() with check_render_options(embed_options={ "tooltip": True, "renderer": "canvas" }): chart.display("canvas") # check that above options do not persist with check_render_options(): chart.display()
def test_selection(): # test instantiation of selections interval = alt.selection_interval(name='selec_1') assert interval.selection.type == 'interval' assert interval.name == 'selec_1' single = alt.selection_single(name='selec_2') assert single.selection.type == 'single' assert single.name == 'selec_2' multi = alt.selection_multi(name='selec_3') assert multi.selection.type == 'multi' assert multi.name == 'selec_3' # test adding to chart chart = alt.Chart().add_selection(single) chart = chart.add_selection(multi, interval) assert set(chart.selection.keys()) == {'selec_1', 'selec_2', 'selec_3'} # test logical operations assert isinstance(single & multi, alt.SelectionAnd) assert isinstance(single | multi, alt.SelectionOr) assert isinstance(~single, alt.SelectionNot)
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
def test_facet_parse_data(): data = pd.DataFrame({'x': range(5), 'y': range(5), 'row': list('abcab')}) chart = alt.Chart(data).mark_point().encode( x='x', y='y:O' ).facet( row='row', column='column:O' ) with alt.data_transformers.enable(consolidate_datasets=False): dct = chart.to_dict() assert 'values' in dct['data'] assert 'data' not in dct['spec'] assert dct['facet'] == {'column': {'field': 'column', 'type': 'ordinal'}, 'row': {'field': 'row', 'type': 'nominal'}} with alt.data_transformers.enable(consolidate_datasets=True): dct = chart.to_dict() assert 'datasets' in dct assert 'name' in dct['data'] assert 'data' not in dct['spec'] assert dct['facet'] == {'column': {'field': 'column', 'type': 'ordinal'}, 'row': {'field': 'row', 'type': 'nominal'}}
def test_geo_interface_serializing_arrays_tuples(): import array as arr geom = { "bbox": arr.array('d', [1, 2, 3, 4]), "geometry": { "coordinates": [ tuple((tuple((6.90, 53.48)), tuple( (5.98, 51.85)), tuple((6.07, 53.51)), tuple( (6.90, 53.48)))) ], "type": "Polygon" }, "id": 27, "properties": {}, "type": "Feature" } feat = geom_obj(geom) with alt.data_transformers.enable(consolidate_datasets=False): spec = alt.Chart(feat).mark_geoshape().to_dict() assert spec['data']['values']['geometry']['coordinates'][0][0] == [ 6.9, 53.48 ]
def test_data_property(): data = pd.DataFrame({"x": [1, 2, 3], "y": list("ABC")}) chart1 = alt.Chart(data).mark_point() chart2 = alt.Chart().mark_point().properties(data=data) assert chart1.to_dict() == chart2.to_dict()
def Chart(data): return alt.Chart(data).mark_point().encode(x="x:Q", y="y:Q")
def test_selection_property(): sel = alt.selection_interval() chart = alt.Chart("data.csv").mark_point().properties(selection=sel) assert list(chart["selection"].keys()) == [sel.name]