Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

feat: update charts in datasource column (#5054)

Shahmir Varqha50f657e1562e
diff --git a/frontend/src/components/data-table/types.ts b/frontend/src/components/data-table/types.ts
index 14252212fd..ef1b832b87 100644
--- a/frontend/src/components/data-table/types.ts
+++ b/frontend/src/components/data-table/types.ts
@@ -5,22 +5,27 @@ import { Objects } from "@/utils/objects";
export type ColumnName = string;
-export interface ColumnHeaderStats {
- total?: number | null;
- nulls?: number | null;
- unique?: number | null;
- true?: number | null;
- false?: number | null;
- min?: number | string | null;
- max?: number | string | null;
- mean?: number | string | null;
- median?: number | string | null;
- std?: number | string | null;
- p5?: number | string | null;
- p25?: number | string | null;
- p75?: number | string | null;
- p95?: number | string | null;
-}
+export const ColumnHeaderStatsKeys = [
+ "total",
+ "nulls",
+ "unique",
+ "true",
+ "false",
+ "min",
+ "max",
+ "mean",
+ "median",
+ "std",
+ "p5",
+ "p25",
+ "p75",
+ "p95",
+];
+export type ColumnHeaderStatsKey = (typeof ColumnHeaderStatsKeys)[number];
+export type ColumnHeaderStats = Record<
+ ColumnHeaderStatsKey,
+ number | string | null
+>;
export type FieldTypesWithExternalType = Array<
[columnName: string, [dataType: DataType, externalType: string]]
diff --git a/frontend/src/components/datasources/datasources.tsx b/frontend/src/components/datasources/datasources.tsx
index afc5b934e3..adf8f3d51f 100644
--- a/frontend/src/components/datasources/datasources.tsx
+++ b/frontend/src/components/datasources/datasources.tsx
@@ -75,7 +75,7 @@ import {
RotatingChevron,
} from "./components";
import { InstallPackageButton } from "./install-package-button";
-import { isSchemaless, sqlCode } from "./utils";
+import { convertStatsName, isSchemaless, sqlCode } from "./utils";
import { useOnMount } from "@/hooks/useLifecycle";
import {
PreviewSQLTableList,
@@ -874,7 +874,9 @@ const DatasetColumnPreview: React.FC<{
className="h-3 w-3 invisible group-hover:visible"
value={String(value)}
/>
- <span className="text-xs min-w-[60px] uppercase">{key}</span>
+ <span className="text-xs min-w-[60px] capitalize">
+ {convertStatsName(key, column.type)}
+ </span>
<span className="text-xs font-bold text-muted-foreground tracking-wide">
{prettyNumber(value)}
</span>
diff --git a/frontend/src/components/datasources/utils.ts b/frontend/src/components/datasources/utils.ts
index 2282a4ea95..1f83be35cc 100644
--- a/frontend/src/components/datasources/utils.ts
+++ b/frontend/src/components/datasources/utils.ts
@@ -3,7 +3,8 @@ import {
type SQLTableContext,
DUCKDB_ENGINE,
} from "@/core/datasets/data-source-connections";
-import type { DataTable } from "@/core/kernel/messages";
+import type { DataTable, DataType } from "@/core/kernel/messages";
+import type { ColumnHeaderStatsKeys } from "../data-table/types";
// Some databases have no schemas, so we don't show it (eg. Clickhouse)
export function isSchemaless(schemaName: string) {
@@ -45,3 +46,18 @@ export function sqlCode(
return `_df = mo.sql(f'SELECT "${columnName}" FROM ${table.name} LIMIT 100')`;
}
+
+export function convertStatsName(
+ stat: (typeof ColumnHeaderStatsKeys)[number],
+ type: DataType,
+) {
+ if (type === "date" || type === "datetime" || type === "time") {
+ if (stat === "min") {
+ return "Earliest";
+ }
+ if (stat === "max") {
+ return "Latest";
+ }
+ }
+ return stat;
+}
diff --git a/frontend/src/plugins/impl/DataTablePlugin.tsx b/frontend/src/plugins/impl/DataTablePlugin.tsx
index d4e7949d45..247928d101 100644
--- a/frontend/src/plugins/impl/DataTablePlugin.tsx
+++ b/frontend/src/plugins/impl/DataTablePlugin.tsx
@@ -95,6 +95,8 @@ export interface GetRowResult {
rows: unknown[];
}
+const maybeNumber = z.union([z.number(), z.nan(), z.string()]).nullable();
+
/**
* Arguments for a data table
*
@@ -213,15 +215,15 @@ export const DataTablePlugin = createPlugin<S>("marimo-table")
unique: z.number().nullable(),
true: z.number().nullable(),
false: z.number().nullable(),
- min: z.union([z.number(), z.nan(), z.string()]).nullable(),
- max: z.union([z.number(), z.nan(), z.string()]).nullable(),
- std: z.union([z.number(), z.nan(), z.string()]).nullable(),
- mean: z.union([z.number(), z.nan(), z.string()]).nullable(),
- median: z.union([z.number(), z.nan(), z.string()]).nullable(),
- p5: z.union([z.number(), z.nan(), z.string()]).nullable(),
- p25: z.union([z.number(), z.nan(), z.string()]).nullable(),
- p75: z.union([z.number(), z.nan(), z.string()]).nullable(),
- p95: z.union([z.number(), z.nan(), z.string()]).nullable(),
+ min: maybeNumber,
+ max: maybeNumber,
+ std: maybeNumber,
+ mean: maybeNumber,
+ median: maybeNumber,
+ p5: maybeNumber,
+ p25: maybeNumber,
+ p75: maybeNumber,
+ p95: maybeNumber,
}),
),
is_disabled: z.boolean().optional(),
diff --git a/marimo/_data/charts.py b/marimo/_data/charts.py
index 5bfd7e9527..fa8c140231 100644
--- a/marimo/_data/charts.py
+++ b/marimo/_data/charts.py
@@ -4,7 +4,7 @@ from __future__ import annotations
import abc
from dataclasses import dataclass
from textwrap import dedent
-from typing import Any, cast
+from typing import TYPE_CHECKING, Any, Literal, Optional, cast
import narwhals.stable.v1 as nw
@@ -12,6 +12,9 @@ from marimo._data.models import DataType
from marimo._utils import assert_never
from marimo._utils.narwhals_utils import can_narwhalify
+if TYPE_CHECKING:
+ import altair as alt
+
@abc.abstractmethod
class ChartBuilder:
@@ -28,7 +31,8 @@ class ChartBuilder:
return cast(str, self.altair(data, column).to_json())
@abc.abstractmethod
- def altair_code(self, data: str, column: str) -> str:
+ def altair_code(self, data: str, column: str, simple: bool) -> str:
+ """If simple, return simple altair code."""
raise NotImplementedError
@@ -38,30 +42,85 @@ class ChartParams:
column: str
+# Comma grouping and no decimals
+TOOLTIP_COUNT_FORMAT = ",.0f"
+
+# Comma grouping and 2 decimals
+TOOLTIP_NUMBER_FORMAT = ",.2f"
+
+# Percentage with 2 decimals
+TOOLTIP_PERCENTAGE_FORMAT = ".2%"
+
+NUM_RECORDS = "Number of records"
+
+# Similar to mint.mint11 (same as table charts)
+COLOR = "#1C7361"
+
+# Set width to container and remove border lines of chart
+COMMON_CONFIG = 'properties(width="container").configure_view(stroke=None)'
+
+
+def add_common_config(chart: alt.Chart | alt.LayerChart) -> alt.Chart:
+ return chart.properties(width="container").configure_view(stroke=None) # type: ignore
+
+
class NumberChartBuilder(ChartBuilder):
def altair(self, data: Any, column: str) -> Any:
import altair as alt
- return (
+ chart = (
alt.Chart(data)
- .mark_bar()
+ .mark_bar(color=COLOR)
.encode(
- x=alt.X(column, type="quantitative", bin=True),
- y=alt.Y("count()", type="quantitative"),
+ x=alt.X(column, type="quantitative", bin=True, title=column),
+ y=alt.Y("count()", type="quantitative", title=NUM_RECORDS),
+ tooltip=[
+ alt.Tooltip(
+ column,
+ type="quantitative",
+ bin=True,
+ title=column,
+ format=TOOLTIP_NUMBER_FORMAT,
+ ),
+ alt.Tooltip(
+ "count()",
+ type="quantitative",
+ format=TOOLTIP_COUNT_FORMAT,
+ title=NUM_RECORDS,
+ ),
+ ],
)
- .properties(width="container")
+ )
+ return add_common_config(chart)
+
+ def altair_code(self, data: str, column: str, simple: bool) -> str:
+ mark_bar = (
+ """.mark_bar()""" if simple else """.mark_bar(color="{COLOR}")"""
)
- def altair_code(self, data: str, column: str) -> str:
return f"""
_chart = (
alt.Chart({data})
- .mark_bar()
+ {mark_bar}
.encode(
- x=alt.X("{column}", type="quantitative", bin=True),
- y=alt.Y("count()", type="quantitative"),
- )
- .properties(width="container")
+ x=alt.X("{column}", type="quantitative", bin=True, title="{column}"),
+ y=alt.Y("count()", type="quantitative", title="{NUM_RECORDS}"),
+ tooltip=[
+ alt.Tooltip(
+ "{column}",
+ type="quantitative",
+ bin=True,
+ title="{column}",
+ format="{TOOLTIP_NUMBER_FORMAT}",
+ ),
+ alt.Tooltip(
+ "count()",
+ type="quantitative",
+ format="{TOOLTIP_COUNT_FORMAT}",
+ title="{NUM_RECORDS}",
+ ),
+ ],
+ ).{COMMON_CONFIG}
)
_chart
"""
@@ -75,81 +134,204 @@ class StringChartBuilder(ChartBuilder):
def altair(self, data: Any, column: str) -> Any:
import altair as alt
- if self.should_limit_to_10_items:
- return (
- alt.Chart(data)
- .transform_aggregate(count="count()", groupby=[column])
- .transform_window(
- rank="rank()",
- sort=[
- alt.SortField("count", order="descending"),
- alt.SortField(column, order="ascending"),
- ],
- )
- .transform_filter(alt.datum.rank <= 10)
- .mark_bar()
- .encode(
- y=alt.Y(column, type="nominal", sort="-x"),
- x=alt.X("count", type="quantitative"),
- )
- .properties(title=f"Top 10 {column}", width="container")
- )
-
- return (
+ _base_chart = (
alt.Chart(data)
- .mark_bar()
+ .transform_aggregate(count="count()", groupby=[column])
+ .transform_window(
+ rank="rank()",
+ sort=[
+ alt.SortField("count", order="descending"),
+ alt.SortField(column, order="ascending"),
+ ],
+ )
+ .transform_joinaggregate(total_count="sum(count)")
+ .transform_calculate(percentage="datum.count / datum.total_count")
.encode(
- y=alt.Y(column, type="nominal"),
- x=alt.X("count()", type="quantitative"),
+ y=alt.Y(
+ f"{column}:N",
+ sort="-x",
+ axis=alt.Axis(title=None),
+ ),
+ x=alt.X("count:Q", title=NUM_RECORDS),
+ tooltip=[
+ alt.Tooltip(f"{column}:N"),
+ alt.Tooltip(
+ "count:Q",
+ format=TOOLTIP_COUNT_FORMAT,
+ title=NUM_RECORDS,
+ ),
+ ],
)
- .properties(width="container")
)
- def altair_code(self, data: str, column: str) -> str:
+ def add_encodings(chart: alt.Chart) -> alt.Chart:
+ _bar_chart = chart.mark_bar(color=COLOR)
+ _text_chart = chart.mark_text(align="left", dx=3).encode(
+ text=alt.Text("percentage:Q", format=TOOLTIP_PERCENTAGE_FORMAT)
+ )
+ return _bar_chart + _text_chart # type: ignore
+
if self.should_limit_to_10_items:
- return f"""
- _chart = (
- alt.Chart({data})
- .transform_aggregate(count="count()", groupby=["{column}"])
- .transform_window(
- rank="rank()",
- sort=[
- alt.SortField("count", order="descending"),
- alt.SortField("{column}", order="ascending"),
- ],
- )
- .transform_filter(alt.datum.rank <= 10)
- .mark_bar()
- .encode(
- y=alt.Y("{column}", type="nominal", sort="-x"),
- x=alt.X("count", type="quantitative"),
- )
- .properties(title="Top 10 {column}", width="container")
+ _base_chart = _base_chart.transform_filter(alt.datum.rank <= 10)
+ _chart = add_encodings(_base_chart)
+ return (
+ _chart.properties(title=f"Top 10 {column}", width="container")
+ .configure_view(stroke=None)
+ .configure_axis(grid=False)
)
- _chart
- """
+
+ _chart_with_encodings = add_encodings(_base_chart)
+ _chart = add_common_config(_chart_with_encodings)
+ return _chart.configure_axis(grid=False)
+
+ def altair_code(self, data: str, column: str, simple: bool) -> str:
+ return (
+ self.simple_altair_code(data, column)
+ if simple
+ else self.complex_altair_code(data, column)
+ )
+
+ def simple_altair_code(self, data: str, column: str) -> str:
+ properties_config = (
+ """.properties(title="Top 10 {column}", width="container")"""
+ if self.should_limit_to_10_items
+ else """.properties(width="container")"""
+ )
return f"""
_chart = (
alt.Chart({data})
.mark_bar()
+ .transform_aggregate(count="count()", groupby=["{column}"])
+ .transform_window(
+ rank="rank()",
+ sort=[
+ alt.SortField("count", order="descending"),
+ alt.SortField("{column}", order="ascending"),
+ ],
+ )
+ .transform_filter(alt.datum.rank <= 10)
.encode(
- y=alt.Y("{column}", type="nominal"),
- x=alt.X("count()", type="quantitative"),
+ y=alt.Y(
+ "{column}:N",
+ sort="-x",
+ axis=alt.Axis(title=None),
+ ),
+ x=alt.X("count:Q", title="{NUM_RECORDS}"),
+ tooltip=[
+ alt.Tooltip("{column}:N"),
+ alt.Tooltip("count:Q", format="{TOOLTIP_COUNT_FORMAT}", title="{NUM_RECORDS}"),
+ ],
)
- .properties(width="container")
+ {properties_config}
+ .configure_view(stroke=None)
+ .configure_axis(grid=False)
)
_chart
"""
+ def complex_altair_code(self, data: str, column: str) -> str:
+ base_chart_code = dedent(f"""
+ _base_chart = (
+ alt.Chart({data})
+ .transform_aggregate(count="count()", groupby=["{column}"])
+ .transform_window(
+ rank="rank()",
+ sort=[
+ alt.SortField("count", order="descending"),
+ alt.SortField("{column}", order="ascending"),
+ ],
+ )
+ .transform_filter(alt.datum.rank <= 10)
+ .transform_joinaggregate(total_count="sum(count)")
+ .transform_calculate(
+ percentage="datum.count / datum.total_count"
+ )
+ .encode(
+ y=alt.Y(
+ "{column}:N",
+ sort="-x",
+ axis=alt.Axis(title=None),
+ ),
+ x=alt.X("count:Q", title="{NUM_RECORDS}"),
+ tooltip=[
+ alt.Tooltip("{column}:N"),
+ alt.Tooltip("count:Q", format="{TOOLTIP_COUNT_FORMAT}", title="{NUM_RECORDS}"),
+ ],
+ )
+ )
+
+ _bar_chart = _base_chart.mark_bar(color="{COLOR}")
+ _text_chart = _base_chart.mark_text(align="left", dx=3).encode(
+ text=alt.Text("percentage:Q", format="{TOOLTIP_PERCENTAGE_FORMAT}")
+ )
+ """)
+
+ if self.should_limit_to_10_items:
+ return f"""
+ {base_chart_code}
+_chart = (
+ (_bar_chart + _text_chart)
+ .properties(title="Top 10 {column}", width="container")
+ .configure_view(stroke=None)
+ .configure_axis(grid=False)
+)
+_chart
+ """
+
+ return f"""
+ {base_chart_code}
+_chart = (
+ (_bar_chart + _text_chart)
+ .properties(width="container")
+ .configure_view(stroke=None)
+ .configure_axis(grid=False)
+)
+_chart
+ """
+
+
+TimeUnitOptions = Literal[
+ "year",
+ "month",
+ "date",
+ "yearmonth",
+ "yearmonthdate",
+ "monthdate",
+ "yearmonthdatehours",
+ "yearmonthdatehoursminutes",
+]
+
class DateChartBuilder(ChartBuilder):
DEFAULT_DATE_FORMAT = "%Y-%m-%d"
+ DEFAULT_TIME_UNIT: TimeUnitOptions = "yearmonthdate"
+
+ def __init__(self) -> None:
+ self.date_format: Optional[str] = None
+ self.time_unit: Optional[TimeUnitOptions] = None
- def _guess_date_format(self, data: Any, column: str) -> str:
- """Guess the appropriate date format based on the range of dates in the column."""
+ def _get_date_format(
+ self, data: Any, column: str
+ ) -> tuple[str, TimeUnitOptions]:
+ if self.date_format is not None and self.time_unit is not None:
+ return self.date_format, self.time_unit
+ else:
+ date_format, time_unit = self._guess_date_format(data, column)
+ # Set the date format and time unit to avoid recalculating
+ self.date_format = str(date_format)
+ self.time_unit = time_unit
+ return date_format, time_unit
+
+ def _guess_date_format(
+ self, data: Any, column: str
+ ) -> tuple[str, TimeUnitOptions]:
+ """
+ Guess the appropriate date format based on the range of dates in the column.
+ Returns date_format, time_unit
+ """
if not can_narwhalify(data, eager_only=True):
- return "%Y-%m-%d"
+ return self.DEFAULT_DATE_FORMAT, self.DEFAULT_TIME_UNIT
df = nw.from_native(data, eager_only=True)
@@ -160,87 +342,324 @@ class DateChartBuilder(ChartBuilder):
# Calculate the difference in days
time_diff = max_date - min_date
if not hasattr(time_diff, "days"):
- return self.DEFAULT_DATE_FORMAT
+ return self.DEFAULT_DATE_FORMAT, self.DEFAULT_TIME_UNIT
days_diff = time_diff.days
# Choose format based on the range
if days_diff > 365 * 10: # More than 10 years
- return "%Y" # Year only
+ return "%Y", "year" # Year only
elif days_diff > 365: # More than a year
- return "%Y-%m" # Year and month
+ return "%Y-%m", "yearmonth" # Year and month
elif days_diff > 31: # More than a month
- return "%Y-%m-%d" # Full date
+ return "%Y-%m-%d", "yearmonthdate" # Full date
elif days_diff > 1: # More than a day
- return "%Y-%m-%d %H" # Date and time (hours)
+ return "%Y-%m-%d %H", "yearmonthdatehours" # Date and time (hours)
else:
- return "%Y-%m-%d %H:%M" # Date and time (hours, minutes)
+ # Date and time (hours, minutes)
+ return (
+ "%Y-%m-%d %H:%M",
+ "yearmonthdatehoursminutes",
+ )
def altair(self, data: Any, column: str) -> Any:
import altair as alt
- return (
- alt.Chart(data)
- .mark_bar()
+ date_format, time_unit = self._get_date_format(data, column)
+ new_field = f"date_{column}"
+
+ base = alt.Chart(data).transform_filter(f"datum.{column} != null")
+
+ # Explicit time binning, create a new field
+ transformed = base.transform_timeunit(
+ as_=new_field, field=column, timeUnit=time_unit
+ ).transform_aggregate(count="count()", groupby=[new_field])
+
+ # Create a selection that picks the nearest points
+ nearest = alt.selection_point(
+ fields=[new_field], nearest=True, on="mouseover", empty=False
+ )
+
+ # Area chart
+ area = transformed.mark_area(
+ line={"color": COLOR},
+ color=alt.Gradient(
+ gradient="linear", # type: ignore
+ stops=[
+ alt.GradientStop(color="white", offset=0),
+ alt.GradientStop(color=COLOR, offset=1),
+ ],
+ x1=1,
+ x2=1,
+ y1=1,
+ y2=0,
+ ),
+ ).encode(
+ x=alt.X(f"{new_field}:T", title=column),
+ y=alt.Y("count:Q", title=NUM_RECORDS),
+ )
+
+ # Vertical line
+ rule = (
+ transformed.mark_rule(color="seagreen", strokeWidth=1)
.encode(
- x=alt.X(
- column,
- type="temporal",
- bin=alt.Bin(maxbins=20),
- axis=alt.Axis(
- format=self._guess_date_format(data, column)
+ x=f"{new_field}:T",
+ opacity=alt.condition(nearest, alt.value(0.6), alt.value(0)),
+ tooltip=[
+ alt.Tooltip(
+ f"{new_field}:T",
+ title=column,
+ timeUnit=time_unit,
),
- ),
- y=alt.Y("count()", type="quantitative"),
+ alt.Tooltip(
+ "count:Q",
+ title=NUM_RECORDS,
+ format=TOOLTIP_COUNT_FORMAT,
+ ),
+ ],
)
- .properties(width="container")
+ .add_params(nearest)
)
- def altair_code(self, data: str, column: str) -> str:
+ # Points on the chart
+ points = transformed.mark_point(
+ size=80,
+ color=COLOR,
+ filled=True,
+ ).encode(
+ x=f"{new_field}:T",
+ y="count:Q",
+ opacity=alt.condition(nearest, alt.value(1), alt.value(0)),
+ )
+
+ chart = add_common_config(alt.layer(area, points, rule))
+ return chart
+
+ def altair_code(self, data: str, column: str, simple: bool = True) -> str:
+ return (
+ self.simple_altair_code(data, column)
+ if simple
+ else self.complex_altair_code(data, column)
+ )
+
+ def simple_altair_code(self, data: str, column: str) -> str:
+ """Offer simple charts for users to copy"""
+ _, time_unit = self._get_date_format(data, column)
+ new_field = f"_{column}"
+
return f"""
_chart = (
alt.Chart({data})
- .mark_bar()
+ .transform_filter(f"datum.{column} != null")
+ .transform_timeunit(as_="{new_field}", field="{column}", timeUnit="{time_unit}")
+ .mark_area()
.encode(
- x=alt.X(
- "{column}",
- type="temporal",
- bin=alt.Bin(maxbins=20),
- axis=alt.Axis(format="%Y-%m-%d")
- ),
- y=alt.Y("count()", type="quantitative"),
+ x=alt.X("{new_field}:T", title="{column}"),
+ y=alt.Y("count():Q", title="{NUM_RECORDS}"),
+ tooltip=[
+ alt.Tooltip("{new_field}:T", title="{column}", timeUnit="{time_unit}"),
+ alt.Tooltip("count():Q", title="{NUM_RECORDS}", format="{TOOLTIP_COUNT_FORMAT}")
+ ]
+ ).{COMMON_CONFIG}
+ )
+ _chart
+ """
+
+ def complex_altair_code(self, data: str, column: str) -> str:
+ """Complex altair code for data charts. Offer more control over the chart"""
+ _, time_unit = self._get_date_format(data, column)
+
+ new_field = f"_{column}"
+
+ return f"""
+ _base = alt.Chart({data}).transform_filter(f"datum.{column} != null")
+
+ # Explicit time binning, create a new field
+ _transformed = _base.transform_timeunit(
+ as_="{new_field}", field="{column}", timeUnit="{time_unit}"
+ ).transform_aggregate(count="count()", groupby=["{new_field}"])
+
+ # Create a selection that picks the nearest points
+ _nearest = alt.selection_point(
+ fields=["{new_field}"],
+ nearest=True,
+ on="mouseover",
+ empty=False,
+ )
+
+ # Area chart
+ _area = _transformed.mark_area(
+ line={{"color": "{COLOR}"}},
+ color=alt.Gradient(
+ gradient="linear",
+ stops=[
+ alt.GradientStop(color="white", offset=0),
+ alt.GradientStop(color="{COLOR}", offset=1),
+ ],
+ x1=1,
+ x2=1,
+ y1=1,
+ y2=0,
+ ),
+ ).encode(
+ x=alt.X("{new_field}:T", title="{column}"),
+ y=alt.Y("count:Q", title="{NUM_RECORDS}"),
+ )
+
+ # Vertical line
+ _rule = (
+ _transformed.mark_rule(color="seagreen", strokeWidth=1)
+ .encode(
+ x="{new_field}:T",
+ opacity=alt.condition(_nearest, alt.value(0.6), alt.value(0)),
+ tooltip=[
+ alt.Tooltip(
+ "{new_field}:T",
+ title="{column}",
+ timeUnit="{time_unit}",
+ ),
+ alt.Tooltip(
+ "count:Q",
+ title="{NUM_RECORDS}",
+ format="{TOOLTIP_COUNT_FORMAT}",
+ ),
+ ],
)
- .properties(width="container")
+ .add_params(_nearest)
)
+
+ # Points on the chart
+ _points = _transformed.mark_point(
+ size=80,
+ color="{COLOR}",
+ filled=True,
+ ).encode(
+ x="{new_field}:T",
+ y="count:Q",
+ opacity=alt.condition(_nearest, alt.value(1), alt.value(0)),
+ )
+
+ _chart = alt.layer(_area, _points, _rule).{COMMON_CONFIG}
_chart
"""
class BooleanChartBuilder(ChartBuilder):
+ BASE_COLOR = ["#99c99c", "#1C7361"]
+
def altair(self, data: Any, column: str) -> Any:
import altair as alt
- return (
+ base = (
alt.Chart(data)
- .mark_bar()
+ .transform_aggregate(count="count()", groupby=[column])
+ .transform_joinaggregate(total="sum(count)")
+ .transform_calculate(percentage="datum.count / datum.total")
.encode(
- x=alt.X(column, type="nominal"),
- y=alt.Y("count()", type="quantitative"),
+ theta=alt.Theta(
+ field="count",
+ type="quantitative",
+ stack=True,
+ ),
+ color=alt.Color(
+ f"{column}:N",
+ scale=alt.Scale(range=self.BASE_COLOR),
+ ),
+ tooltip=[
+ alt.Tooltip(f"{column}:N", title=column),
+ alt.Tooltip(
+ "count:Q",
+ title=NUM_RECORDS,
+ format=TOOLTIP_COUNT_FORMAT,
+ ),
+ ],
)
- .properties(width="container")
)
- def altair_code(self, data: str, column: str) -> str:
+ pie = base.mark_arc(outerRadius=85)
+ text = base.mark_text(radius=100, size=13).encode(
+ text=alt.Text("percentage:Q", format=TOOLTIP_PERCENTAGE_FORMAT)
+ )
+
+ return (pie + text).properties(width="container")
+
+ def altair_code(self, data: str, column: str, simple: bool) -> str:
+ return (
+ self.simple_altair_code(data, column)
+ if simple
+ else self.complex_altair_code(data, column)
+ )
+
+ def complex_altair_code(self, data: str, column: str) -> str:
return f"""
- _chart = (
+ _base = (
alt.Chart({data})
- .mark_bar()
+ .transform_aggregate(
+ count="count()",
+ groupby=["{column}"]
+ )
+ .transform_joinaggregate(
+ total="sum(count)"
+ )
+ .transform_calculate(
+ percentage="datum.count / datum.total"
+ )
.encode(
- x=alt.X("{column}", type="nominal"),
- y=alt.Y("count()", type="quantitative"),
+ theta=alt.Theta(
+ field="count",
+ type="quantitative",
+ stack=True,
+ ),
+ color=alt.Color(
+ "{column}:N",
+ scale=alt.Scale(range={self.BASE_COLOR}),
+ legend=alt.Legend(title="{column}")
+ ),
+ tooltip=[
+ alt.Tooltip("{column}:N", title="{column}"),
+ alt.Tooltip("count:Q", title="{NUM_RECORDS}", format="{TOOLTIP_COUNT_FORMAT}"),
+ ],
)
- .properties(width="container")
)
+
+ _pie = _base.mark_arc(outerRadius=85)
+ _text = _base.mark_text(radius=100, size=13).encode(
+ text=alt.Text("percentage:Q", format="{TOOLTIP_PERCENTAGE_FORMAT}"),
+ )
+
+ _chart = (_pie + _text).properties(width="container")
+ _chart
+ """
+
+ def simple_altair_code(self, data: str, column: str) -> str:
+ """Removed colours"""
+
+ return f"""
+ _base = (
+ alt.Chart({data})
+ .transform_aggregate(count="count()", groupby=["{column}"])
+ .transform_joinaggregate(total="sum(count)")
+ .transform_calculate(percentage="datum.count / datum.total")
+ .encode(
+ theta=alt.Theta(
+ field="count",
+ type="quantitative",
+ stack=True,
+ ),
+ color=alt.Color("{column}:N"),
+ tooltip=[
+ alt.Tooltip("{column}:N", title="{column}"),
+ alt.Tooltip("count:Q", title="{NUM_RECORDS}", format="{TOOLTIP_COUNT_FORMAT}"),
+ ],
+ )
+ )
+
+ _pie = _base.mark_arc(outerRadius=85)
+ _text = _base.mark_text(radius=100, size=13).encode(
+ text=alt.Text("percentage:Q", format="{TOOLTIP_PERCENTAGE_FORMAT}"),
+ )
+
+ _chart = (_pie + _text).{COMMON_CONFIG}
_chart
"""
@@ -249,26 +668,54 @@ class IntegerChartBuilder(ChartBuilder):
def altair(self, data: Any, column: str) -> Any:
import altair as alt
- return (
+ chart = (
alt.Chart(data)
- .mark_bar()
+ .mark_bar(color=COLOR)
.encode(
- x=alt.X(column, type="quantitative", bin=True),
- y=alt.Y("count()", type="quantitative"),
+ x=alt.X(column, type="quantitative", bin=True, title=column),
+ y=alt.Y("count()", type="quantitative", title=NUM_RECORDS),
+ tooltip=[
+ alt.Tooltip(
+ column, type="quantitative", bin=True, title=column
+ ),
+ alt.Tooltip(
+ "count()",
+ type="quantitative",
+ format=TOOLTIP_COUNT_FORMAT,
+ title=NUM_RECORDS,
+ ),
+ ],
)
- .properties(width="container")
+ )
+ return add_common_config(chart)
+
+ def altair_code(self, data: str, column: str, simple: bool = True) -> str:
+ mark_bar = (
+ """.mark_bar()""" if simple else """.mark_bar(color="{COLOR}")"""
)
- def altair_code(self, data: str, column: str) -> str:
return f"""
_chart = (
alt.Chart({data})
- .mark_bar()
+ {mark_bar}
.encode(
- x=alt.X("{column}", type="quantitative", bin=True),
- y=alt.Y("count()", type="quantitative"),
- )
- .properties(width="container")
+ x=alt.X("{column}", type="quantitative", bin=True, title="{column}"),
+ y=alt.Y("count()", type="quantitative", title="{NUM_RECORDS}"),
+ tooltip=[
+ alt.Tooltip(
+ "{column}",
+ type="quantitative",
+ bin=True,
+ title="{column}",
+ ),
+ alt.Tooltip(
+ "count()",
+ type="quantitative",
+ format="{TOOLTIP_COUNT_FORMAT}",
+ title="{NUM_RECORDS}",
+ ),
+ ],
+ ).{COMMON_CONFIG}
)
_chart
"""
@@ -278,26 +725,39 @@ class UnknownChartBuilder(ChartBuilder):
def altair(self, data: Any, column: str) -> Any:
import altair as alt
- return (
+ chart = (
alt.Chart(data)
- .mark_bar()
+ .mark_bar(color=COLOR)
.encode(
x=alt.X(column, type="nominal"),
- y=alt.Y("count()", type="quantitative"),
+ y=alt.Y("count()", type="quantitative", title="{NUM_RECORDS}"),
+ tooltip=[
+ alt.Tooltip(column, type="nominal"),
+ alt.Tooltip(
+ "count()", type="quantitative", title=NUM_RECORDS
+ ),
+ ],
)
- .properties(width="container")
+ )
+ return add_common_config(chart)
+
+ def altair_code(self, data: str, column: str, simple: bool = True) -> str:
+ mark_bar = (
+ """.mark_bar()""" if simple else """.mark_bar(color="{COLOR}")"""
)
- def altair_code(self, data: str, column: str) -> str:
return f"""
_chart = (
alt.Chart({data})
- .mark_bar()
+ {mark_bar}
.encode(
x=alt.X("{column}", type="nominal"),
- y=alt.Y("count()", type="quantitative"),
- )
- .properties(width="container")
+ y=alt.Y("count()", type="quantitative", title="{NUM_RECORDS}"),
+ tooltip=[
+ alt.Tooltip("{column}", type="nominal"),
+ alt.Tooltip("count()", type="quantitative", title="{NUM_RECORDS}"),
+ ],
+ ).{COMMON_CONFIG}
)
_chart
"""
@@ -312,10 +772,10 @@ class WrapperChartBuilder(ChartBuilder):
data, _escape_special_path_characters(str(column))
)
- def altair_code(self, data: str, column: str) -> str:
+ def altair_code(self, data: str, column: str, simple: bool = True) -> str:
return dedent(
self.delegate.altair_code(
- data, _escape_special_path_characters(str(column))
+ data, _escape_special_path_characters(str(column)), simple
)
).strip()
diff --git a/marimo/_data/preview_column.py b/marimo/_data/preview_column.py
index c63364bc54..f8ddb7bd62 100644
--- a/marimo/_data/preview_column.py
+++ b/marimo/_data/preview_column.py
@@ -209,8 +209,7 @@ def _get_altair_chart(
chart_builder = get_chart_builder(column_type, should_limit_to_10_items)
code = chart_builder.altair_code(
- request.table_name,
- request.column_name,
+ request.table_name, request.column_name, simple=True
)
chart_max_rows_errors = False
diff --git a/tests/_data/snapshots/charts-complex.txt b/tests/_data/snapshots/charts-complex.txt
new file mode 100644
index 0000000000..c43b36d5df
--- /dev/null
+++ b/tests/_data/snapshots/charts-complex.txt
@@ -0,0 +1,403 @@
+# boolean
+_base = (
+ alt.Chart(df)
+ .transform_aggregate(
+ count="count()",
+ groupby=["some_column"]
+ )
+ .transform_joinaggregate(
+ total="sum(count)"
+ )
+ .transform_calculate(
+ percentage="datum.count / datum.total"
+ )
+ .encode(
+ theta=alt.Theta(
+ field="count",
+ type="quantitative",
+ stack=True,
+ ),
+ color=alt.Color(
+ "some_column:N",
+ scale=alt.Scale(range=['#99c99c', '#1C7361']),
+ legend=alt.Legend(title="some_column")
+ ),
+ tooltip=[
+ alt.Tooltip("some_column:N", title="some_column"),
+ alt.Tooltip("count:Q", title="Number of records", format=",.0f"),
+ ],
+ )
+)
+
+_pie = _base.mark_arc(outerRadius=85)
+_text = _base.mark_text(radius=100, size=13).encode(
+ text=alt.Text("percentage:Q", format=".2%"),
+)
+
+_chart = (_pie + _text).properties(width="container")
+_chart
+
+# date
+_base = alt.Chart(df).transform_filter(f"datum.some_column != null")
+
+# Explicit time binning, create a new field
+_transformed = _base.transform_timeunit(
+ as_="_some_column", field="some_column", timeUnit="yearmonthdate"
+).transform_aggregate(count="count()", groupby=["_some_column"])
+
+# Create a selection that picks the nearest points
+_nearest = alt.selection_point(
+ fields=["_some_column"],
+ nearest=True,
+ on="mouseover",
+ empty=False,
+)
+
+# Area chart
+_area = _transformed.mark_area(
+ line={"color": "#1C7361"},
+ color=alt.Gradient(
+ gradient="linear",
+ stops=[
+ alt.GradientStop(color="white", offset=0),
+ alt.GradientStop(color="#1C7361", offset=1),
+ ],
+ x1=1,
+ x2=1,
+ y1=1,
+ y2=0,
+ ),
+).encode(
+ x=alt.X("_some_column:T", title="some_column"),
+ y=alt.Y("count:Q", title="Number of records"),
+)
+
+# Vertical line
+_rule = (
+ _transformed.mark_rule(color="seagreen", strokeWidth=1)
+ .encode(
+ x="_some_column:T",
+ opacity=alt.condition(_nearest, alt.value(0.6), alt.value(0)),
+ tooltip=[
+ alt.Tooltip(
+ "_some_column:T",
+ title="some_column",
+ timeUnit="yearmonthdate",
+ ),
+ alt.Tooltip(
+ "count:Q",
+ title="Number of records",
+ format=",.0f",
+ ),
+ ],
+ )
+ .add_params(_nearest)
+)
+
+# Points on the chart
+_points = _transformed.mark_point(
+ size=80,
+ color="#1C7361",
+ filled=True,
+).encode(
+ x="_some_column:T",
+ y="count:Q",
+ opacity=alt.condition(_nearest, alt.value(1), alt.value(0)),
+)
+
+_chart = alt.layer(_area, _points, _rule).properties(width="container").configure_view(stroke=None)
+_chart
+
+# datetime
+_base = alt.Chart(df).transform_filter(f"datum.some_column != null")
+
+# Explicit time binning, create a new field
+_transformed = _base.transform_timeunit(
+ as_="_some_column", field="some_column", timeUnit="yearmonthdate"
+).transform_aggregate(count="count()", groupby=["_some_column"])
+
+# Create a selection that picks the nearest points
+_nearest = alt.selection_point(
+ fields=["_some_column"],
+ nearest=True,
+ on="mouseover",
+ empty=False,
+)
+
+# Area chart
+_area = _transformed.mark_area(
+ line={"color": "#1C7361"},
+ color=alt.Gradient(
+ gradient="linear",
+ stops=[
+ alt.GradientStop(color="white", offset=0),
+ alt.GradientStop(color="#1C7361", offset=1),
+ ],
+ x1=1,
+ x2=1,
+ y1=1,
+ y2=0,
+ ),
+).encode(
+ x=alt.X("_some_column:T", title="some_column"),
+ y=alt.Y("count:Q", title="Number of records"),
+)
+
+# Vertical line
+_rule = (
+ _transformed.mark_rule(color="seagreen", strokeWidth=1)
+ .encode(
+ x="_some_column:T",
+ opacity=alt.condition(_nearest, alt.value(0.6), alt.value(0)),
+ tooltip=[
+ alt.Tooltip(
+ "_some_column:T",
+ title="some_column",
+ timeUnit="yearmonthdate",
+ ),
+ alt.Tooltip(
+ "count:Q",
+ title="Number of records",
+ format=",.0f",
+ ),
+ ],
+ )
+ .add_params(_nearest)
+)
+
+# Points on the chart
+_points = _transformed.mark_point(
+ size=80,
+ color="#1C7361",
+ filled=True,
+).encode(
+ x="_some_column:T",
+ y="count:Q",
+ opacity=alt.condition(_nearest, alt.value(1), alt.value(0)),
+)
+
+_chart = alt.layer(_area, _points, _rule).properties(width="container").configure_view(stroke=None)
+_chart
+
+# time
+_base = alt.Chart(df).transform_filter(f"datum.some_column != null")
+
+# Explicit time binning, create a new field
+_transformed = _base.transform_timeunit(
+ as_="_some_column", field="some_column", timeUnit="yearmonthdate"
+).transform_aggregate(count="count()", groupby=["_some_column"])
+
+# Create a selection that picks the nearest points
+_nearest = alt.selection_point(
+ fields=["_some_column"],
+ nearest=True,
+ on="mouseover",
+ empty=False,
+)
+
+# Area chart
+_area = _transformed.mark_area(
+ line={"color": "#1C7361"},
+ color=alt.Gradient(
+ gradient="linear",
+ stops=[
+ alt.GradientStop(color="white", offset=0),
+ alt.GradientStop(color="#1C7361", offset=1),
+ ],
+ x1=1,
+ x2=1,
+ y1=1,
+ y2=0,
+ ),
+).encode(
+ x=alt.X("_some_column:T", title="some_column"),
+ y=alt.Y("count:Q", title="Number of records"),
+)
+
+# Vertical line
+_rule = (
+ _transformed.mark_rule(color="seagreen", strokeWidth=1)
+ .encode(
+ x="_some_column:T",
+ opacity=alt.condition(_nearest, alt.value(0.6), alt.value(0)),
+ tooltip=[
+ alt.Tooltip(
+ "_some_column:T",
+ title="some_column",
+ timeUnit="yearmonthdate",
+ ),
+ alt.Tooltip(
+ "count:Q",
+ title="Number of records",
+ format=",.0f",
+ ),
+ ],
+ )
+ .add_params(_nearest)
+)
+
+# Points on the chart
+_points = _transformed.mark_point(
+ size=80,
+ color="#1C7361",
+ filled=True,
+).encode(
+ x="_some_column:T",
+ y="count:Q",
+ opacity=alt.condition(_nearest, alt.value(1), alt.value(0)),
+)
+
+_chart = alt.layer(_area, _points, _rule).properties(width="container").configure_view(stroke=None)
+_chart
+
+# integer
+_chart = (
+ alt.Chart(df)
+ .mark_bar(color="{COLOR}")
+ .encode(
+ x=alt.X("some_column", type="quantitative", bin=True, title="some_column"),
+ y=alt.Y("count()", type="quantitative", title="Number of records"),
+ tooltip=[
+ alt.Tooltip(
+ "some_column",
+ type="quantitative",
+ bin=True,
+ title="some_column",
+ ),
+ alt.Tooltip(
+ "count()",
+ type="quantitative",
+ format=",.0f",
+ title="Number of records",
+ ),
+ ],
+ ).properties(width="container").configure_view(stroke=None)
+)
+_chart
+
+# number
+_chart = (
+ alt.Chart(df)
+ .mark_bar(color="{COLOR}")
+ .encode(
+ x=alt.X("some_column", type="quantitative", bin=True, title="some_column"),
+ y=alt.Y("count()", type="quantitative", title="Number of records"),
+ tooltip=[
+ alt.Tooltip(
+ "some_column",
+ type="quantitative",
+ bin=True,
+ title="some_column",
+ format=",.2f",
+ ),
+ alt.Tooltip(
+ "count()",
+ type="quantitative",
+ format=",.0f",
+ title="Number of records",
+ ),
+ ],
+ ).properties(width="container").configure_view(stroke=None)
+)
+_chart
+
+# string
+_base_chart = (
+ alt.Chart(df)
+ .transform_aggregate(count="count()", groupby=["some_column"])
+ .transform_window(
+ rank="rank()",
+ sort=[
+ alt.SortField("count", order="descending"),
+ alt.SortField("some_column", order="ascending"),
+ ],
+ )
+ .transform_filter(alt.datum.rank <= 10)
+ .transform_joinaggregate(total_count="sum(count)")
+ .transform_calculate(
+ percentage="datum.count / datum.total_count"
+ )
+ .encode(
+ y=alt.Y(
+ "some_column:N",
+ sort="-x",
+ axis=alt.Axis(title=None),
+ ),
+ x=alt.X("count:Q", title="Number of records"),
+ tooltip=[
+ alt.Tooltip("some_column:N"),
+ alt.Tooltip("count:Q", format=",.0f", title="Number of records"),
+ ],
+ )
+)
+
+_bar_chart = _base_chart.mark_bar(color="#1C7361")
+_text_chart = _base_chart.mark_text(align="left", dx=3).encode(
+ text=alt.Text("percentage:Q", format=".2%")
+)
+
+_chart = (
+ (_bar_chart + _text_chart)
+ .properties(width="container")
+ .configure_view(stroke=None)
+ .configure_axis(grid=False)
+)
+_chart
+
+# string (limit to 10 items)
+_base_chart = (
+ alt.Chart(df)
+ .transform_aggregate(count="count()", groupby=["some_column"])
+ .transform_window(
+ rank="rank()",
+ sort=[
+ alt.SortField("count", order="descending"),
+ alt.SortField("some_column", order="ascending"),
+ ],
+ )
+ .transform_filter(alt.datum.rank <= 10)
+ .transform_joinaggregate(total_count="sum(count)")
+ .transform_calculate(
+ percentage="datum.count / datum.total_count"
+ )
+ .encode(
+ y=alt.Y(
+ "some_column:N",
+ sort="-x",
+ axis=alt.Axis(title=None),
+ ),
+ x=alt.X("count:Q", title="Number of records"),
+ tooltip=[
+ alt.Tooltip("some_column:N"),
+ alt.Tooltip("count:Q", format=",.0f", title="Number of records"),
+ ],
+ )
+)
+
+_bar_chart = _base_chart.mark_bar(color="#1C7361")
+_text_chart = _base_chart.mark_text(align="left", dx=3).encode(
+ text=alt.Text("percentage:Q", format=".2%")
+)
+
+_chart = (
+ (_bar_chart + _text_chart)
+ .properties(title="Top 10 some_column", width="container")
+ .configure_view(stroke=None)
+ .configure_axis(grid=False)
+)
+_chart
+
+# unknown
+_chart = (
+ alt.Chart(df)
+ .mark_bar(color="{COLOR}")
+ .encode(
+ x=alt.X("some_column", type="nominal"),
+ y=alt.Y("count()", type="quantitative", title="Number of records"),
+ tooltip=[
+ alt.Tooltip("some_column", type="nominal"),
+ alt.Tooltip("count()", type="quantitative", title="Number of records"),
+ ],
+ ).properties(width="container").configure_view(stroke=None)
+)
+_chart
\ No newline at end of file
diff --git a/tests/_data/snapshots/charts.txt b/tests/_data/snapshots/charts.txt
index f5e39e624a..6e9f84f765 100644
--- a/tests/_data/snapshots/charts.txt
+++ b/tests/_data/snapshots/charts.txt
@@ -1,63 +1,79 @@
# boolean
-_chart = (
+_base = (
alt.Chart(df)
- .mark_bar()
+ .transform_aggregate(count="count()", groupby=["some_column"])
+ .transform_joinaggregate(total="sum(count)")
+ .transform_calculate(percentage="datum.count / datum.total")
.encode(
- x=alt.X("some_column", type="nominal"),
- y=alt.Y("count()", type="quantitative"),
+ theta=alt.Theta(
+ field="count",
+ type="quantitative",
+ stack=True,
+ ),
+ color=alt.Color("some_column:N"),
+ tooltip=[
+ alt.Tooltip("some_column:N", title="some_column"),
+ alt.Tooltip("count:Q", title="Number of records", format=",.0f"),
+ ],
)
- .properties(width="container")
)
+
+_pie = _base.mark_arc(outerRadius=85)
+_text = _base.mark_text(radius=100, size=13).encode(
+ text=alt.Text("percentage:Q", format=".2%"),
+)
+
+_chart = (_pie + _text).properties(width="container").configure_view(stroke=None)
_chart
# date
_chart = (
alt.Chart(df)
- .mark_bar()
+ .transform_filter(f"datum.some_column != null")
+ .transform_timeunit(as_="_some_column", field="some_column", timeUnit="yearmonthdate")
+ .mark_area()
.encode(
- x=alt.X(
- "some_column",
- type="temporal",
- bin=alt.Bin(maxbins=20),
- axis=alt.Axis(format="%Y-%m-%d")
- ),
- y=alt.Y("count()", type="quantitative"),
- )
- .properties(width="container")
+ x=alt.X("_some_column:T", title="some_column"),
+ y=alt.Y("count():Q", title="Number of records"),
+ tooltip=[
+ alt.Tooltip("_some_column:T", title="some_column", timeUnit="yearmonthdate"),
+ alt.Tooltip("count():Q", title="Number of records", format=",.0f")
+ ]
+ ).properties(width="container").configure_view(stroke=None)
)
_chart
# datetime
_chart = (
alt.Chart(df)
- .mark_bar()
+ .transform_filter(f"datum.some_column != null")
+ .transform_timeunit(as_="_some_column", field="some_column", timeUnit="yearmonthdate")
+ .mark_area()
.encode(
- x=alt.X(
- "some_column",
- type="temporal",
- bin=alt.Bin(maxbins=20),
- axis=alt.Axis(format="%Y-%m-%d")
- ),
- y=alt.Y("count()", type="quantitative"),
- )
- .properties(width="container")
+ x=alt.X("_some_column:T", title="some_column"),
+ y=alt.Y("count():Q", title="Number of records"),
+ tooltip=[
+ alt.Tooltip("_some_column:T", title="some_column", timeUnit="yearmonthdate"),
+ alt.Tooltip("count():Q", title="Number of records", format=",.0f")
+ ]
+ ).properties(width="container").configure_view(stroke=None)
)
_chart
# time
_chart = (
alt.Chart(df)
- .mark_bar()
+ .transform_filter(f"datum.some_column != null")
+ .transform_timeunit(as_="_some_column", field="some_column", timeUnit="yearmonthdate")
+ .mark_area()
.encode(
- x=alt.X(
- "some_column",
- type="temporal",
- bin=alt.Bin(maxbins=20),
- axis=alt.Axis(format="%Y-%m-%d")
- ),
- y=alt.Y("count()", type="quantitative"),
- )
- .properties(width="container")
+ x=alt.X("_some_column:T", title="some_column"),
+ y=alt.Y("count():Q", title="Number of records"),
+ tooltip=[
+ alt.Tooltip("_some_column:T", title="some_column", timeUnit="yearmonthdate"),
+ alt.Tooltip("count():Q", title="Number of records", format=",.0f")
+ ]
+ ).properties(width="container").configure_view(stroke=None)
)
_chart
@@ -66,10 +82,23 @@ _chart = (
alt.Chart(df)
.mark_bar()
.encode(
- x=alt.X("some_column", type="quantitative", bin=True),
- y=alt.Y("count()", type="quantitative"),
- )
- .properties(width="container")
+ x=alt.X("some_column", type="quantitative", bin=True, title="some_column"),
+ y=alt.Y("count()", type="quantitative", title="Number of records"),
+ tooltip=[
+ alt.Tooltip(
+ "some_column",
+ type="quantitative",
+ bin=True,
+ title="some_column",
+ ),
+ alt.Tooltip(
+ "count()",
+ type="quantitative",
+ format=",.0f",
+ title="Number of records",
+ ),
+ ],
+ ).properties(width="container").configure_view(stroke=None)
)
_chart
@@ -78,10 +107,24 @@ _chart = (
alt.Chart(df)
.mark_bar()
.encode(
- x=alt.X("some_column", type="quantitative", bin=True),
- y=alt.Y("count()", type="quantitative"),
- )
- .properties(width="container")
+ x=alt.X("some_column", type="quantitative", bin=True, title="some_column"),
+ y=alt.Y("count()", type="quantitative", title="Number of records"),
+ tooltip=[
+ alt.Tooltip(
+ "some_column",
+ type="quantitative",
+ bin=True,
+ title="some_column",
+ format=",.2f",
+ ),
+ alt.Tooltip(
+ "count()",
+ type="quantitative",
+ format=",.0f",
+ title="Number of records",
+ ),
+ ],
+ ).properties(width="container").configure_view(stroke=None)
)
_chart
@@ -89,17 +132,37 @@ _chart
_chart = (
alt.Chart(df)
.mark_bar()
+ .transform_aggregate(count="count()", groupby=["some_column"])
+ .transform_window(
+ rank="rank()",
+ sort=[
+ alt.SortField("count", order="descending"),
+ alt.SortField("some_column", order="ascending"),
+ ],
+ )
+ .transform_filter(alt.datum.rank <= 10)
.encode(
- y=alt.Y("some_column", type="nominal"),
- x=alt.X("count()", type="quantitative"),
+ y=alt.Y(
+ "some_column:N",
+ sort="-x",
+ axis=alt.Axis(title=None),
+ ),
+ x=alt.X("count:Q", title="Number of records"),
+ tooltip=[
+ alt.Tooltip("some_column:N"),
+ alt.Tooltip("count:Q", format=",.0f", title="Number of records"),
+ ],
)
.properties(width="container")
+ .configure_view(stroke=None)
+ .configure_axis(grid=False)
)
_chart
# string (limit to 10 items)
_chart = (
alt.Chart(df)
+ .mark_bar()
.transform_aggregate(count="count()", groupby=["some_column"])
.transform_window(
rank="rank()",
@@ -109,12 +172,21 @@ _chart = (
],
)
.transform_filter(alt.datum.rank <= 10)
- .mark_bar()
.encode(
- y=alt.Y("some_column", type="nominal", sort="-x"),
- x=alt.X("count", type="quantitative"),
+ y=alt.Y(
+ "some_column:N",
+ sort="-x",
+ axis=alt.Axis(title=None),
+ ),
+ x=alt.X("count:Q", title="Number of records"),
+ tooltip=[
+ alt.Tooltip("some_column:N"),
+ alt.Tooltip("count:Q", format=",.0f", title="Number of records"),
+ ],
)
- .properties(title="Top 10 some_column", width="container")
+ .properties(title="Top 10 {column}", width="container")
+ .configure_view(stroke=None)
+ .configure_axis(grid=False)
)
_chart
@@ -124,8 +196,11 @@ _chart = (
.mark_bar()
.encode(
x=alt.X("some_column", type="nominal"),
- y=alt.Y("count()", type="quantitative"),
- )
- .properties(width="container")
+ y=alt.Y("count()", type="quantitative", title="Number of records"),
+ tooltip=[
+ alt.Tooltip("some_column", type="nominal"),
+ alt.Tooltip("count()", type="quantitative", title="Number of records"),
+ ],
+ ).properties(width="container").configure_view(stroke=None)
)
_chart
\ No newline at end of file
diff --git a/tests/_data/snapshots/charts_bad_characters.txt b/tests/_data/snapshots/charts_bad_characters.txt
index 522c5e9d0f..f51f9d8973 100644
--- a/tests/_data/snapshots/charts_bad_characters.txt
+++ b/tests/_data/snapshots/charts_bad_characters.txt
@@ -2,11 +2,30 @@
_chart = (
alt.Chart(df)
.mark_bar()
+ .transform_aggregate(count="count()", groupby=["col<angles"])
+ .transform_window(
+ rank="rank()",
+ sort=[
+ alt.SortField("count", order="descending"),
+ alt.SortField("col<angles", order="ascending"),
+ ],
+ )
+ .transform_filter(alt.datum.rank <= 10)
.encode(
- y=alt.Y("col<angles", type="nominal"),
- x=alt.X("count()", type="quantitative"),
+ y=alt.Y(
+ "col<angles:N",
+ sort="-x",
+ axis=alt.Axis(title=None),
+ ),
+ x=alt.X("count:Q", title="Number of records"),
+ tooltip=[
+ alt.Tooltip("col<angles:N"),
+ alt.Tooltip("count:Q", format=",.0f", title="Number of records"),
+ ],
)
.properties(width="container")
+ .configure_view(stroke=None)
+ .configure_axis(grid=False)
)
_chart
@@ -14,11 +33,30 @@ _chart
_chart = (
alt.Chart(df)
.mark_bar()
+ .transform_aggregate(count="count()", groupby=["col\[0\]brackets"])
+ .transform_window(
+ rank="rank()",
+ sort=[
+ alt.SortField("count", order="descending"),
+ alt.SortField("col\[0\]brackets", order="ascending"),
+ ],
+ )
+ .transform_filter(alt.datum.rank <= 10)
.encode(
- y=alt.Y("col\[0\]brackets", type="nominal"),
- x=alt.X("count()", type="quantitative"),
+ y=alt.Y(
+ "col\[0\]brackets:N",
+ sort="-x",
+ axis=alt.Axis(title=None),
+ ),
+ x=alt.X("count:Q", title="Number of records"),
+ tooltip=[
+ alt.Tooltip("col\[0\]brackets:N"),
+ alt.Tooltip("count:Q", format=",.0f", title="Number of records"),
+ ],
)
.properties(width="container")
+ .configure_view(stroke=None)
+ .configure_axis(grid=False)
)
_chart
@@ -26,11 +64,30 @@ _chart
_chart = (
alt.Chart(df)
.mark_bar()
+ .transform_aggregate(count="count()", groupby=["col\:colon"])
+ .transform_window(
+ rank="rank()",
+ sort=[
+ alt.SortField("count", order="descending"),
+ alt.SortField("col\:colon", order="ascending"),
+ ],
+ )
+ .transform_filter(alt.datum.rank <= 10)
.encode(
- y=alt.Y("col\:colon", type="nominal"),
- x=alt.X("count()", type="quantitative"),
+ y=alt.Y(
+ "col\:colon:N",
+ sort="-x",
+ axis=alt.Axis(title=None),
+ ),
+ x=alt.X("count:Q", title="Number of records"),
+ tooltip=[
+ alt.Tooltip("col\:colon:N"),
+ alt.Tooltip("count:Q", format=",.0f", title="Number of records"),
+ ],
)
.properties(width="container")
+ .configure_view(stroke=None)
+ .configure_axis(grid=False)
)
_chart
@@ -38,11 +95,30 @@ _chart
_chart = (
alt.Chart(df)
.mark_bar()
+ .transform_aggregate(count="count()", groupby=["col\.period"])
+ .transform_window(
+ rank="rank()",
+ sort=[
+ alt.SortField("count", order="descending"),
+ alt.SortField("col\.period", order="ascending"),
+ ],
+ )
+ .transform_filter(alt.datum.rank <= 10)
.encode(
- y=alt.Y("col\.period", type="nominal"),
- x=alt.X("count()", type="quantitative"),
+ y=alt.Y(
+ "col\.period:N",
+ sort="-x",
+ axis=alt.Axis(title=None),
+ ),
+ x=alt.X("count:Q", title="Number of records"),
+ tooltip=[
+ alt.Tooltip("col\.period:N"),
+ alt.Tooltip("count:Q", format=",.0f", title="Number of records"),
+ ],
)
.properties(width="container")
+ .configure_view(stroke=None)
+ .configure_axis(grid=False)
)
_chart
@@ -50,10 +126,29 @@ _chart
_chart = (
alt.Chart(df)
.mark_bar()
+ .transform_aggregate(count="count()", groupby=["col\backslash"])
+ .transform_window(
+ rank="rank()",
+ sort=[
+ alt.SortField("count", order="descending"),
+ alt.SortField("col\backslash", order="ascending"),
+ ],
+ )
+ .transform_filter(alt.datum.rank <= 10)
.encode(
- y=alt.Y("col\backslash", type="nominal"),
- x=alt.X("count()", type="quantitative"),
+ y=alt.Y(
+ "col\backslash:N",
+ sort="-x",
+ axis=alt.Axis(title=None),
+ ),
+ x=alt.X("count:Q", title="Number of records"),
+ tooltip=[
+ alt.Tooltip("col\backslash:N"),
+ alt.Tooltip("count:Q", format=",.0f", title="Number of records"),
+ ],
)
.properties(width="container")
+ .configure_view(stroke=None)
+ .configure_axis(grid=False)
)
_chart
\ No newline at end of file
diff --git a/tests/_data/snapshots/charts_json.txt b/tests/_data/snapshots/charts_json.txt
index b8f8a1cf9f..b565aca9bf 100644
--- a/tests/_data/snapshots/charts_json.txt
+++ b/tests/_data/snapshots/charts_json.txt
@@ -23,19 +23,138 @@
}
]
},
- "encoding": {
- "x": {
- "field": "some_column",
- "type": "nominal"
+ "layer": [
+ {
+ "encoding": {
+ "color": {
+ "field": "some_column",
+ "scale": {
+ "range": [
+ "#99c99c",
+ "#1C7361"
+ ]
+ },
+ "type": "nominal"
+ },
+ "theta": {
+ "field": "count",
+ "stack": true,
+ "type": "quantitative"
+ },
+ "tooltip": [
+ {
+ "field": "some_column",
+ "title": "some_column",
+ "type": "nominal"
+ },
+ {
+ "field": "count",
+ "format": ",.0f",
+ "title": "Number of records",
+ "type": "quantitative"
+ }
+ ]
+ },
+ "mark": {
+ "outerRadius": 85,
+ "type": "arc"
+ },
+ "transform": [
+ {
+ "aggregate": [
+ {
+ "as": "count",
+ "op": "count"
+ }
+ ],
+ "groupby": [
+ "some_column"
+ ]
+ },
+ {
+ "joinaggregate": [
+ {
+ "as": "total",
+ "field": "count",
+ "op": "sum"
+ }
+ ]
+ },
+ {
+ "as": "percentage",
+ "calculate": "datum.count / datum.total"
+ }
+ ]
},
- "y": {
- "aggregate": "count",
- "type": "quantitative"
+ {
+ "encoding": {
+ "color": {
+ "field": "some_column",
+ "scale": {
+ "range": [
+ "#99c99c",
+ "#1C7361"
+ ]
+ },
+ "type": "nominal"
+ },
+ "text": {
+ "field": "percentage",
+ "format": ".2%",
+ "type": "quantitative"
+ },
+ "theta": {
+ "field": "count",
+ "stack": true,
+ "type": "quantitative"
+ },
+ "tooltip": [
+ {
+ "field": "some_column",
+ "title": "some_column",
+ "type": "nominal"
+ },
+ {
+ "field": "count",
+ "format": ",.0f",
+ "title": "Number of records",
+ "type": "quantitative"
+ }
+ ]
+ },
+ "mark": {
+ "radius": 100,
+ "size": 13,
+ "type": "text"
+ },
+ "transform": [
+ {
+ "aggregate": [
+ {
+ "as": "count",
+ "op": "count"
+ }
+ ],
+ "groupby": [
+ "some_column"
+ ]
+ },
+ {
+ "joinaggregate": [
+ {
+ "as": "total",
+ "field": "count",
+ "op": "sum"
+ }
+ ]
+ },
+ {
+ "as": "percentage",
+ "calculate": "datum.count / datum.total"
+ }
+ ]
}
- },
- "mark": {
- "type": "bar"
- },
+ ],
"width": "container"
}
@@ -45,7 +164,8 @@
"config": {
"view": {
"continuousHeight": 300,
- "continuousWidth": 300
+ "continuousWidth": 300,
+ "stroke": null
}
},
"data": {
@@ -64,25 +184,186 @@
}
]
},
- "encoding": {
- "x": {
- "axis": {
- "format": "%Y-%m-%d"
+ "layer": [
+ {
+ "encoding": {
+ "x": {
+ "field": "date_some_column",
+ "title": "some_column",
+ "type": "temporal"
+ },
+ "y": {
+ "field": "count",
+ "title": "Number of records",
+ "type": "quantitative"
+ }
},
- "bin": {
- "maxbins": 20
+ "mark": {
+ "color": {
+ "gradient": "linear",
+ "stops": [
+ {
+ "color": "white",
+ "offset": 0
+ },
+ {
+ "color": "#1C7361",
+ "offset": 1
+ }
+ ],
+ "x1": 1,
+ "x2": 1,
+ "y1": 1,
+ "y2": 0
+ },
+ "line": {
+ "color": "#1C7361"
+ },
+ "type": "area"
},
- "field": "some_column",
- "type": "temporal"
+ "transform": [
+ {
+ "filter": "datum.some_column != null"
+ },
+ {
+ "as": "date_some_column",
+ "field": "some_column",
+ "timeUnit": "yearmonthdate"
+ },
+ {
+ "aggregate": [
+ {
+ "as": "count",
+ "op": "count"
+ }
+ ],
+ "groupby": [
+ "date_some_column"
+ ]
+ }
+ ]
},
- "y": {
- "aggregate": "count",
- "type": "quantitative"
+ {
+ "encoding": {
+ "opacity": {
+ "condition": {
+ "empty": false,
+ "param": "param_1",
+ "value": 1
+ },
+ "value": 0
+ },
+ "x": {
+ "field": "date_some_column",
+ "type": "temporal"
+ },
+ "y": {
+ "field": "count",
+ "type": "quantitative"
+ }
+ },
+ "mark": {
+ "color": "#1C7361",
+ "filled": true,
+ "size": 80,
+ "type": "point"
+ },
+ "transform": [
+ {
+ "filter": "datum.some_column != null"
+ },
+ {
+ "as": "date_some_column",
+ "field": "some_column",
+ "timeUnit": "yearmonthdate"
+ },
+ {
+ "aggregate": [
+ {
+ "as": "count",
+ "op": "count"
+ }
+ ],
+ "groupby": [
+ "date_some_column"
+ ]
+ }
+ ]
+ },
+ {
+ "encoding": {
+ "opacity": {
+ "condition": {
+ "empty": false,
+ "param": "param_1",
+ "value": 0.6
+ },
+ "value": 0
+ },
+ "tooltip": [
+ {
+ "field": "date_some_column",
+ "timeUnit": "yearmonthdate",
+ "title": "some_column",
+ "type": "temporal"
+ },
+ {
+ "field": "count",
+ "format": ",.0f",
+ "title": "Number of records",
+ "type": "quantitative"
+ }
+ ],
+ "x": {
+ "field": "date_some_column",
+ "type": "temporal"
+ }
+ },
+ "mark": {
+ "color": "seagreen",
+ "strokeWidth": 1,
+ "type": "rule"
+ },
+ "name": "view_1",
+ "transform": [
+ {
+ "filter": "datum.some_column != null"
+ },
+ {
+ "as": "date_some_column",
+ "field": "some_column",
+ "timeUnit": "yearmonthdate"
+ },
+ {
+ "aggregate": [
+ {
+ "as": "count",
+ "op": "count"
+ }
+ ],
+ "groupby": [
+ "date_some_column"
+ ]
+ }
+ ]
}
- },
- "mark": {
- "type": "bar"
- },
+ ],
+ "params": [
+ {
+ "name": "param_1",
+ "select": {
+ "fields": [
+ "date_some_column"
+ ],
+ "nearest": true,
+ "on": "mouseover",
+ "type": "point"
+ },
+ "views": [
+ "view_1"
+ ]
+ }
+ ],
"width": "container"
}
@@ -92,7 +373,8 @@
"config": {
"view": {
"continuousHeight": 300,
- "continuousWidth": 300
+ "continuousWidth": 300,
+ "stroke": null
}
},
"data": {
@@ -111,25 +393,186 @@
}
]
},
- "encoding": {
- "x": {
- "axis": {
- "format": "%Y-%m-%d"
+ "layer": [
+ {
+ "encoding": {
+ "x": {
+ "field": "date_some_column",
+ "title": "some_column",
+ "type": "temporal"
+ },
+ "y": {
+ "field": "count",
+ "title": "Number of records",
+ "type": "quantitative"
+ }
},
- "bin": {
- "maxbins": 20
+ "mark": {
+ "color": {
+ "gradient": "linear",
+ "stops": [
+ {
+ "color": "white",
+ "offset": 0
+ },
+ {
+ "color": "#1C7361",
+ "offset": 1
+ }
+ ],
+ "x1": 1,
+ "x2": 1,
+ "y1": 1,
+ "y2": 0
+ },
+ "line": {
+ "color": "#1C7361"
+ },
+ "type": "area"
},
- "field": "some_column",
- "type": "temporal"
+ "transform": [
+ {
+ "filter": "datum.some_column != null"
+ },
+ {
+ "as": "date_some_column",
+ "field": "some_column",
+ "timeUnit": "yearmonthdate"
+ },
+ {
+ "aggregate": [
+ {
+ "as": "count",
+ "op": "count"
+ }
+ ],
+ "groupby": [
+ "date_some_column"
+ ]
+ }
+ ]
},
- "y": {
- "aggregate": "count",
- "type": "quantitative"
+ {
+ "encoding": {
+ "opacity": {
+ "condition": {
+ "empty": false,
+ "param": "param_2",
+ "value": 1
+ },
+ "value": 0
+ },
+ "x": {
+ "field": "date_some_column",
+ "type": "temporal"
+ },
+ "y": {
+ "field": "count",
+ "type": "quantitative"
+ }
+ },
+ "mark": {
+ "color": "#1C7361",
+ "filled": true,
+ "size": 80,
+ "type": "point"
+ },
+ "transform": [
+ {
+ "filter": "datum.some_column != null"
+ },
+ {
+ "as": "date_some_column",
+ "field": "some_column",
+ "timeUnit": "yearmonthdate"
+ },
+ {
+ "aggregate": [
+ {
+ "as": "count",
+ "op": "count"
+ }
+ ],
+ "groupby": [
+ "date_some_column"
+ ]
+ }
+ ]
+ },
+ {
+ "encoding": {
+ "opacity": {
+ "condition": {
+ "empty": false,
+ "param": "param_2",
+ "value": 0.6
+ },
+ "value": 0
+ },
+ "tooltip": [
+ {
+ "field": "date_some_column",
+ "timeUnit": "yearmonthdate",
+ "title": "some_column",
+ "type": "temporal"
+ },
+ {
+ "field": "count",
+ "format": ",.0f",
+ "title": "Number of records",
+ "type": "quantitative"
+ }
+ ],
+ "x": {
+ "field": "date_some_column",
+ "type": "temporal"
+ }
+ },
+ "mark": {
+ "color": "seagreen",
+ "strokeWidth": 1,
+ "type": "rule"
+ },
+ "name": "view_2",
+ "transform": [
+ {
+ "filter": "datum.some_column != null"
+ },
+ {
+ "as": "date_some_column",
+ "field": "some_column",
+ "timeUnit": "yearmonthdate"
+ },
+ {
+ "aggregate": [
+ {
+ "as": "count",
+ "op": "count"
+ }
+ ],
+ "groupby": [
+ "date_some_column"
+ ]
+ }
+ ]
}
- },
- "mark": {
- "type": "bar"
- },
+ ],
+ "params": [
+ {
+ "name": "param_2",
+ "select": {
+ "fields": [
+ "date_some_column"
+ ],
+ "nearest": true,
+ "on": "mouseover",
+ "type": "point"
+ },
+ "views": [
+ "view_2"
+ ]
+ }
+ ],
"width": "container"
}
@@ -139,7 +582,8 @@
"config": {
"view": {
"continuousHeight": 300,
- "continuousWidth": 300
+ "continuousWidth": 300,
+ "stroke": null
}
},
"data": {
@@ -158,25 +602,186 @@
}
]
},
- "encoding": {
- "x": {
- "axis": {
- "format": "%Y-%m-%d"
+ "layer": [
+ {
+ "encoding": {
+ "x": {
+ "field": "date_some_column",
+ "title": "some_column",
+ "type": "temporal"
+ },
+ "y": {
+ "field": "count",
+ "title": "Number of records",
+ "type": "quantitative"
+ }
},
- "bin": {
- "maxbins": 20
+ "mark": {
+ "color": {
+ "gradient": "linear",
+ "stops": [
+ {
+ "color": "white",
+ "offset": 0
+ },
+ {
+ "color": "#1C7361",
+ "offset": 1
+ }
+ ],
+ "x1": 1,
+ "x2": 1,
+ "y1": 1,
+ "y2": 0
+ },
+ "line": {
+ "color": "#1C7361"
+ },
+ "type": "area"
},
- "field": "some_column",
- "type": "temporal"
+ "transform": [
+ {
+ "filter": "datum.some_column != null"
+ },
+ {
+ "as": "date_some_column",
+ "field": "some_column",
+ "timeUnit": "yearmonthdate"
+ },
+ {
+ "aggregate": [
+ {
+ "as": "count",
+ "op": "count"
+ }
+ ],
+ "groupby": [
+ "date_some_column"
+ ]
+ }
+ ]
},
- "y": {
- "aggregate": "count",
- "type": "quantitative"
+ {
+ "encoding": {
+ "opacity": {
+ "condition": {
+ "empty": false,
+ "param": "param_3",
+ "value": 1
+ },
+ "value": 0
+ },
+ "x": {
+ "field": "date_some_column",
+ "type": "temporal"
+ },
+ "y": {
+ "field": "count",
+ "type": "quantitative"
+ }
+ },
+ "mark": {
+ "color": "#1C7361",
+ "filled": true,
+ "size": 80,
+ "type": "point"
+ },
+ "transform": [
+ {
+ "filter": "datum.some_column != null"
+ },
+ {
+ "as": "date_some_column",
+ "field": "some_column",
+ "timeUnit": "yearmonthdate"
+ },
+ {
+ "aggregate": [
+ {
+ "as": "count",
+ "op": "count"
+ }
+ ],
+ "groupby": [
+ "date_some_column"
+ ]
+ }
+ ]
+ },
+ {
+ "encoding": {
+ "opacity": {
+ "condition": {
+ "empty": false,
+ "param": "param_3",
+ "value": 0.6
+ },
+ "value": 0
+ },
+ "tooltip": [
+ {
+ "field": "date_some_column",
+ "timeUnit": "yearmonthdate",
+ "title": "some_column",
+ "type": "temporal"
+ },
+ {
+ "field": "count",
+ "format": ",.0f",
+ "title": "Number of records",
+ "type": "quantitative"
+ }
+ ],
+ "x": {
+ "field": "date_some_column",
+ "type": "temporal"
+ }
+ },
+ "mark": {
+ "color": "seagreen",
+ "strokeWidth": 1,
+ "type": "rule"
+ },
+ "name": "view_3",
+ "transform": [
+ {
+ "filter": "datum.some_column != null"
+ },
+ {
+ "as": "date_some_column",
+ "field": "some_column",
+ "timeUnit": "yearmonthdate"
+ },
+ {
+ "aggregate": [
+ {
+ "as": "count",
+ "op": "count"
+ }
+ ],
+ "groupby": [
+ "date_some_column"
+ ]
+ }
+ ]
}
- },
- "mark": {
- "type": "bar"
- },
+ ],
+ "params": [
+ {
+ "name": "param_3",
+ "select": {
+ "fields": [
+ "date_some_column"
+ ],
+ "nearest": true,
+ "on": "mouseover",
+ "type": "point"
+ },
+ "views": [
+ "view_3"
+ ]
+ }
+ ],
"width": "container"
}
@@ -186,7 +791,8 @@
"config": {
"view": {
"continuousHeight": 300,
- "continuousWidth": 300
+ "continuousWidth": 300,
+ "stroke": null
}
},
"data": {
@@ -206,17 +812,34 @@
]
},
"encoding": {
+ "tooltip": [
+ {
+ "bin": true,
+ "field": "some_column",
+ "title": "some_column",
+ "type": "quantitative"
+ },
+ {
+ "aggregate": "count",
+ "format": ",.0f",
+ "title": "Number of records",
+ "type": "quantitative"
+ }
+ ],
"x": {
"bin": true,
"field": "some_column",
+ "title": "some_column",
"type": "quantitative"
},
"y": {
"aggregate": "count",
+ "title": "Number of records",
"type": "quantitative"
}
},
"mark": {
+ "color": "#1C7361",
"type": "bar"
},
"width": "container"
@@ -228,7 +851,8 @@
"config": {
"view": {
"continuousHeight": 300,
- "continuousWidth": 300
+ "continuousWidth": 300,
+ "stroke": null
}
},
"data": {
@@ -248,17 +872,35 @@
]
},
"encoding": {
+ "tooltip": [
+ {
+ "bin": true,
+ "field": "some_column",
+ "format": ",.2f",
+ "title": "some_column",
+ "type": "quantitative"
+ },
+ {
+ "aggregate": "count",
+ "format": ",.0f",
+ "title": "Number of records",
+ "type": "quantitative"
+ }
+ ],
"x": {
"bin": true,
"field": "some_column",
+ "title": "some_column",
"type": "quantitative"
},
"y": {
"aggregate": "count",
+ "title": "Number of records",
"type": "quantitative"
}
},
"mark": {
+ "color": "#1C7361",
"type": "bar"
},
"width": "container"
@@ -268,9 +910,13 @@
{
"$schema": "https://vega.github.io/schema/vega-lite/v5.20.1.json",
"config": {
+ "axis": {
+ "grid": false
+ },
"view": {
"continuousHeight": 300,
- "continuousWidth": 300
+ "continuousWidth": 300,
+ "stroke": null
}
},
"data": {
@@ -289,19 +935,170 @@
}
]
},
- "encoding": {
- "x": {
- "aggregate": "count",
- "type": "quantitative"
+ "layer": [
+ {
+ "encoding": {
+ "tooltip": [
+ {
+ "field": "some_column",
+ "type": "nominal"
+ },
+ {
+ "field": "count",
+ "format": ",.0f",
+ "title": "Number of records",
+ "type": "quantitative"
+ }
+ ],
+ "x": {
+ "field": "count",
+ "title": "Number of records",
+ "type": "quantitative"
+ },
+ "y": {
+ "axis": {
+ "title": null
+ },
+ "field": "some_column",
+ "sort": "-x",
+ "type": "nominal"
+ }
+ },
+ "mark": {
+ "color": "#1C7361",
+ "type": "bar"
+ },
+ "transform": [
+ {
+ "aggregate": [
+ {
+ "as": "count",
+ "op": "count"
+ }
+ ],
+ "groupby": [
+ "some_column"
+ ]
+ },
+ {
+ "sort": [
+ {
+ "field": "count",
+ "order": "descending"
+ },
+ {
+ "field": "some_column",
+ "order": "ascending"
+ }
+ ],
+ "window": [
+ {
+ "as": "rank",
+ "field": "",
+ "op": "rank"
+ }
+ ]
+ },
+ {
+ "joinaggregate": [
+ {
+ "as": "total_count",
+ "field": "count",
+ "op": "sum"
+ }
+ ]
+ },
+ {
+ "as": "percentage",
+ "calculate": "datum.count / datum.total_count"
+ }
+ ]
},
- "y": {
- "field": "some_column",
- "type": "nominal"
+ {
+ "encoding": {
+ "text": {
+ "field": "percentage",
+ "format": ".2%",
+ "type": "quantitative"
+ },
+ "tooltip": [
+ {
+ "field": "some_column",
+ "type": "nominal"
+ },
+ {
+ "field": "count",
+ "format": ",.0f",
+ "title": "Number of records",
+ "type": "quantitative"
+ }
+ ],
+ "x": {
+ "field": "count",
+ "title": "Number of records",
+ "type": "quantitative"
+ },
+ "y": {
+ "axis": {
+ "title": null
+ },
+ "field": "some_column",
+ "sort": "-x",
+ "type": "nominal"
+ }
+ },
+ "mark": {
+ "align": "left",
+ "dx": 3,
+ "type": "text"
+ },
+ "transform": [
+ {
+ "aggregate": [
+ {
+ "as": "count",
+ "op": "count"
+ }
+ ],
+ "groupby": [
+ "some_column"
+ ]
+ },
+ {
+ "sort": [
+ {
+ "field": "count",
+ "order": "descending"
+ },
+ {
+ "field": "some_column",
+ "order": "ascending"
+ }
+ ],
+ "window": [
+ {
+ "as": "rank",
+ "field": "",
+ "op": "rank"
+ }
+ ]
+ },
+ {
+ "joinaggregate": [
+ {
+ "as": "total_count",
+ "field": "count",
+ "op": "sum"
+ }
+ ]
+ },
+ {
+ "as": "percentage",
+ "calculate": "datum.count / datum.total_count"
+ }
+ ]
}
- },
- "mark": {
- "type": "bar"
- },
+ ],
"width": "container"
}
@@ -309,9 +1106,13 @@
{
"$schema": "https://vega.github.io/schema/vega-lite/v5.20.1.json",
"config": {
+ "axis": {
+ "grid": false
+ },
"view": {
"continuousHeight": 300,
- "continuousWidth": 300
+ "continuousWidth": 300,
+ "stroke": null
}
},
"data": {
@@ -330,56 +1131,177 @@
}
]
},
- "encoding": {
- "x": {
- "field": "count",
- "type": "quantitative"
- },
- "y": {
- "field": "some_column",
- "sort": "-x",
- "type": "nominal"
- }
- },
- "mark": {
- "type": "bar"
- },
- "title": "Top 10 some_column",
- "transform": [
+ "layer": [
{
- "aggregate": [
+ "encoding": {
+ "tooltip": [
+ {
+ "field": "some_column",
+ "type": "nominal"
+ },
+ {
+ "field": "count",
+ "format": ",.0f",
+ "title": "Number of records",
+ "type": "quantitative"
+ }
+ ],
+ "x": {
+ "field": "count",
+ "title": "Number of records",
+ "type": "quantitative"
+ },
+ "y": {
+ "axis": {
+ "title": null
+ },
+ "field": "some_column",
+ "sort": "-x",
+ "type": "nominal"
+ }
+ },
+ "mark": {
+ "color": "#1C7361",
+ "type": "bar"
+ },
+ "transform": [
+ {
+ "aggregate": [
+ {
+ "as": "count",
+ "op": "count"
+ }
+ ],
+ "groupby": [
+ "some_column"
+ ]
+ },
+ {
+ "sort": [
+ {
+ "field": "count",
+ "order": "descending"
+ },
+ {
+ "field": "some_column",
+ "order": "ascending"
+ }
+ ],
+ "window": [
+ {
+ "as": "rank",
+ "field": "",
+ "op": "rank"
+ }
+ ]
+ },
{
- "as": "count",
- "op": "count"
+ "joinaggregate": [
+ {
+ "as": "total_count",
+ "field": "count",
+ "op": "sum"
+ }
+ ]
+ },
+ {
+ "as": "percentage",
+ "calculate": "datum.count / datum.total_count"
+ },
+ {
+ "filter": "(datum.rank <= 10)"
}
- ],
- "groupby": [
- "some_column"
]
},
{
- "sort": [
- {
+ "encoding": {
+ "text": {
+ "field": "percentage",
+ "format": ".2%",
+ "type": "quantitative"
+ },
+ "tooltip": [
+ {
+ "field": "some_column",
+ "type": "nominal"
+ },
+ {
+ "field": "count",
+ "format": ",.0f",
+ "title": "Number of records",
+ "type": "quantitative"
+ }
+ ],
+ "x": {
"field": "count",
- "order": "descending"
+ "title": "Number of records",
+ "type": "quantitative"
},
- {
+ "y": {
+ "axis": {
+ "title": null
+ },
"field": "some_column",
- "order": "ascending"
+ "sort": "-x",
+ "type": "nominal"
}
- ],
- "window": [
+ },
+ "mark": {
+ "align": "left",
+ "dx": 3,
+ "type": "text"
+ },
+ "transform": [
+ {
+ "aggregate": [
+ {
+ "as": "count",
+ "op": "count"
+ }
+ ],
+ "groupby": [
+ "some_column"
+ ]
+ },
+ {
+ "sort": [
+ {
+ "field": "count",
+ "order": "descending"
+ },
+ {
+ "field": "some_column",
+ "order": "ascending"
+ }
+ ],
+ "window": [
+ {
+ "as": "rank",
+ "field": "",
+ "op": "rank"
+ }
+ ]
+ },
+ {
+ "joinaggregate": [
+ {
+ "as": "total_count",
+ "field": "count",
+ "op": "sum"
+ }
+ ]
+ },
{
- "as": "rank",
- "field": "",
- "op": "rank"
+ "as": "percentage",
+ "calculate": "datum.count / datum.total_count"
+ },
+ {
+ "filter": "(datum.rank <= 10)"
}
]
- },
- {
- "filter": "(datum.rank <= 10)"
}
],
+ "title": "Top 10 some_column",
"width": "container"
}
@@ -389,7 +1311,8 @@
"config": {
"view": {
"continuousHeight": 300,
- "continuousWidth": 300
+ "continuousWidth": 300,
+ "stroke": null
}
},
"data": {
@@ -409,16 +1332,29 @@
]
},
"encoding": {
+ "tooltip": [
+ {
+ "field": "some_column",
+ "type": "nominal"
+ },
+ {
+ "aggregate": "count",
+ "title": "Number of records",
+ "type": "quantitative"
+ }
+ ],
"x": {
"field": "some_column",
"type": "nominal"
},
"y": {
"aggregate": "count",
+ "title": "{NUM_RECORDS}",
"type": "quantitative"
}
},
"mark": {
+ "color": "#1C7361",
"type": "bar"
},
"width": "container"
diff --git a/tests/_data/snapshots/charts_json_bad_data.txt b/tests/_data/snapshots/charts_json_bad_data.txt
index 930dcd26d8..8d3e8469ba 100644
--- a/tests/_data/snapshots/charts_json_bad_data.txt
+++ b/tests/_data/snapshots/charts_json_bad_data.txt
@@ -1,9 +1,13 @@
{
"$schema": "https://vega.github.io/schema/vega-lite/v5.20.1.json",
"config": {
+ "axis": {
+ "grid": false
+ },
"view": {
"continuousHeight": 300,
- "continuousWidth": 300
+ "continuousWidth": 300,
+ "stroke": null
}
},
"data": {
@@ -22,18 +26,169 @@
}
]
},
- "encoding": {
- "x": {
- "aggregate": "count",
- "type": "quantitative"
+ "layer": [
+ {
+ "encoding": {
+ "tooltip": [
+ {
+ "field": "some\\[0\\]really\\.bad\\:column",
+ "type": "nominal"
+ },
+ {
+ "field": "count",
+ "format": ",.0f",
+ "title": "Number of records",
+ "type": "quantitative"
+ }
+ ],
+ "x": {
+ "field": "count",
+ "title": "Number of records",
+ "type": "quantitative"
+ },
+ "y": {
+ "axis": {
+ "title": null
+ },
+ "field": "some\\[0\\]really\\.bad\\:column",
+ "sort": "-x",
+ "type": "nominal"
+ }
+ },
+ "mark": {
+ "color": "#1C7361",
+ "type": "bar"
+ },
+ "transform": [
+ {
+ "aggregate": [
+ {
+ "as": "count",
+ "op": "count"
+ }
+ ],
+ "groupby": [
+ "some\\[0\\]really\\.bad\\:column"
+ ]
+ },
+ {
+ "sort": [
+ {
+ "field": "count",
+ "order": "descending"
+ },
+ {
+ "field": "some\\[0\\]really\\.bad\\:column",
+ "order": "ascending"
+ }
+ ],
+ "window": [
+ {
+ "as": "rank",
+ "field": "",
+ "op": "rank"
+ }
+ ]
+ },
+ {
+ "joinaggregate": [
+ {
+ "as": "total_count",
+ "field": "count",
+ "op": "sum"
+ }
+ ]
+ },
+ {
+ "as": "percentage",
+ "calculate": "datum.count / datum.total_count"
+ }
+ ]
},
- "y": {
- "field": "some\\[0\\]really\\.bad\\:column",
- "type": "nominal"
+ {
+ "encoding": {
+ "text": {
+ "field": "percentage",
+ "format": ".2%",
+ "type": "quantitative"
+ },
+ "tooltip": [
+ {
+ "field": "some\\[0\\]really\\.bad\\:column",
+ "type": "nominal"
+ },
+ {
+ "field": "count",
+ "format": ",.0f",
+ "title": "Number of records",
+ "type": "quantitative"
+ }
+ ],
+ "x": {
+ "field": "count",
+ "title": "Number of records",
+ "type": "quantitative"
+ },
+ "y": {
+ "axis": {
+ "title": null
+ },
+ "field": "some\\[0\\]really\\.bad\\:column",
+ "sort": "-x",
+ "type": "nominal"
+ }
+ },
+ "mark": {
+ "align": "left",
+ "dx": 3,
+ "type": "text"
+ },
+ "transform": [
+ {
+ "aggregate": [
+ {
+ "as": "count",
+ "op": "count"
+ }
+ ],
+ "groupby": [
+ "some\\[0\\]really\\.bad\\:column"
+ ]
+ },
+ {
+ "sort": [
+ {
+ "field": "count",
+ "order": "descending"
+ },
+ {
+ "field": "some\\[0\\]really\\.bad\\:column",
+ "order": "ascending"
+ }
+ ],
+ "window": [
+ {
+ "as": "rank",
+ "field": "",
+ "op": "rank"
+ }
+ ]
+ },
+ {
+ "joinaggregate": [
+ {
+ "as": "total_count",
+ "field": "count",
+ "op": "sum"
+ }
+ ]
+ },
+ {
+ "as": "percentage",
+ "calculate": "datum.count / datum.total_count"
+ }
+ ]
}
- },
- "mark": {
- "type": "bar"
- },
+ ],
"width": "container"
}
\ No newline at end of file
diff --git a/tests/_data/snapshots/column_preview_bool_chart_code.txt b/tests/_data/snapshots/column_preview_bool_chart_code.txt
index bcca6c4606..792172a7c8 100644
--- a/tests/_data/snapshots/column_preview_bool_chart_code.txt
+++ b/tests/_data/snapshots/column_preview_bool_chart_code.txt
@@ -1,10 +1,26 @@
-_chart = (
+_base = (
alt.Chart(table)
- .mark_bar()
+ .transform_aggregate(count="count()", groupby=["bool_col"])
+ .transform_joinaggregate(total="sum(count)")
+ .transform_calculate(percentage="datum.count / datum.total")
.encode(
- x=alt.X("bool_col", type="nominal"),
- y=alt.Y("count()", type="quantitative"),
+ theta=alt.Theta(
+ field="count",
+ type="quantitative",
+ stack=True,
+ ),
+ color=alt.Color("bool_col:N"),
+ tooltip=[
+ alt.Tooltip("bool_col:N", title="bool_col"),
+ alt.Tooltip("count:Q", title="Number of records", format=",.0f"),
+ ],
)
- .properties(width="container")
)
+
+_pie = _base.mark_arc(outerRadius=85)
+_text = _base.mark_text(radius=100, size=13).encode(
+ text=alt.Text("percentage:Q", format=".2%"),
+)
+
+_chart = (_pie + _text).properties(width="container").configure_view(stroke=None)
_chart
\ No newline at end of file
diff --git a/tests/_data/snapshots/column_preview_bool_chart_spec.txt b/tests/_data/snapshots/column_preview_bool_chart_spec.txt
index b415b85e34..b2f8a26e97 100644
--- a/tests/_data/snapshots/column_preview_bool_chart_spec.txt
+++ b/tests/_data/snapshots/column_preview_bool_chart_spec.txt
@@ -12,18 +12,137 @@
},
"url": "data:text/csv;base64,Ym9vbF9jb2wKVHJ1ZQpGYWxzZQpUcnVlCg=="
},
- "encoding": {
- "x": {
- "field": "bool_col",
- "type": "nominal"
+ "layer": [
+ {
+ "encoding": {
+ "color": {
+ "field": "bool_col",
+ "scale": {
+ "range": [
+ "#99c99c",
+ "#1C7361"
+ ]
+ },
+ "type": "nominal"
+ },
+ "theta": {
+ "field": "count",
+ "stack": true,
+ "type": "quantitative"
+ },
+ "tooltip": [
+ {
+ "field": "bool_col",
+ "title": "bool_col",
+ "type": "nominal"
+ },
+ {
+ "field": "count",
+ "format": ",.0f",
+ "title": "Number of records",
+ "type": "quantitative"
+ }
+ ]
+ },
+ "mark": {
+ "outerRadius": 85,
+ "type": "arc"
+ },
+ "transform": [
+ {
+ "aggregate": [
+ {
+ "as": "count",
+ "op": "count"
+ }
+ ],
+ "groupby": [
+ "bool_col"
+ ]
+ },
+ {
+ "joinaggregate": [
+ {
+ "as": "total",
+ "field": "count",
+ "op": "sum"
+ }
+ ]
+ },
+ {
+ "as": "percentage",
+ "calculate": "datum.count / datum.total"
+ }
+ ]
},
- "y": {
- "aggregate": "count",
- "type": "quantitative"
+ {
+ "encoding": {
+ "color": {
+ "field": "bool_col",
+ "scale": {
+ "range": [
+ "#99c99c",
+ "#1C7361"
+ ]
+ },
+ "type": "nominal"
+ },
+ "text": {
+ "field": "percentage",
+ "format": ".2%",
+ "type": "quantitative"
+ },
+ "theta": {
+ "field": "count",
+ "stack": true,
+ "type": "quantitative"
+ },
+ "tooltip": [
+ {
+ "field": "bool_col",
+ "title": "bool_col",
+ "type": "nominal"
+ },
+ {
+ "field": "count",
+ "format": ",.0f",
+ "title": "Number of records",
+ "type": "quantitative"
+ }
+ ]
+ },
+ "mark": {
+ "radius": 100,
+ "size": 13,
+ "type": "text"
+ },
+ "transform": [
+ {
+ "aggregate": [
+ {
+ "as": "count",
+ "op": "count"
+ }
+ ],
+ "groupby": [
+ "bool_col"
+ ]
+ },
+ {
+ "joinaggregate": [
+ {
+ "as": "total",
+ "field": "count",
+ "op": "sum"
+ }
+ ]
+ },
+ {
+ "as": "percentage",
+ "calculate": "datum.count / datum.total"
+ }
+ ]
}
- },
- "mark": {
- "type": "bar"
- },
+ ],
"width": "container"
}
\ No newline at end of file
diff --git a/tests/_data/snapshots/column_preview_bool_chart_spec_with_vegafusion.txt b/tests/_data/snapshots/column_preview_bool_chart_spec_with_vegafusion.txt
index ba9b633f21..01d5b95431 100644
--- a/tests/_data/snapshots/column_preview_bool_chart_spec_with_vegafusion.txt
+++ b/tests/_data/snapshots/column_preview_bool_chart_spec_with_vegafusion.txt
@@ -4,62 +4,49 @@
"contains": "padding",
"type": "fit-x"
},
- "axes": [
+ "background": "white",
+ "data": [
{
- "aria": false,
- "domain": false,
- "grid": true,
- "gridScale": "x",
- "labels": false,
- "maxExtent": 0,
- "minExtent": 0,
- "orient": "left",
- "scale": "y",
- "tickCount": {
- "signal": "ceil(height/40)"
- },
- "ticks": false,
- "zindex": 0
+ "name": "source_0"
},
{
- "grid": false,
- "labelAlign": "right",
- "labelAngle": 270,
- "labelBaseline": "middle",
- "orient": "bottom",
- "scale": "x",
- "title": "bool_col",
- "zindex": 0
+ "name": "data_0",
+ "values": [
+ {
+ "bool_col": true,
+ "count": 2,
+ "count_end": 3.0,
+ "count_start": 1.0,
+ "percentage": 0.6666666666666666
+ },
+ {
+ "bool_col": false,
+ "count": 1,
+ "count_end": 1.0,
+ "count_start": 0.0,
+ "percentage": 0.3333333333333333
+ }
+ ]
},
{
- "grid": false,
- "labelOverlap": true,
- "orient": "left",
- "scale": "y",
- "tickCount": {
- "signal": "ceil(height/40)"
- },
- "title": "Count of Records",
- "zindex": 0
- }
- ],
- "background": "white",
- "data": [
- {
- "name": "source_0",
+ "name": "data_1",
"values": [
{
- "__count": 2,
- "bool_col": true
+ "bool_col": true,
+ "count": 2,
+ "count_end": 3.0,
+ "count_start": 1.0
},
{
- "__count": 1,
- "bool_col": false
+ "bool_col": false,
+ "count": 1,
+ "count_end": 1.0,
+ "count_start": 0.0
}
]
},
{
- "name": "source_0_x_domain_bool_col",
+ "name": "data_1_color_domain_bool_col_0",
"values": [
{
"bool_col": true
@@ -70,88 +57,168 @@
]
},
{
- "name": "source_0_y_domain___count",
+ "name": "data_0_color_domain_bool_col_1",
"values": [
{
- "max": 2,
- "min": 1
+ "bool_col": true
+ },
+ {
+ "bool_col": false
}
]
}
],
"height": 300,
+ "legends": [
+ {
+ "fill": "color",
+ "symbolType": "circle",
+ "title": "bool_col"
+ }
+ ],
"marks": [
{
"encode": {
"update": {
+ "endAngle": {
+ "field": "count_start",
+ "scale": "theta"
+ },
"fill": {
- "value": "#4c78a8"
+ "field": "bool_col",
+ "scale": "color"
+ },
+ "innerRadius": {
+ "value": 0
+ },
+ "outerRadius": {
+ "value": 85
+ },
+ "startAngle": {
+ "field": "count_end",
+ "scale": "theta"
},
- "width": {
- "signal": "max(0.25, bandwidth('x'))"
+ "tooltip": {
+ "signal": "{\"bool_col\": isValid(datum[\"bool_col\"]) ? datum[\"bool_col\"] : \"\"+datum[\"bool_col\"], \"Number of records\": format(datum[\"count\"], \",.0f\")}"
},
"x": {
- "field": "bool_col",
- "scale": "x"
+ "mult": 0.5,
+ "signal": "width"
},
"y": {
- "field": "__count",
- "scale": "y"
+ "mult": 0.5,
+ "signal": "height"
+ }
+ }
+ },
+ "from": {
+ "data": "data_1"
+ },
+ "name": "layer_0_marks",
+ "style": [
+ "arc"
+ ],
+ "type": "arc"
+ },
+ {
+ "encode": {
+ "update": {
+ "align": {
+ "value": "center"
},
- "y2": {
- "scale": "y",
- "value": 0
+ "baseline": {
+ "value": "middle"
+ },
+ "fill": {
+ "field": "bool_col",
+ "scale": "color"
+ },
+ "fontSize": {
+ "value": 13
+ },
+ "radius": {
+ "value": 100
+ },
+ "text": {
+ "signal": "format(datum[\"percentage\"], \".2%\")"
+ },
+ "theta": {
+ "signal": "scale(\"theta\", 0.5 * datum[\"count_start\"] + 0.5 * datum[\"count_end\"])"
+ },
+ "tooltip": {
+ "signal": "{\"bool_col\": isValid(datum[\"bool_col\"]) ? datum[\"bool_col\"] : \"\"+datum[\"bool_col\"], \"Number of records\": format(datum[\"count\"], \",.0f\")}"
+ },
+ "x": {
+ "mult": 0.5,
+ "signal": "width"
+ },
+ "y": {
+ "mult": 0.5,
+ "signal": "height"
}
}
},
"from": {
- "data": "source_0"
+ "data": "data_0"
},
- "name": "marks",
+ "name": "layer_1_marks",
"style": [
- "bar"
+ "text"
],
- "type": "rect"
+ "type": "text"
}
],
"padding": 5,
"scales": [
{
"domain": {
- "data": "source_0_x_domain_bool_col",
- "field": "bool_col",
- "sort": true
+ "fields": [
+ {
+ "data": "data_1",
+ "field": "count_start"
+ },
+ {
+ "data": "data_1",
+ "field": "count_end"
+ },
+ {
+ "data": "data_0",
+ "field": "count_start"
+ },
+ {
+ "data": "data_0",
+ "field": "count_end"
+ }
+ ]
},
- "name": "x",
- "paddingInner": 0.1,
- "paddingOuter": 0.05,
+ "name": "theta",
"range": [
0,
- {
- "signal": "width"
- }
+ 6.283185307179586
],
- "type": "band"
+ "type": "linear",
+ "zero": true
},
{
- "domain": [
- {
- "signal": "(data(\"source_0_y_domain___count\")[0] || {}).min"
- },
- {
- "signal": "(data(\"source_0_y_domain___count\")[0] || {}).max"
- }
- ],
- "name": "y",
- "nice": true,
+ "domain": {
+ "fields": [
+ {
+ "data": "data_1_color_domain_bool_col_0",
+ "field": "bool_col"
+ },
+ {
+ "data": "data_0_color_domain_bool_col_1",
+ "field": "bool_col"
+ }
+ ],
+ "sort": true
+ },
+ "name": "color",
"range": [
- {
- "signal": "height"
- },
- 0
+ "#99c99c",
+ "#1C7361"
],
- "type": "linear",
- "zero": true
+ "type": "ordinal"
}
],
"signals": [
@@ -166,5 +233,5 @@
]
}
],
- "style": "cell"
+ "style": "view"
}
\ No newline at end of file
diff --git a/tests/_data/snapshots/column_preview_categorical_chart_code.txt b/tests/_data/snapshots/column_preview_categorical_chart_code.txt
index 2c416729b2..0f01d35606 100644
--- a/tests/_data/snapshots/column_preview_categorical_chart_code.txt
+++ b/tests/_data/snapshots/column_preview_categorical_chart_code.txt
@@ -1,10 +1,29 @@
_chart = (
alt.Chart(table)
.mark_bar()
+ .transform_aggregate(count="count()", groupby=["category_col"])
+ .transform_window(
+ rank="rank()",
+ sort=[
+ alt.SortField("count", order="descending"),
+ alt.SortField("category_col", order="ascending"),
+ ],
+ )
+ .transform_filter(alt.datum.rank <= 10)
.encode(
- y=alt.Y("category_col", type="nominal"),
- x=alt.X("count()", type="quantitative"),
+ y=alt.Y(
+ "category_col:N",
+ sort="-x",
+ axis=alt.Axis(title=None),
+ ),
+ x=alt.X("count:Q", title="Number of records"),
+ tooltip=[
+ alt.Tooltip("category_col:N"),
+ alt.Tooltip("count:Q", format=",.0f", title="Number of records"),
+ ],
)
.properties(width="container")
+ .configure_view(stroke=None)
+ .configure_axis(grid=False)
)
_chart
\ No newline at end of file
diff --git a/tests/_data/snapshots/column_preview_categorical_chart_spec.txt b/tests/_data/snapshots/column_preview_categorical_chart_spec.txt
index c36ef1a766..a7f2bcc9c5 100644
--- a/tests/_data/snapshots/column_preview_categorical_chart_spec.txt
+++ b/tests/_data/snapshots/column_preview_categorical_chart_spec.txt
@@ -1,9 +1,13 @@
{
"$schema": "https://vega.github.io/schema/vega-lite/v5.20.1.json",
"config": {
+ "axis": {
+ "grid": false
+ },
"view": {
"continuousHeight": 300,
- "continuousWidth": 300
+ "continuousWidth": 300,
+ "stroke": null
}
},
"data": {
@@ -12,18 +16,169 @@
},
"url": "data:text/csv;base64,Y2F0ZWdvcnlfY29sCmNhdDEKY2F0MgpjYXQxCg=="
},
- "encoding": {
- "x": {
- "aggregate": "count",
- "type": "quantitative"
+ "layer": [
+ {
+ "encoding": {
+ "tooltip": [
+ {
+ "field": "category_col",
+ "type": "nominal"
+ },
+ {
+ "field": "count",
+ "format": ",.0f",
+ "title": "Number of records",
+ "type": "quantitative"
+ }
+ ],
+ "x": {
+ "field": "count",
+ "title": "Number of records",
+ "type": "quantitative"
+ },
+ "y": {
+ "axis": {
+ "title": null
+ },
+ "field": "category_col",
+ "sort": "-x",
+ "type": "nominal"
+ }
+ },
+ "mark": {
+ "color": "#1C7361",
+ "type": "bar"
+ },
+ "transform": [
+ {
+ "aggregate": [
+ {
+ "as": "count",
+ "op": "count"
+ }
+ ],
+ "groupby": [
+ "category_col"
+ ]
+ },
+ {
+ "sort": [
+ {
+ "field": "count",
+ "order": "descending"
+ },
+ {
+ "field": "category_col",
+ "order": "ascending"
+ }
+ ],
+ "window": [
+ {
+ "as": "rank",
+ "field": "",
+ "op": "rank"
+ }
+ ]
+ },
+ {
+ "joinaggregate": [
+ {
+ "as": "total_count",
+ "field": "count",
+ "op": "sum"
+ }
+ ]
+ },
+ {
+ "as": "percentage",
+ "calculate": "datum.count / datum.total_count"
+ }
+ ]
},
- "y": {
- "field": "category_col",
- "type": "nominal"
+ {
+ "encoding": {
+ "text": {
+ "field": "percentage",
+ "format": ".2%",
+ "type": "quantitative"
+ },
+ "tooltip": [
+ {
+ "field": "category_col",
+ "type": "nominal"
+ },
+ {
+ "field": "count",
+ "format": ",.0f",
+ "title": "Number of records",
+ "type": "quantitative"
+ }
+ ],
+ "x": {
+ "field": "count",
+ "title": "Number of records",
+ "type": "quantitative"
+ },
+ "y": {
+ "axis": {
+ "title": null
+ },
+ "field": "category_col",
+ "sort": "-x",
+ "type": "nominal"
+ }
+ },
+ "mark": {
+ "align": "left",
+ "dx": 3,
+ "type": "text"
+ },
+ "transform": [
+ {
+ "aggregate": [
+ {
+ "as": "count",
+ "op": "count"
+ }
+ ],
+ "groupby": [
+ "category_col"
+ ]
+ },
+ {
+ "sort": [
+ {
+ "field": "count",
+ "order": "descending"
+ },
+ {
+ "field": "category_col",
+ "order": "ascending"
+ }
+ ],
+ "window": [
+ {
+ "as": "rank",
+ "field": "",
+ "op": "rank"
+ }
+ ]
+ },
+ {
+ "joinaggregate": [
+ {
+ "as": "total_count",
+ "field": "count",
+ "op": "sum"
+ }
+ ]
+ },
+ {
+ "as": "percentage",
+ "calculate": "datum.count / datum.total_count"
+ }
+ ]
}
- },
- "mark": {
- "type": "bar"
- },
+ ],
"width": "container"
}
\ No newline at end of file
diff --git a/tests/_data/snapshots/column_preview_categorical_chart_spec_with_vegafusion.txt b/tests/_data/snapshots/column_preview_categorical_chart_spec_with_vegafusion.txt
index 01a1d01e92..769b296305 100644
--- a/tests/_data/snapshots/column_preview_categorical_chart_spec_with_vegafusion.txt
+++ b/tests/_data/snapshots/column_preview_categorical_chart_spec_with_vegafusion.txt
@@ -5,22 +5,6 @@
"type": "fit-x"
},
"axes": [
- {
- "aria": false,
- "domain": false,
- "grid": true,
- "gridScale": "y",
- "labels": false,
- "maxExtent": 0,
- "minExtent": 0,
- "orient": "bottom",
- "scale": "x",
- "tickCount": {
- "signal": "ceil(width/40)"
- },
- "ticks": false,
- "zindex": 0
- },
{
"grid": false,
"labelFlush": true,
@@ -30,38 +14,60 @@
"tickCount": {
"signal": "ceil(width/40)"
},
- "title": "Count of Records",
+ "title": "Number of records",
"zindex": 0
},
{
"grid": false,
"orient": "left",
"scale": "y",
- "title": "category_col",
"zindex": 0
}
],
"background": "white",
+ "config": {
+ "axis": {
+ "grid": false
+ },
+ "style": {
+ "cell": {
+ "stroke": null
+ }
+ }
+ },
"data": [
{
- "name": "source_0",
+ "name": "source_0"
+ },
+ {
+ "name": "data_1",
"values": [
{
- "__count": 2,
- "category_col": "cat1"
+ "category_col": "cat1",
+ "count": 2,
+ "percentage": 0.6666666666666666
},
{
- "__count": 1,
- "category_col": "cat2"
+ "category_col": "cat2",
+ "count": 1,
+ "percentage": 0.3333333333333333
}
]
},
{
- "name": "source_0_x_domain___count",
+ "name": "data_2",
"values": [
{
- "max": 2,
- "min": 1
+ "category_col": "cat1",
+ "count": 2,
+ "count_end": 2.0,
+ "count_start": 0.0
+ },
+ {
+ "category_col": "cat2",
+ "count": 1,
+ "count_end": 1.0,
+ "count_start": 0.0
}
]
},
@@ -69,10 +75,12 @@
"name": "source_0_y_domain_category_col",
"values": [
{
- "category_col": "cat1"
+ "category_col": "cat1",
+ "sort_field": 2
},
{
- "category_col": "cat2"
+ "category_col": "cat2",
+ "sort_field": 1
}
]
}
@@ -82,18 +90,21 @@
"encode": {
"update": {
"fill": {
- "value": "#4c78a8"
+ "value": "#1C7361"
},
"height": {
"signal": "max(0.25, bandwidth('y'))"
},
+ "tooltip": {
+ "signal": "{\"category_col\": isValid(datum[\"category_col\"]) ? datum[\"category_col\"] : \"\"+datum[\"category_col\"], \"Number of records\": format(datum[\"count\"], \",.0f\")}"
+ },
"x": {
- "field": "__count",
+ "field": "count_end",
"scale": "x"
},
"x2": {
- "scale": "x",
- "value": 0
+ "field": "count_start",
+ "scale": "x"
},
"y": {
"field": "category_col",
@@ -102,26 +113,75 @@
}
},
"from": {
- "data": "source_0"
+ "data": "data_2"
},
- "name": "marks",
+ "name": "layer_0_marks",
"style": [
"bar"
],
"type": "rect"
+ },
+ {
+ "encode": {
+ "update": {
+ "align": {
+ "value": "left"
+ },
+ "baseline": {
+ "value": "middle"
+ },
+ "dx": {
+ "value": 3
+ },
+ "fill": {
+ "value": "black"
+ },
+ "text": {
+ "signal": "format(datum[\"percentage\"], \".2%\")"
+ },
+ "tooltip": {
+ "signal": "{\"category_col\": isValid(datum[\"category_col\"]) ? datum[\"category_col\"] : \"\"+datum[\"category_col\"], \"Number of records\": format(datum[\"count\"], \",.0f\")}"
+ },
+ "x": {
+ "field": "count",
+ "scale": "x"
+ },
+ "y": {
+ "band": 0.5,
+ "field": "category_col",
+ "scale": "y"
+ }
+ }
+ },
+ "from": {
+ "data": "data_1"
+ },
+ "name": "layer_1_marks",
+ "style": [
+ "text"
+ ],
+ "type": "text"
}
],
"padding": 5,
"scales": [
{
- "domain": [
- {
- "signal": "(data(\"source_0_x_domain___count\")[0] || {}).min"
- },
- {
- "signal": "(data(\"source_0_x_domain___count\")[0] || {}).max"
- }
- ],
+ "domain": {
+ "fields": [
+ {
+ "data": "data_2",
+ "field": "count_start"
+ },
+ {
+ "data": "data_2",
+ "field": "count_end"
+ },
+ {
+ "data": "data_1",
+ "field": "count"
+ }
+ ]
+ },
"name": "x",
"nice": true,
"range": [
@@ -137,7 +197,11 @@
"domain": {
"data": "source_0_y_domain_category_col",
"field": "category_col",
- "sort": true
+ "sort": {
+ "field": "sort_field",
+ "op": "max",
+ "order": "descending"
+ }
},
"name": "y",
"paddingInner": 0.1,
diff --git a/tests/_data/snapshots/column_preview_date_chart_code.txt b/tests/_data/snapshots/column_preview_date_chart_code.txt
index 1aa5bcfb46..386b329fa1 100644
--- a/tests/_data/snapshots/column_preview_date_chart_code.txt
+++ b/tests/_data/snapshots/column_preview_date_chart_code.txt
@@ -1,15 +1,15 @@
_chart = (
alt.Chart(table)
- .mark_bar()
+ .transform_filter(f"datum.date_col != null")
+ .transform_timeunit(as_="_date_col", field="date_col", timeUnit="yearmonthdate")
+ .mark_area()
.encode(
- x=alt.X(
- "date_col",
- type="temporal",
- bin=alt.Bin(maxbins=20),
- axis=alt.Axis(format="%Y-%m-%d")
- ),
- y=alt.Y("count()", type="quantitative"),
- )
- .properties(width="container")
+ x=alt.X("_date_col:T", title="date_col"),
+ y=alt.Y("count():Q", title="Number of records"),
+ tooltip=[
+ alt.Tooltip("_date_col:T", title="date_col", timeUnit="yearmonthdate"),
+ alt.Tooltip("count():Q", title="Number of records", format=",.0f")
+ ]
+ ).properties(width="container").configure_view(stroke=None)
)
_chart
\ No newline at end of file
diff --git a/tests/_data/snapshots/column_preview_duckdb_bool_chart_spec.txt b/tests/_data/snapshots/column_preview_duckdb_bool_chart_spec.txt
index 136e5a9480..90a0a340de 100644
--- a/tests/_data/snapshots/column_preview_duckdb_bool_chart_spec.txt
+++ b/tests/_data/snapshots/column_preview_duckdb_bool_chart_spec.txt
@@ -4,65 +4,52 @@
"contains": "padding",
"type": "fit-x"
},
- "axes": [
+ "background": "white",
+ "data": [
{
- "aria": false,
- "domain": false,
- "grid": true,
- "gridScale": "x",
- "labels": false,
- "maxExtent": 0,
- "minExtent": 0,
- "orient": "left",
- "scale": "y",
- "tickCount": {
- "signal": "ceil(height/40)"
- },
- "ticks": false,
- "zindex": 0
+ "name": "data-834341051d0a090d8e3ab71fa64b81b9"
},
{
- "grid": false,
- "labelAlign": "right",
- "labelAngle": 270,
- "labelBaseline": "middle",
- "orient": "bottom",
- "scale": "x",
- "title": "bool_col",
- "zindex": 0
+ "name": "data_0"
},
{
- "grid": false,
- "labelOverlap": true,
- "orient": "left",
- "scale": "y",
- "tickCount": {
- "signal": "ceil(height/40)"
- },
- "title": "Count of Records",
- "zindex": 0
- }
- ],
- "background": "white",
- "data": [
- {
- "name": "data-834341051d0a090d8e3ab71fa64b81b9"
+ "name": "data_1",
+ "values": [
+ {
+ "bool_col": true,
+ "count": 50,
+ "count_end": 100.0,
+ "count_start": 50.0,
+ "percentage": 0.5
+ },
+ {
+ "bool_col": false,
+ "count": 50,
+ "count_end": 50.0,
+ "count_start": 0.0,
+ "percentage": 0.5
+ }
+ ]
},
{
- "name": "data_0",
+ "name": "data_2",
"values": [
{
- "__count": 50,
- "bool_col": true
+ "bool_col": true,
+ "count": 50,
+ "count_end": 100.0,
+ "count_start": 50.0
},
{
- "__count": 50,
- "bool_col": false
+ "bool_col": false,
+ "count": 50,
+ "count_end": 50.0,
+ "count_start": 0.0
}
]
},
{
- "name": "data_0_x_domain_bool_col",
+ "name": "data_2_color_domain_bool_col_0",
"values": [
{
"bool_col": true
@@ -73,88 +60,168 @@
]
},
{
- "name": "data_0_y_domain___count",
+ "name": "data_1_color_domain_bool_col_1",
"values": [
{
- "max": 50,
- "min": 50
+ "bool_col": true
+ },
+ {
+ "bool_col": false
}
]
}
],
"height": 300,
+ "legends": [
+ {
+ "fill": "color",
+ "symbolType": "circle",
+ "title": "bool_col"
+ }
+ ],
"marks": [
{
"encode": {
"update": {
+ "endAngle": {
+ "field": "count_start",
+ "scale": "theta"
+ },
"fill": {
- "value": "#4c78a8"
+ "field": "bool_col",
+ "scale": "color"
+ },
+ "innerRadius": {
+ "value": 0
},
- "width": {
- "signal": "max(0.25, bandwidth('x'))"
+ "outerRadius": {
+ "value": 85
+ },
+ "startAngle": {
+ "field": "count_end",
+ "scale": "theta"
+ },
+ "tooltip": {
+ "signal": "{\"bool_col\": isValid(datum[\"bool_col\"]) ? datum[\"bool_col\"] : \"\"+datum[\"bool_col\"], \"Number of records\": format(datum[\"count\"], \",.0f\")}"
},
"x": {
- "field": "bool_col",
- "scale": "x"
+ "mult": 0.5,
+ "signal": "width"
},
"y": {
- "field": "__count",
- "scale": "y"
+ "mult": 0.5,
+ "signal": "height"
+ }
+ }
+ },
+ "from": {
+ "data": "data_2"
+ },
+ "name": "layer_0_marks",
+ "style": [
+ "arc"
+ ],
+ "type": "arc"
+ },
+ {
+ "encode": {
+ "update": {
+ "align": {
+ "value": "center"
},
- "y2": {
- "scale": "y",
- "value": 0
+ "baseline": {
+ "value": "middle"
+ },
+ "fill": {
+ "field": "bool_col",
+ "scale": "color"
+ },
+ "fontSize": {
+ "value": 13
+ },
+ "radius": {
+ "value": 100
+ },
+ "text": {
+ "signal": "format(datum[\"percentage\"], \".2%\")"
+ },
+ "theta": {
+ "signal": "scale(\"theta\", 0.5 * datum[\"count_start\"] + 0.5 * datum[\"count_end\"])"
+ },
+ "tooltip": {
+ "signal": "{\"bool_col\": isValid(datum[\"bool_col\"]) ? datum[\"bool_col\"] : \"\"+datum[\"bool_col\"], \"Number of records\": format(datum[\"count\"], \",.0f\")}"
+ },
+ "x": {
+ "mult": 0.5,
+ "signal": "width"
+ },
+ "y": {
+ "mult": 0.5,
+ "signal": "height"
}
}
},
"from": {
- "data": "data_0"
+ "data": "data_1"
},
- "name": "marks",
+ "name": "layer_1_marks",
"style": [
- "bar"
+ "text"
],
- "type": "rect"
+ "type": "text"
}
],
"padding": 5,
"scales": [
{
"domain": {
- "data": "data_0_x_domain_bool_col",
- "field": "bool_col",
- "sort": true
+ "fields": [
+ {
+ "data": "data_2",
+ "field": "count_start"
+ },
+ {
+ "data": "data_2",
+ "field": "count_end"
+ },
+ {
+ "data": "data_1",
+ "field": "count_start"
+ },
+ {
+ "data": "data_1",
+ "field": "count_end"
+ }
+ ]
},
- "name": "x",
- "paddingInner": 0.1,
- "paddingOuter": 0.05,
+ "name": "theta",
"range": [
0,
- {
- "signal": "width"
- }
+ 6.283185307179586
],
- "type": "band"
+ "type": "linear",
+ "zero": true
},
{
- "domain": [
- {
- "signal": "(data(\"data_0_y_domain___count\")[0] || {}).min"
- },
- {
- "signal": "(data(\"data_0_y_domain___count\")[0] || {}).max"
- }
- ],
- "name": "y",
- "nice": true,
+ "domain": {
+ "fields": [
+ {
+ "data": "data_2_color_domain_bool_col_0",
+ "field": "bool_col"
+ },
+ {
+ "data": "data_1_color_domain_bool_col_1",
+ "field": "bool_col"
+ }
+ ],
+ "sort": true
+ },
+ "name": "color",
"range": [
- {
- "signal": "height"
- },
- 0
+ "#99c99c",
+ "#1C7361"
],
- "type": "linear",
- "zero": true
+ "type": "ordinal"
}
],
"signals": [
@@ -169,5 +236,5 @@
]
}
],
- "style": "cell"
+ "style": "view"
}
\ No newline at end of file
diff --git a/tests/_data/snapshots/column_preview_duckdb_categorical_chart_spec.txt b/tests/_data/snapshots/column_preview_duckdb_categorical_chart_spec.txt
index 5030eff9e6..0c4fc5dcab 100644
--- a/tests/_data/snapshots/column_preview_duckdb_categorical_chart_spec.txt
+++ b/tests/_data/snapshots/column_preview_duckdb_categorical_chart_spec.txt
@@ -5,22 +5,6 @@
"type": "fit-x"
},
"axes": [
- {
- "aria": false,
- "domain": false,
- "grid": true,
- "gridScale": "y",
- "labels": false,
- "maxExtent": 0,
- "minExtent": 0,
- "orient": "bottom",
- "scale": "x",
- "tickCount": {
- "signal": "ceil(width/40)"
- },
- "ticks": false,
- "zindex": 0
- },
{
"grid": false,
"labelFlush": true,
@@ -30,18 +14,27 @@
"tickCount": {
"signal": "ceil(width/40)"
},
- "title": "count",
+ "title": "Number of records",
"zindex": 0
},
{
"grid": false,
"orient": "left",
"scale": "y",
- "title": "category",
"zindex": 0
}
],
"background": "white",
+ "config": {
+ "axis": {
+ "grid": false
+ },
+ "style": {
+ "cell": {
+ "stroke": null
+ }
+ }
+ },
"data": [
{
"name": "data-6f2678becc24b5ff9fbec3e85cf09cd0"
@@ -50,25 +43,54 @@
"name": "data_0"
},
{
- "name": "data_1",
+ "name": "data_2",
+ "values": [
+ {
+ "category": "A",
+ "count": 25,
+ "percentage": 0.25
+ },
+ {
+ "category": "B",
+ "count": 25,
+ "percentage": 0.25
+ },
+ {
+ "category": "C",
+ "count": 25,
+ "percentage": 0.25
+ },
+ {
+ "category": "D",
+ "count": 25,
+ "percentage": 0.25
+ }
+ ]
+ },
+ {
+ "name": "data_3",
"values": [
{
"category": "A",
+ "count": 25,
"count_end": 25.0,
"count_start": 0.0
},
{
"category": "B",
+ "count": 25,
"count_end": 25.0,
"count_start": 0.0
},
{
"category": "C",
+ "count": 25,
"count_end": 25.0,
"count_start": 0.0
},
{
"category": "D",
+ "count": 25,
"count_end": 25.0,
"count_start": 0.0
}
@@ -101,11 +123,14 @@
"encode": {
"update": {
"fill": {
- "value": "#4c78a8"
+ "value": "#1C7361"
},
"height": {
"signal": "max(0.25, bandwidth('y'))"
},
+ "tooltip": {
+ "signal": "{\"category\": isValid(datum[\"category\"]) ? datum[\"category\"] : \"\"+datum[\"category\"], \"Number of records\": format(datum[\"count\"], \",.0f\")}"
+ },
"x": {
"field": "count_end",
"scale": "x"
@@ -121,23 +146,73 @@
}
},
"from": {
- "data": "data_1"
+ "data": "data_3"
},
- "name": "marks",
+ "name": "layer_0_marks",
"style": [
"bar"
],
"type": "rect"
+ },
+ {
+ "encode": {
+ "update": {
+ "align": {
+ "value": "left"
+ },
+ "baseline": {
+ "value": "middle"
+ },
+ "dx": {
+ "value": 3
+ },
+ "fill": {
+ "value": "black"
+ },
+ "text": {
+ "signal": "format(datum[\"percentage\"], \".2%\")"
+ },
+ "tooltip": {
+ "signal": "{\"category\": isValid(datum[\"category\"]) ? datum[\"category\"] : \"\"+datum[\"category\"], \"Number of records\": format(datum[\"count\"], \",.0f\")}"
+ },
+ "x": {
+ "field": "count",
+ "scale": "x"
+ },
+ "y": {
+ "band": 0.5,
+ "field": "category",
+ "scale": "y"
+ }
+ }
+ },
+ "from": {
+ "data": "data_2"
+ },
+ "name": "layer_1_marks",
+ "style": [
+ "text"
+ ],
+ "type": "text"
}
],
"padding": 5,
"scales": [
{
"domain": {
- "data": "data_1",
"fields": [
- "count_start",
- "count_end"
+ {
+ "data": "data_3",
+ "field": "count_start"
+ },
+ {
+ "data": "data_3",
+ "field": "count_end"
+ },
+ {
+ "data": "data_2",
+ "field": "count"
+ }
]
},
"name": "x",
diff --git a/tests/_data/snapshots/column_preview_float_chart_code.txt b/tests/_data/snapshots/column_preview_float_chart_code.txt
index 517879cdd8..3c9731080e 100644
--- a/tests/_data/snapshots/column_preview_float_chart_code.txt
+++ b/tests/_data/snapshots/column_preview_float_chart_code.txt
@@ -2,9 +2,23 @@ _chart = (
alt.Chart(table)
.mark_bar()
.encode(
- x=alt.X("float_col", type="quantitative", bin=True),
- y=alt.Y("count()", type="quantitative"),
- )
- .properties(width="container")
+ x=alt.X("float_col", type="quantitative", bin=True, title="float_col"),
+ y=alt.Y("count()", type="quantitative", title="Number of records"),
+ tooltip=[
+ alt.Tooltip(
+ "float_col",
+ type="quantitative",
+ bin=True,
+ title="float_col",
+ format=",.2f",
+ ),
+ alt.Tooltip(
+ "count()",
+ type="quantitative",
+ format=",.0f",
+ title="Number of records",
+ ),
+ ],
+ ).properties(width="container").configure_view(stroke=None)
)
_chart
\ No newline at end of file
diff --git a/tests/_data/snapshots/column_preview_float_chart_spec.txt b/tests/_data/snapshots/column_preview_float_chart_spec.txt
index 04df1082e4..fe8797a4ff 100644
--- a/tests/_data/snapshots/column_preview_float_chart_spec.txt
+++ b/tests/_data/snapshots/column_preview_float_chart_spec.txt
@@ -3,7 +3,8 @@
"config": {
"view": {
"continuousHeight": 300,
- "continuousWidth": 300
+ "continuousWidth": 300,
+ "stroke": null
}
},
"data": {
@@ -13,17 +14,35 @@
"url": "data:text/csv;base64,ZmxvYXRfY29sCjEuMQoyLjIKMy4zCg=="
},
"encoding": {
+ "tooltip": [
+ {
+ "bin": true,
+ "field": "float_col",
+ "format": ",.2f",
+ "title": "float_col",
+ "type": "quantitative"
+ },
+ {
+ "aggregate": "count",
+ "format": ",.0f",
+ "title": "Number of records",
+ "type": "quantitative"
+ }
+ ],
"x": {
"bin": true,
"field": "float_col",
+ "title": "float_col",
"type": "quantitative"
},
"y": {
"aggregate": "count",
+ "title": "Number of records",
"type": "quantitative"
}
},
"mark": {
+ "color": "#1C7361",
"type": "bar"
},
"width": "container"
diff --git a/tests/_data/snapshots/column_preview_float_chart_spec_with_vegafusion.txt b/tests/_data/snapshots/column_preview_float_chart_spec_with_vegafusion.txt
index 6f0ef64826..8c34881973 100644
--- a/tests/_data/snapshots/column_preview_float_chart_spec_with_vegafusion.txt
+++ b/tests/_data/snapshots/column_preview_float_chart_spec_with_vegafusion.txt
@@ -30,7 +30,7 @@
"tickCount": {
"signal": "ceil(width/10)"
},
- "title": "float_col (binned)",
+ "title": "float_col",
"zindex": 0
},
{
@@ -41,11 +41,18 @@
"tickCount": {
"signal": "ceil(height/40)"
},
- "title": "Count of Records",
+ "title": "Number of records",
"zindex": 0
}
],
"background": "white",
+ "config": {
+ "style": {
+ "cell": {
+ "stroke": null
+ }
+ }
+ },
"data": [
{
"name": "source_0",
@@ -83,7 +90,10 @@
"encode": {
"update": {
"fill": {
- "value": "#4c78a8"
+ "value": "#1C7361"
+ },
+ "tooltip": {
+ "signal": "{\"float_col\": !isValid(datum[\"bin_maxbins_10_float_col\"]) || !isFinite(+datum[\"bin_maxbins_10_float_col\"]) ? \"null\" : format(datum[\"bin_maxbins_10_float_col\"], \",.2f\") + \" \u2013 \" + format(datum[\"bin_maxbins_10_float_col_end\"], \",.2f\"), \"Number of records\": format(datum[\"__count\"], \",.0f\")}"
},
"x": {
"field": "bin_maxbins_10_float_col_end",
diff --git a/tests/_data/snapshots/column_preview_int_chart_code.txt b/tests/_data/snapshots/column_preview_int_chart_code.txt
index 149f413dc0..e7088a1bd3 100644
--- a/tests/_data/snapshots/column_preview_int_chart_code.txt
+++ b/tests/_data/snapshots/column_preview_int_chart_code.txt
@@ -2,9 +2,22 @@ _chart = (
alt.Chart(table)
.mark_bar()
.encode(
- x=alt.X("A", type="quantitative", bin=True),
- y=alt.Y("count()", type="quantitative"),
- )
- .properties(width="container")
+ x=alt.X("A", type="quantitative", bin=True, title="A"),
+ y=alt.Y("count()", type="quantitative", title="Number of records"),
+ tooltip=[
+ alt.Tooltip(
+ "A",
+ type="quantitative",
+ bin=True,
+ title="A",
+ ),
+ alt.Tooltip(
+ "count()",
+ type="quantitative",
+ format=",.0f",
+ title="Number of records",
+ ),
+ ],
+ ).properties(width="container").configure_view(stroke=None)
)
_chart
\ No newline at end of file
diff --git a/tests/_data/snapshots/column_preview_int_chart_spec.txt b/tests/_data/snapshots/column_preview_int_chart_spec.txt
index f097a489d2..37da749eda 100644
--- a/tests/_data/snapshots/column_preview_int_chart_spec.txt
+++ b/tests/_data/snapshots/column_preview_int_chart_spec.txt
@@ -3,7 +3,8 @@
"config": {
"view": {
"continuousHeight": 300,
- "continuousWidth": 300
+ "continuousWidth": 300,
+ "stroke": null
}
},
"data": {
@@ -13,17 +14,34 @@
"url": "data:text/csv;base64,QQoxCjIKMwo="
},
"encoding": {
+ "tooltip": [
+ {
+ "bin": true,
+ "field": "A",
+ "title": "A",
+ "type": "quantitative"
+ },
+ {
+ "aggregate": "count",
+ "format": ",.0f",
+ "title": "Number of records",
+ "type": "quantitative"
+ }
+ ],
"x": {
"bin": true,
"field": "A",
+ "title": "A",
"type": "quantitative"
},
"y": {
"aggregate": "count",
+ "title": "Number of records",
"type": "quantitative"
}
},
"mark": {
+ "color": "#1C7361",
"type": "bar"
},
"width": "container"
diff --git a/tests/_data/snapshots/column_preview_int_chart_spec_with_vegafusion.txt b/tests/_data/snapshots/column_preview_int_chart_spec_with_vegafusion.txt
index a922e5e655..7d0a4cbb3f 100644
--- a/tests/_data/snapshots/column_preview_int_chart_spec_with_vegafusion.txt
+++ b/tests/_data/snapshots/column_preview_int_chart_spec_with_vegafusion.txt
@@ -30,7 +30,7 @@
"tickCount": {
"signal": "ceil(width/10)"
},
- "title": "A (binned)",
+ "title": "A",
"zindex": 0
},
{
@@ -41,11 +41,18 @@
"tickCount": {
"signal": "ceil(height/40)"
},
- "title": "Count of Records",
+ "title": "Number of records",
"zindex": 0
}
],
"background": "white",
+ "config": {
+ "style": {
+ "cell": {
+ "stroke": null
+ }
+ }
+ },
"data": [
{
"name": "source_0",
@@ -83,7 +90,10 @@
"encode": {
"update": {
"fill": {
- "value": "#4c78a8"
+ "value": "#1C7361"
+ },
+ "tooltip": {
+ "signal": "{\"A\": !isValid(datum[\"bin_maxbins_10_A\"]) || !isFinite(+datum[\"bin_maxbins_10_A\"]) ? \"null\" : format(datum[\"bin_maxbins_10_A\"], \"\") + \" \u2013 \" + format(datum[\"bin_maxbins_10_A_end\"], \"\"), \"Number of records\": format(datum[\"__count\"], \",.0f\")}"
},
"x": {
"field": "bin_maxbins_10_A_end",
diff --git a/tests/_data/snapshots/column_preview_str_chart_code.txt b/tests/_data/snapshots/column_preview_str_chart_code.txt
index 6a74b3c662..8053cef631 100644
--- a/tests/_data/snapshots/column_preview_str_chart_code.txt
+++ b/tests/_data/snapshots/column_preview_str_chart_code.txt
@@ -1,10 +1,29 @@
_chart = (
alt.Chart(table)
.mark_bar()
+ .transform_aggregate(count="count()", groupby=["B"])
+ .transform_window(
+ rank="rank()",
+ sort=[
+ alt.SortField("count", order="descending"),
+ alt.SortField("B", order="ascending"),
+ ],
+ )
+ .transform_filter(alt.datum.rank <= 10)
.encode(
- y=alt.Y("B", type="nominal"),
- x=alt.X("count()", type="quantitative"),
+ y=alt.Y(
+ "B:N",
+ sort="-x",
+ axis=alt.Axis(title=None),
+ ),
+ x=alt.X("count:Q", title="Number of records"),
+ tooltip=[
+ alt.Tooltip("B:N"),
+ alt.Tooltip("count:Q", format=",.0f", title="Number of records"),
+ ],
)
.properties(width="container")
+ .configure_view(stroke=None)
+ .configure_axis(grid=False)
)
_chart
\ No newline at end of file
diff --git a/tests/_data/snapshots/column_preview_str_chart_spec.txt b/tests/_data/snapshots/column_preview_str_chart_spec.txt
index 89e5ab3052..43721c83fd 100644
--- a/tests/_data/snapshots/column_preview_str_chart_spec.txt
+++ b/tests/_data/snapshots/column_preview_str_chart_spec.txt
@@ -1,9 +1,13 @@
{
"$schema": "https://vega.github.io/schema/vega-lite/v5.20.1.json",
"config": {
+ "axis": {
+ "grid": false
+ },
"view": {
"continuousHeight": 300,
- "continuousWidth": 300
+ "continuousWidth": 300,
+ "stroke": null
}
},
"data": {
@@ -12,18 +16,169 @@
},
"url": "data:text/csv;base64,QgphCmEKYQo="
},
- "encoding": {
- "x": {
- "aggregate": "count",
- "type": "quantitative"
+ "layer": [
+ {
+ "encoding": {
+ "tooltip": [
+ {
+ "field": "B",
+ "type": "nominal"
+ },
+ {
+ "field": "count",
+ "format": ",.0f",
+ "title": "Number of records",
+ "type": "quantitative"
+ }
+ ],
+ "x": {
+ "field": "count",
+ "title": "Number of records",
+ "type": "quantitative"
+ },
+ "y": {
+ "axis": {
+ "title": null
+ },
+ "field": "B",
+ "sort": "-x",
+ "type": "nominal"
+ }
+ },
+ "mark": {
+ "color": "#1C7361",
+ "type": "bar"
+ },
+ "transform": [
+ {
+ "aggregate": [
+ {
+ "as": "count",
+ "op": "count"
+ }
+ ],
+ "groupby": [
+ "B"
+ ]
+ },
+ {
+ "sort": [
+ {
+ "field": "count",
+ "order": "descending"
+ },
+ {
+ "field": "B",
+ "order": "ascending"
+ }
+ ],
+ "window": [
+ {
+ "as": "rank",
+ "field": "",
+ "op": "rank"
+ }
+ ]
+ },
+ {
+ "joinaggregate": [
+ {
+ "as": "total_count",
+ "field": "count",
+ "op": "sum"
+ }
+ ]
+ },
+ {
+ "as": "percentage",
+ "calculate": "datum.count / datum.total_count"
+ }
+ ]
},
- "y": {
- "field": "B",
- "type": "nominal"
+ {
+ "encoding": {
+ "text": {
+ "field": "percentage",
+ "format": ".2%",
+ "type": "quantitative"
+ },
+ "tooltip": [
+ {
+ "field": "B",
+ "type": "nominal"
+ },
+ {
+ "field": "count",
+ "format": ",.0f",
+ "title": "Number of records",
+ "type": "quantitative"
+ }
+ ],
+ "x": {
+ "field": "count",
+ "title": "Number of records",
+ "type": "quantitative"
+ },
+ "y": {
+ "axis": {
+ "title": null
+ },
+ "field": "B",
+ "sort": "-x",
+ "type": "nominal"
+ }
+ },
+ "mark": {
+ "align": "left",
+ "dx": 3,
+ "type": "text"
+ },
+ "transform": [
+ {
+ "aggregate": [
+ {
+ "as": "count",
+ "op": "count"
+ }
+ ],
+ "groupby": [
+ "B"
+ ]
+ },
+ {
+ "sort": [
+ {
+ "field": "count",
+ "order": "descending"
+ },
+ {
+ "field": "B",
+ "order": "ascending"
+ }
+ ],
+ "window": [
+ {
+ "as": "rank",
+ "field": "",
+ "op": "rank"
+ }
+ ]
+ },
+ {
+ "joinaggregate": [
+ {
+ "as": "total_count",
+ "field": "count",
+ "op": "sum"
+ }
+ ]
+ },
+ {
+ "as": "percentage",
+ "calculate": "datum.count / datum.total_count"
+ }
+ ]
}
- },
- "mark": {
- "type": "bar"
- },
+ ],
"width": "container"
}
\ No newline at end of file
diff --git a/tests/_data/snapshots/column_preview_str_chart_spec_with_vegafusion.txt b/tests/_data/snapshots/column_preview_str_chart_spec_with_vegafusion.txt
index 6913d463c5..8d2a644f76 100644
--- a/tests/_data/snapshots/column_preview_str_chart_spec_with_vegafusion.txt
+++ b/tests/_data/snapshots/column_preview_str_chart_spec_with_vegafusion.txt
@@ -5,22 +5,6 @@
"type": "fit-x"
},
"axes": [
- {
- "aria": false,
- "domain": false,
- "grid": true,
- "gridScale": "y",
- "labels": false,
- "maxExtent": 0,
- "minExtent": 0,
- "orient": "bottom",
- "scale": "x",
- "tickCount": {
- "signal": "ceil(width/40)"
- },
- "ticks": false,
- "zindex": 0
- },
{
"grid": false,
"labelFlush": true,
@@ -30,34 +14,49 @@
"tickCount": {
"signal": "ceil(width/40)"
},
- "title": "Count of Records",
+ "title": "Number of records",
"zindex": 0
},
{
"grid": false,
"orient": "left",
"scale": "y",
- "title": "B",
"zindex": 0
}
],
"background": "white",
+ "config": {
+ "axis": {
+ "grid": false
+ },
+ "style": {
+ "cell": {
+ "stroke": null
+ }
+ }
+ },
"data": [
{
- "name": "source_0",
+ "name": "source_0"
+ },
+ {
+ "name": "data_1",
"values": [
{
"B": "a",
- "__count": 3
+ "count": 3,
+ "percentage": 1.0
}
]
},
{
- "name": "source_0_x_domain___count",
+ "name": "data_2",
"values": [
{
- "max": 3,
- "min": 3
+ "B": "a",
+ "count": 3,
+ "count_end": 3.0,
+ "count_start": 0.0
}
]
},
@@ -65,7 +64,8 @@
"name": "source_0_y_domain_B",
"values": [
{
- "B": "a"
+ "B": "a",
+ "sort_field": 3
}
]
}
@@ -75,18 +75,21 @@
"encode": {
"update": {
"fill": {
- "value": "#4c78a8"
+ "value": "#1C7361"
},
"height": {
"signal": "max(0.25, bandwidth('y'))"
},
+ "tooltip": {
+ "signal": "{\"B\": isValid(datum[\"B\"]) ? datum[\"B\"] : \"\"+datum[\"B\"], \"Number of records\": format(datum[\"count\"], \",.0f\")}"
+ },
"x": {
- "field": "__count",
+ "field": "count_end",
"scale": "x"
},
"x2": {
- "scale": "x",
- "value": 0
+ "field": "count_start",
+ "scale": "x"
},
"y": {
"field": "B",
@@ -95,26 +98,75 @@
}
},
"from": {
- "data": "source_0"
+ "data": "data_2"
},
- "name": "marks",
+ "name": "layer_0_marks",
"style": [
"bar"
],
"type": "rect"
+ },
+ {
+ "encode": {
+ "update": {
+ "align": {
+ "value": "left"
+ },
+ "baseline": {
+ "value": "middle"
+ },
+ "dx": {
+ "value": 3
+ },
+ "fill": {
+ "value": "black"
+ },
+ "text": {
+ "signal": "format(datum[\"percentage\"], \".2%\")"
+ },
+ "tooltip": {
+ "signal": "{\"B\": isValid(datum[\"B\"]) ? datum[\"B\"] : \"\"+datum[\"B\"], \"Number of records\": format(datum[\"count\"], \",.0f\")}"
+ },
+ "x": {
+ "field": "count",
+ "scale": "x"
+ },
+ "y": {
+ "band": 0.5,
+ "field": "B",
+ "scale": "y"
+ }
+ }
+ },
+ "from": {
+ "data": "data_1"
+ },
+ "name": "layer_1_marks",
+ "style": [
+ "text"
+ ],
+ "type": "text"
}
],
"padding": 5,
"scales": [
{
- "domain": [
- {
- "signal": "(data(\"source_0_x_domain___count\")[0] || {}).min"
- },
- {
- "signal": "(data(\"source_0_x_domain___count\")[0] || {}).max"
- }
- ],
+ "domain": {
+ "fields": [
+ {
+ "data": "data_2",
+ "field": "count_start"
+ },
+ {
+ "data": "data_2",
+ "field": "count_end"
+ },
+ {
+ "data": "data_1",
+ "field": "count"
+ }
+ ]
+ },
"name": "x",
"nice": true,
"range": [
@@ -130,7 +182,11 @@
"domain": {
"data": "source_0_y_domain_B",
"field": "B",
- "sort": true
+ "sort": {
+ "field": "sort_field",
+ "op": "max",
+ "order": "descending"
+ }
},
"name": "y",
"paddingInner": 0.1,
diff --git a/tests/_data/test_charts.py b/tests/_data/test_charts.py
index 171b861d68..e2c864a880 100644
--- a/tests/_data/test_charts.py
+++ b/tests/_data/test_charts.py
@@ -40,12 +40,13 @@ def test_get_chart_builder():
)
-def test_charts_altair_code():
+def validate_and_return_codes(simple: bool) -> list[str]:
outputs: list[str] = []
for t, should_limit_to_10_items in TYPES:
builder = get_chart_builder(t, should_limit_to_10_items)
- code = builder.altair_code("df", "some_column")
+ code = builder.altair_code("df", "some_column", simple=simple)
+
# Validate it is valid Python code
try:
ast.parse(code)
@@ -54,8 +55,16 @@ def test_charts_altair_code():
title = f"{t} (limit to 10 items)" if should_limit_to_10_items else t
outputs.append(f"# {title}\n{code}")
+ return outputs
+
+
+def test_charts_altair_code():
+ outputs = validate_and_return_codes(simple=True)
snapshot("charts.txt", "\n\n".join(outputs))
+ complex_outputs = validate_and_return_codes(simple=False)
+ snapshot("charts-complex.txt", "\n\n".join(complex_outputs))
+
def test_charts_bad_characters():
outputs: list[str] = []
@@ -116,17 +125,17 @@ def test_charts_altair_json_bad_data():
# More than 10 years
(
({"dates": [datetime(2000, 1, 1), datetime(2020, 1, 1)]}),
- "%Y",
+ ("%Y", "year"),
),
# More than a year
(
({"dates": [datetime(2020, 1, 1), datetime(2021, 6, 1)]}),
- "%Y-%m",
+ ("%Y-%m", "yearmonth"),
),
# More than a month
(
({"dates": [datetime(2020, 1, 1), datetime(2020, 2, 15)]}),
- "%Y-%m-%d",
+ ("%Y-%m-%d", "yearmonthdate"),
),
# More than a day
(
@@ -138,7 +147,7 @@ def test_charts_altair_json_bad_data():
]
}
),
- "%Y-%m-%d %H:%M",
+ ("%Y-%m-%d %H:%M", "yearmonthdatehoursminutes"),
),
# Less than a day
(
@@ -150,7 +159,7 @@ def test_charts_altair_json_bad_data():
]
}
),
- "%Y-%m-%d %H:%M",
+ ("%Y-%m-%d %H:%M", "yearmonthdatehoursminutes"),
),
],
)
@@ -162,15 +171,21 @@ def test_date_chart_builder_guess_date_format_with_dataframes(
builder = DateChartBuilder()
for df in eager_dfs:
- assert builder._guess_date_format(df, "dates") == expected_format, (
- f"Expected {expected_format} for {type(df)}"
- )
+ date_format, time_unit = builder._guess_date_format(df, "dates")
+ assert (
+ date_format,
+ time_unit,
+ ) == expected_format, f"Expected {expected_format} for {type(df)}"
non_eager_dfs = create_dataframes(data, include=NON_EAGER_LIBS)
for df in non_eager_dfs:
+ date_format, time_unit = builder._guess_date_format(df, "dates")
assert (
- builder._guess_date_format(df, "dates")
- == DateChartBuilder.DEFAULT_DATE_FORMAT
+ date_format,
+ time_unit,
+ ) == (
+ DateChartBuilder.DEFAULT_DATE_FORMAT,
+ DateChartBuilder.DEFAULT_TIME_UNIT,
), f"Expected {DateChartBuilder.DEFAULT_DATE_FORMAT} for {type(df)}"
@@ -182,7 +197,41 @@ def test_date_chart_builder_guess_date_format_with_non_narwhalifiable_data():
class NonNarwhalifiableData:
pass
- assert (
- builder._guess_date_format(NonNarwhalifiableData(), "dates")
- == "%Y-%m-%d"
+ date_format, time_unit = builder._guess_date_format(
+ NonNarwhalifiableData(), "dates"
)
+ assert date_format == DateChartBuilder.DEFAULT_DATE_FORMAT
+ assert time_unit == DateChartBuilder.DEFAULT_TIME_UNIT
+
+
[email protected](not HAS_DEPS, reason="optional dependencies not installed")
+def test_date_chart_builder_get_date_format():
+ from datetime import datetime
+
+ import pandas as pd
+
+ builder = DateChartBuilder()
+
+ # Test with non-cached format (should guess)
+ data = pd.DataFrame(
+ {"dates": [datetime(2020, 1, 1), datetime(2020, 2, 1)]}
+ )
+
+ # First call should guess the format
+ date_format, time_unit = builder._get_date_format(data, "dates")
+ assert date_format == "%Y-%m-%d %H"
+ assert time_unit == "yearmonthdatehours"
+
+ # Second call should use cached format
+ date_format2, time_unit2 = builder._get_date_format(data, "dates")
+ assert date_format2 == date_format
+ assert time_unit2 == time_unit
+
+ # Test with manually set format
+ builder2 = DateChartBuilder()
+ builder2.date_format = "%Y"
+ builder2.time_unit = "year"
+
+ date_format3, time_unit3 = builder2._get_date_format(data, "dates")
+ assert date_format3 == "%Y"
+ assert time_unit3 == "year"