Top-Level Chart Configuration#

Many aspects of a chart’s appearance can be configured at the top level using the configure_*() methods. These methods and the properties that they set are only valid at the top level of a chart, and can be thought of as a way of setting a chart theme: that is, they set the default styles for the entire chart, and these defaults can be overridden by specific style settings associated with chart elements.

These methods and their arguments will be outlined below:

For more discussion of approaches to chart customization, see Customizing Visualizations.

Chart Configuration#

The Chart.configure() method adds a Config instance to the chart, and has the following attributes:

Property

Type

Description

arc

RectConfig

Arc-specific Config

area

AreaConfig

Area-Specific Config

aria

boolean

A boolean flag indicating if ARIA default attributes should be included for marks and guides (SVG output only). If false, the "aria-hidden" attribute will be set for all guides, removing them from the ARIA accessibility tree and Vega-Lite will not generate default descriptions for marks.

Default value: true.

autosize

anyOf(AutosizeType, AutoSizeParams)

How the visualization size should be determined. If a string, should be one of "pad", "fit" or "none". Object values can additionally specify parameters for content sizing and automatic resizing.

Default value: pad

axis

AxisConfig

Axis configuration, which determines default properties for all x and y axes. For a full list of axis configuration options, please see the corresponding section of the axis documentation.

axisBand

AxisConfig

Config for axes with “band” scales.

axisBottom

AxisConfig

Config for x-axis along the bottom edge of the chart.

axisDiscrete

AxisConfig

Config for axes with “point” or “band” scales.

axisLeft

AxisConfig

Config for y-axis along the left edge of the chart.

axisPoint

AxisConfig

Config for axes with “point” scales.

axisQuantitative

AxisConfig

Config for quantitative axes.

axisRight

AxisConfig

Config for y-axis along the right edge of the chart.

axisTemporal

AxisConfig

Config for temporal axes.

axisTop

AxisConfig

Config for x-axis along the top edge of the chart.

axisX

AxisConfig

X-axis specific config.

axisXBand

AxisConfig

Config for x-axes with “band” scales.

axisXDiscrete

AxisConfig

Config for x-axes with “point” or “band” scales.

axisXPoint

AxisConfig

Config for x-axes with “point” scales.

axisXQuantitative

AxisConfig

Config for x-quantitative axes.

axisXTemporal

AxisConfig

Config for x-temporal axes.

axisY

AxisConfig

Y-axis specific config.

axisYBand

AxisConfig

Config for y-axes with “band” scales.

axisYDiscrete

AxisConfig

Config for y-axes with “point” or “band” scales.

axisYPoint

AxisConfig

Config for y-axes with “point” scales.

axisYQuantitative

AxisConfig

Config for y-quantitative axes.

axisYTemporal

AxisConfig

Config for y-temporal axes.

background

anyOf(Color, ExprRef)

CSS color property to use as the background of the entire view.

Default value: "white"

bar

BarConfig

Bar-Specific Config

boxplot

BoxPlotConfig

Box Config

circle

MarkConfig

Circle-Specific Config

concat

CompositionConfig

Default configuration for all concatenation and repeat view composition operators (concat, hconcat, vconcat, and repeat)

countTitle

string

Default axis and legend title for count fields.

Default value: 'Count of Records.

customFormatTypes

boolean

Allow the formatType property for text marks and guides to accept a custom formatter function registered as a Vega expression.

errorband

ErrorBandConfig

ErrorBand Config

errorbar

ErrorBarConfig

ErrorBar Config

facet

CompositionConfig

Default configuration for the facet view composition operator

fieldTitle

[‘verbal’, ‘functional’, ‘plain’]

Defines how Vega-Lite generates title for fields. There are three possible styles:

  • "verbal" (Default) - displays function in a verbal style (e.g., “Sum of field”, “Year-month of date”, “field (binned)”).

  • "function" - displays function using parentheses and capitalized texts (e.g., “SUM(field)”, “YEARMONTH(date)”, “BIN(field)”).

  • "plain" - displays only the field name without functions (e.g., “field”, “date”, “field”).

font

string

Default font for all text marks, titles, and labels.

geoshape

MarkConfig

Geoshape-Specific Config

header

HeaderConfig

Header configuration, which determines default properties for all headers.

For a full list of header configuration options, please see the corresponding section of in the header documentation.

headerColumn

HeaderConfig

Header configuration, which determines default properties for column headers.

For a full list of header configuration options, please see the corresponding section of in the header documentation.

headerFacet

HeaderConfig

Header configuration, which determines default properties for non-row/column facet headers.

For a full list of header configuration options, please see the corresponding section of in the header documentation.

headerRow

HeaderConfig

Header configuration, which determines default properties for row headers.

For a full list of header configuration options, please see the corresponding section of in the header documentation.

image

RectConfig

Image-specific Config

legend

LegendConfig

Legend configuration, which determines default properties for all legends. For a full list of legend configuration options, please see the corresponding section of in the legend documentation.

line

LineConfig

Line-Specific Config

lineBreak

anyOf(string, ExprRef)

A delimiter, such as a newline character, upon which to break text strings into multiple lines. This property provides a global default for text marks, which is overridden by mark or style config settings, and by the lineBreak mark encoding channel. If signal-valued, either string or regular expression (regexp) values are valid.

locale

Locale

Locale definitions for string parsing and formatting of number and date values. The locale object should contain number and/or time properties with locale definitions. Locale definitions provided in the config block may be overridden by the View constructor locale option.

mark

MarkConfig

Mark Config

numberFormat

string

D3 Number format for guide labels and text marks. For example "s" for SI units. Use D3’s number format pattern.

padding

anyOf(Padding, ExprRef)

The default visualization padding, in pixels, from the edge of the visualization canvas to the data rectangle. If a number, specifies padding for all sides. If an object, the value should have the format {"left": 5, "top": 5, "right": 5, "bottom": 5} to specify padding for each side of the visualization.

Default value: 5

params

array(anyOf(VariableParameter, TopLevelSelectionParameter))

Dynamic variables or selections that parameterize a visualization.

point

MarkConfig

Point-Specific Config

projection

ProjectionConfig

Projection configuration, which determines default properties for all projections. For a full list of projection configuration options, please see the corresponding section of the projection documentation.

range

RangeConfig

An object hash that defines default range arrays or schemes for using with scales. For a full list of scale range configuration options, please see the corresponding section of the scale documentation.

rect

RectConfig

Rect-Specific Config

rule

MarkConfig

Rule-Specific Config

scale

ScaleConfig

Scale configuration determines default properties for all scales. For a full list of scale configuration options, please see the corresponding section of the scale documentation.

selection

SelectionConfig

An object hash for defining default properties for each type of selections.

square

MarkConfig

Square-Specific Config

style

StyleConfigIndex

An object hash that defines key-value mappings to determine default properties for marks with a given style. The keys represent styles names; the values have to be valid mark configuration objects.

text

MarkConfig

Text-Specific Config

tick

TickConfig

Tick-Specific Config

timeFormat

string

Default time format for raw time values (without time units) in text marks, legend labels and header labels.

Default value: "%b %d, %Y" Note: Axes automatically determine the format for each label automatically so this config does not affect axes.

title

TitleConfig

Title configuration, which determines default properties for all titles. For a full list of title configuration options, please see the corresponding section of the title documentation.

trail

LineConfig

Trail-Specific Config

view

ViewConfig

Default properties for single view plots.

Axis Configuration#

Axis configuration defines default settings for axes, and can be set using the Chart.configure_axis() method. Properties defined here are applied to all axes in the figure.

Additional property blocks can target more specific axis types based on the orientation (“axisX”, “axisY”, “axisLeft”, “axisTop”, etc.) or band scale type (“axisBand”). For example, properties defined under the “axisBand” property will only apply to axes visualizing “band” scales. If multiple axis config blocks apply to a single axis, type-based options take precedence over orientation-based options, which in turn take precedence over general options.

The methods are the following:

  • Chart.configure_axis()

  • Chart.configure_axisBand()

  • Chart.configure_axisBottom()

  • Chart.configure_axisLeft()

  • Chart.configure_axisRight()

  • Chart.configure_axisTop()

  • Chart.configure_axisX()

  • Chart.configure_axisY()

They have the following properties:

Property

Type

Description

aria

anyOf(boolean, ExprRef)

bandPosition

anyOf(number, ExprRef)

description

anyOf(string, ExprRef)

disable

boolean

Disable axis by default.

domain

boolean

A boolean flag indicating if the domain (the axis baseline) should be included as part of the axis.

Default value: true

domainCap

anyOf(StrokeCap, ExprRef)

domainColor

anyOf(anyOf(null, Color), ExprRef)

domainDash

anyOf(array(number), ExprRef)

domainDashOffset

anyOf(number, ExprRef)

domainOpacity

anyOf(number, ExprRef)

domainWidth

anyOf(number, ExprRef)

format

anyOf(string, Dict)

When used with the default "number" and "time" format type, the text formatting pattern for labels of guides (axes, legends, headers) and text marks.

See the format documentation for more examples.

When used with a custom formatType, this value will be passed as format alongside datum.value to the registered function.

Default value: Derived from numberFormat config for number format and from timeFormat config for time format.

formatType

string

The format type for labels. One of "number", "time", or a registered custom format type.

Default value:

  • "time" for temporal fields and ordinal and nominal fields with timeUnit.

  • "number" for quantitative fields as well as ordinal and nominal fields without timeUnit.

grid

boolean

A boolean flag indicating if grid lines should be included as part of the axis

Default value: true for continuous scales that are not binned; otherwise, false.

gridCap

anyOf(StrokeCap, ExprRef)

gridColor

anyOf(anyOf(null, Color), ExprRef, ConditionalAxisColor)

gridDash

anyOf(array(number), ExprRef, ConditionalAxisNumberArray)

gridDashOffset

anyOf(number, ExprRef, ConditionalAxisNumber)

gridOpacity

anyOf(number, ExprRef, ConditionalAxisNumber)

gridWidth

anyOf(number, ExprRef, ConditionalAxisNumber)

labelAlign

anyOf(Align, ExprRef, ConditionalAxisLabelAlign)

labelAngle

anyOf(number, ExprRef)

labelBaseline

anyOf(TextBaseline, ExprRef, ConditionalAxisLabelBaseline)

labelBound

anyOf([number, boolean], ExprRef)

labelColor

anyOf(anyOf(null, Color), ExprRef, ConditionalAxisColor)

labelExpr

string

Vega expression for customizing labels.

Note: The label text and value can be assessed via the label and value properties of the axis’s backing datum object.

labelFlush

[boolean, number]

Indicates if the first and last axis labels should be aligned flush with the scale range. Flush alignment for a horizontal axis will left-align the first label and right-align the last label. For vertical axes, bottom and top text baselines are applied instead. If this property is a number, it also indicates the number of pixels by which to offset the first and last labels; for example, a value of 2 will flush-align the first and last labels and also push them 2 pixels outward from the center of the axis. The additional adjustment can sometimes help the labels better visually group with corresponding axis ticks.

Default value: true for axis of a continuous x-scale. Otherwise, false.

labelFlushOffset

anyOf(number, ExprRef)

labelFont

anyOf(string, ExprRef, ConditionalAxisString)

labelFontSize

anyOf(number, ExprRef, ConditionalAxisNumber)

labelFontStyle

anyOf(FontStyle, ExprRef, ConditionalAxisLabelFontStyle)

labelFontWeight

anyOf(FontWeight, ExprRef, ConditionalAxisLabelFontWeight)

labelLimit

anyOf(number, ExprRef)

labelLineHeight

anyOf(number, ExprRef)

labelOffset

anyOf(number, ExprRef, ConditionalAxisNumber)

labelOpacity

anyOf(number, ExprRef, ConditionalAxisNumber)

labelOverlap

anyOf(LabelOverlap, ExprRef)

The strategy to use for resolving overlap of axis labels. If false (the default), no overlap reduction is attempted. If set to true or "parity", a strategy of removing every other label is used (this works well for standard linear axes). If set to "greedy", a linear scan of the labels is performed, removing any labels that overlaps with the last visible label (this often works better for log-scaled axes).

Default value: true for non-nominal fields with non-log scales; "greedy" for log scales; otherwise false.

labelPadding

anyOf(number, ExprRef, ConditionalAxisNumber)

labelSeparation

anyOf(number, ExprRef)

labels

boolean

A boolean flag indicating if labels should be included as part of the axis.

Default value: true.

maxExtent

anyOf(number, ExprRef)

minExtent

anyOf(number, ExprRef)

offset

anyOf(number, ExprRef)

The offset, in pixels, by which to displace the axis from the edge of the enclosing group or data rectangle.

Default value: derived from the axis config’s offset (0 by default)

orient

anyOf(AxisOrient, ExprRef)

The orientation of the axis. One of "top", "bottom", "left" or "right". The orientation can be used to further specialize the axis type (e.g., a y-axis oriented towards the right edge of the chart).

Default value: "bottom" for x-axes and "left" for y-axes.

position

anyOf(number, ExprRef)

The anchor position of the axis in pixels. For x-axes with top or bottom orientation, this sets the axis group x coordinate. For y-axes with left or right orientation, this sets the axis group y coordinate.

Default value: 0

style

anyOf(string, array(string))

A string or array of strings indicating the name of custom styles to apply to the axis. A style is a named collection of axis property defined within the style configuration. If style is an array, later styles will override earlier styles.

Default value: (none) Note: Any specified style will augment the default style. For example, an x-axis mark with "style": "foo" will use config.axisX and config.style.foo (the specified style "foo" has higher precedence).

tickBand

anyOf([‘center’, ‘extent’], ExprRef)

tickCap

anyOf(StrokeCap, ExprRef)

tickColor

anyOf(anyOf(null, Color), ExprRef, ConditionalAxisColor)

tickCount

anyOf(number, TimeInterval, TimeIntervalStep, ExprRef)

A desired number of ticks, for axes visualizing quantitative scales. The resulting number may be different so that values are “nice” (multiples of 2, 5, 10) and lie within the underlying scale’s range.

For scales of type "time" or "utc", the tick count can instead be a time interval specifier. Legal string values are "millisecond", "second", "minute", "hour", "day", "week", "month", and "year". Alternatively, an object-valued interval specifier of the form {"interval": "month", "step": 3} includes a desired number of interval steps. Here, ticks are generated for each quarter (Jan, Apr, Jul, Oct) boundary.

Default value: Determine using a formula ceil(width/40) for x and ceil(height/40) for y.

tickDash

anyOf(array(number), ExprRef, ConditionalAxisNumberArray)

tickDashOffset

anyOf(number, ExprRef, ConditionalAxisNumber)

tickExtra

boolean

Boolean flag indicating if an extra axis tick should be added for the initial position of the axis. This flag is useful for styling axes for band scales such that ticks are placed on band boundaries rather in the middle of a band. Use in conjunction with "bandPosition": 1 and an axis "padding" value of 0.

tickMinStep

anyOf(number, ExprRef)

The minimum desired step between axis ticks, in terms of scale domain values. For example, a value of 1 indicates that ticks should not be less than 1 unit apart. If tickMinStep is specified, the tickCount value will be adjusted, if necessary, to enforce the minimum step value.

tickOffset

anyOf(number, ExprRef)

tickOpacity

anyOf(number, ExprRef, ConditionalAxisNumber)

tickRound

boolean

Boolean flag indicating if pixel position values should be rounded to the nearest integer.

Default value: true

tickSize

anyOf(number, ExprRef, ConditionalAxisNumber)

tickWidth

anyOf(number, ExprRef, ConditionalAxisNumber)

ticks

boolean

Boolean value that determines whether the axis should include ticks.

Default value: true

title

anyOf(Text, null)

A title for the field. If null, the title will be removed.

Default value: derived from the field’s name and transformation function (aggregate, bin and timeUnit). If the field has an aggregate function, the function is displayed as part of the title (e.g., "Sum of Profit"). If the field is binned or has a time unit applied, the applied function is shown in parentheses (e.g., "Profit (binned)", "Transaction Date (year-month)"). Otherwise, the title is simply the field name.

Notes:

  1. You can customize the default field title format by providing the fieldTitle property in the config or fieldTitle function via the compile function’s options.

  2. If both field definition’s title and axis, header, or legend title are defined, axis/header/legend title will be used.

titleAlign

anyOf(Align, ExprRef)

titleAnchor

anyOf(TitleAnchor, ExprRef)

titleAngle

anyOf(number, ExprRef)

titleBaseline

anyOf(TextBaseline, ExprRef)

titleColor

anyOf(anyOf(null, Color), ExprRef)

titleFont

anyOf(string, ExprRef)

titleFontSize

anyOf(number, ExprRef)

titleFontStyle

anyOf(FontStyle, ExprRef)

titleFontWeight

anyOf(FontWeight, ExprRef)

titleLimit

anyOf(number, ExprRef)

titleLineHeight

anyOf(number, ExprRef)

titleOpacity

anyOf(number, ExprRef)

titlePadding

anyOf(number, ExprRef)

titleX

anyOf(number, ExprRef)

titleY

anyOf(number, ExprRef)

translate

anyOf(number, ExprRef)

values

anyOf(array(number), array(string), array(boolean), array(DateTime), ExprRef)

Explicitly set the visible axis tick values.

zindex

number

A non-negative integer indicating the z-index of the axis. If zindex is 0, axes should be drawn behind all chart elements. To put them in front, set zindex to 1 or more.

Default value: 0 (behind the marks).

Header Configuration#

The Chart.configure_header() method allows configuration of facet headers, including the font, color, size, and position of the title and labels. Here is an example:

import altair as alt
from vega_datasets import data

source = data.cars.url

chart = alt.Chart(source).mark_point().encode(
    x='Horsepower:Q',
    y='Miles_per_Gallon:Q',
    color='Origin:N',
    column='Origin:N'
).properties(
    width=180,
    height=180
)

chart.configure_header(
    titleColor='green',
    titleFontSize=14,
    labelColor='red',
    labelFontSize=14
)

Property

Type

Description

format

anyOf(string, Dict)

When used with the default "number" and "time" format type, the text formatting pattern for labels of guides (axes, legends, headers) and text marks.

See the format documentation for more examples.

When used with a custom formatType, this value will be passed as format alongside datum.value to the registered function.

Default value: Derived from numberFormat config for number format and from timeFormat config for time format.

formatType

string

The format type for labels. One of "number", "time", or a registered custom format type.

Default value:

  • "time" for temporal fields and ordinal and nominal fields with timeUnit.

  • "number" for quantitative fields as well as ordinal and nominal fields without timeUnit.

labelAlign

anyOf(Align, ExprRef)

Horizontal text alignment of header labels. One of "left", "center", or "right".

labelAnchor

TitleAnchor

The anchor position for placing the labels. One of "start", "middle", or "end". For example, with a label orientation of top these anchor positions map to a left-, center-, or right-aligned label.

labelAngle

number

The rotation angle of the header labels.

Default value: 0 for column header, -90 for row header.

labelBaseline

anyOf(TextBaseline, ExprRef)

The vertical text baseline for the header labels. One of "alphabetic" (default), "top", "middle", "bottom", "line-top", or "line-bottom". The "line-top" and "line-bottom" values operate similarly to "top" and "bottom", but are calculated relative to the titleLineHeight rather than titleFontSize alone.

labelColor

anyOf(Color, ExprRef)

The color of the header label, can be in hex color code or regular color name.

labelExpr

string

Vega expression for customizing labels.

Note: The label text and value can be assessed via the label and value properties of the header’s backing datum object.

labelFont

anyOf(string, ExprRef)

The font of the header label.

labelFontSize

anyOf(number, ExprRef)

The font size of the header label, in pixels.

labelFontStyle

anyOf(FontStyle, ExprRef)

The font style of the header label.

labelFontWeight

anyOf(FontWeight, ExprRef)

The font weight of the header label.

labelLimit

anyOf(number, ExprRef)

The maximum length of the header label in pixels. The text value will be automatically truncated if the rendered size exceeds the limit.

Default value: 0, indicating no limit

labelLineHeight

anyOf(number, ExprRef)

Line height in pixels for multi-line header labels or title text with "line-top" or "line-bottom" baseline.

labelOrient

Orient

The orientation of the header label. One of "top", "bottom", "left" or "right".

labelPadding

anyOf(number, ExprRef)

The padding, in pixel, between facet header’s label and the plot.

Default value: 10

labels

boolean

A boolean flag indicating if labels should be included as part of the header.

Default value: true.

orient

Orient

Shortcut for setting both labelOrient and titleOrient.

title

null

Set to null to disable title for the axis, legend, or header.

titleAlign

anyOf(Align, ExprRef)

Horizontal text alignment (to the anchor) of header titles.

titleAnchor

TitleAnchor

The anchor position for placing the title. One of "start", "middle", or "end". For example, with an orientation of top these anchor positions map to a left-, center-, or right-aligned title.

titleAngle

number

The rotation angle of the header title.

Default value: 0.

titleBaseline

anyOf(TextBaseline, ExprRef)

The vertical text baseline for the header title. One of "alphabetic" (default), "top", "middle", "bottom", "line-top", or "line-bottom". The "line-top" and "line-bottom" values operate similarly to "top" and "bottom", but are calculated relative to the titleLineHeight rather than titleFontSize alone.

Default value: "middle"

titleColor

anyOf(Color, ExprRef)

Color of the header title, can be in hex color code or regular color name.

titleFont

anyOf(string, ExprRef)

Font of the header title. (e.g., "Helvetica Neue").

titleFontSize

anyOf(number, ExprRef)

Font size of the header title.

titleFontStyle

anyOf(FontStyle, ExprRef)

The font style of the header title.

titleFontWeight

anyOf(FontWeight, ExprRef)

Font weight of the header title. This can be either a string (e.g "bold", "normal") or a number (100, 200, 300, …, 900 where "normal" = 400 and "bold" = 700).

titleLimit

anyOf(number, ExprRef)

The maximum length of the header title in pixels. The text value will be automatically truncated if the rendered size exceeds the limit.

Default value: 0, indicating no limit

titleLineHeight

anyOf(number, ExprRef)

Line height in pixels for multi-line header title text or title text with "line-top" or "line-bottom" baseline.

titleOrient

Orient

The orientation of the header title. One of "top", "bottom", "left" or "right".

titlePadding

anyOf(number, ExprRef)

The padding, in pixel, between facet header’s title and the label.

Default value: 10

Legend Configuration#

The Chart.configure_legend() allows you to customize the appearance of chart legends, including location, fonts, bounding boxes, colors, and more. Here is an example:

import altair as alt
from vega_datasets import data

source = data.cars.url

chart = alt.Chart(source).mark_point().encode(
    x='Horsepower:Q',
    y='Miles_per_Gallon:Q',
    color='Origin:N'
)

chart.configure_legend(
    strokeColor='gray',
    fillColor='#EEEEEE',
    padding=10,
    cornerRadius=10,
    orient='top-right'
)

Additional properties are summarized in the following table:

Property

Type

Description

aria

anyOf(boolean, ExprRef)

clipHeight

anyOf(number, ExprRef)

columnPadding

anyOf(number, ExprRef)

columns

anyOf(number, ExprRef)

cornerRadius

anyOf(number, ExprRef)

description

anyOf(string, ExprRef)

direction

Orientation

The direction of the legend, one of "vertical" or "horizontal".

Default value:

  • For top-/bottom-oriented legends, "horizontal"

  • For left-/right-oriented legends, "vertical"

  • For top/bottom-left/right-oriented legends, "horizontal" for gradient legends and "vertical" for symbol legends.

disable

boolean

Disable legend by default

fillColor

anyOf(anyOf(null, Color), ExprRef)

gradientDirection

anyOf(Orientation, ExprRef)

gradientHorizontalMaxLength

number

Max legend length for a horizontal gradient when config.legend.gradientLength is undefined.

Default value: 200

gradientHorizontalMinLength

number

Min legend length for a horizontal gradient when config.legend.gradientLength is undefined.

Default value: 100

gradientLabelLimit

anyOf(number, ExprRef)

gradientLabelOffset

anyOf(number, ExprRef)

gradientLength

anyOf(number, ExprRef)

gradientOpacity

anyOf(number, ExprRef)

gradientStrokeColor

anyOf(anyOf(null, Color), ExprRef)

gradientStrokeWidth

anyOf(number, ExprRef)

gradientThickness

anyOf(number, ExprRef)

gradientVerticalMaxLength

number

Max legend length for a vertical gradient when config.legend.gradientLength is undefined.

Default value: 200

gradientVerticalMinLength

number

Min legend length for a vertical gradient when config.legend.gradientLength is undefined.

Default value: 100

gridAlign

anyOf(LayoutAlign, ExprRef)

labelAlign

anyOf(Align, ExprRef)

labelBaseline

anyOf(TextBaseline, ExprRef)

labelColor

anyOf(anyOf(null, Color), ExprRef)

labelFont

anyOf(string, ExprRef)

labelFontSize

anyOf(number, ExprRef)

labelFontStyle

anyOf(FontStyle, ExprRef)

labelFontWeight

anyOf(FontWeight, ExprRef)

labelLimit

anyOf(number, ExprRef)

labelOffset

anyOf(number, ExprRef)

labelOpacity

anyOf(number, ExprRef)

labelOverlap

anyOf(LabelOverlap, ExprRef)

The strategy to use for resolving overlap of labels in gradient legends. If false, no overlap reduction is attempted. If set to true or "parity", a strategy of removing every other label is used. If set to "greedy", a linear scan of the labels is performed, removing any label that overlaps with the last visible label (this often works better for log-scaled axes).

Default value: "greedy" for log scales otherwise true`.

labelPadding

anyOf(number, ExprRef)

labelSeparation

anyOf(number, ExprRef)

layout

ExprRef

legendX

anyOf(number, ExprRef)

legendY

anyOf(number, ExprRef)

offset

anyOf(number, ExprRef)

orient

LegendOrient

The orientation of the legend, which determines how the legend is positioned within the scene. One of "left", "right", "top", "bottom", "top-left", "top-right", "bottom-left", "bottom-right", "none".

Default value: "right"

padding

anyOf(number, ExprRef)

rowPadding

anyOf(number, ExprRef)

strokeColor

anyOf(anyOf(null, Color), ExprRef)

strokeDash

anyOf(array(number), ExprRef)

strokeWidth

anyOf(number, ExprRef)

symbolBaseFillColor

anyOf(anyOf(null, Color), ExprRef)

symbolBaseStrokeColor

anyOf(anyOf(null, Color), ExprRef)

symbolDash

anyOf(array(number), ExprRef)

symbolDashOffset

anyOf(number, ExprRef)

symbolDirection

anyOf(Orientation, ExprRef)

symbolFillColor

anyOf(anyOf(null, Color), ExprRef)

symbolLimit

anyOf(number, ExprRef)

symbolOffset

anyOf(number, ExprRef)

symbolOpacity

anyOf(number, ExprRef)

symbolSize

anyOf(number, ExprRef)

symbolStrokeColor

anyOf(anyOf(null, Color), ExprRef)

symbolStrokeWidth

anyOf(number, ExprRef)

symbolType

anyOf(SymbolShape, ExprRef)

tickCount

anyOf(TickCount, ExprRef)

title

null

Set to null to disable title for the axis, legend, or header.

titleAlign

anyOf(Align, ExprRef)

titleAnchor

anyOf(TitleAnchor, ExprRef)

titleBaseline

anyOf(TextBaseline, ExprRef)

titleColor

anyOf(anyOf(null, Color), ExprRef)

titleFont

anyOf(string, ExprRef)

titleFontSize

anyOf(number, ExprRef)

titleFontStyle

anyOf(FontStyle, ExprRef)

titleFontWeight

anyOf(FontWeight, ExprRef)

titleLimit

anyOf(number, ExprRef)

titleLineHeight

anyOf(number, ExprRef)

titleOpacity

anyOf(number, ExprRef)

titleOrient

anyOf(Orient, ExprRef)

titlePadding

anyOf(number, ExprRef)

unselectedOpacity

number

The opacity of unselected legend entries.

Default value: 0.35.

zindex

anyOf(number, ExprRef)

Mark and Mark Style Configuration#

The mark configuration can be set using the Chart.configure_mark() method, which sets the default properties for all marks in the chart. In addition, the config object also provides mark-specific configuration using the mark type (e.g. Chart.configure_area()) for defining default properties for each mark.

For general configuration of all mark types, use:

  • Chart.configure_mark()

For configurations specific to particular mark types, use:

  • Chart.configure_area()

  • Chart.configure_bar()

  • Chart.configure_circle()

  • Chart.configure_geoshape()

  • Chart.configure_line()

  • Chart.configure_point()

  • Chart.configure_rect()

  • Chart.configure_rule()

  • Chart.configure_square()

  • Chart.configure_text()

  • Chart.configure_tick()

  • Chart.configure_trail()

Each of the above methods accepts the following properties:

Property

Type

Description

align

anyOf(Align, ExprRef)

The horizontal alignment of the text or ranged marks (area, bar, image, rect, rule). One of "left", "right", "center".

Note: Expression reference is not supported for range marks.

angle

anyOf(number, ExprRef)

aria

anyOf(boolean, ExprRef)

ariaRole

anyOf(string, ExprRef)

ariaRoleDescription

anyOf(string, ExprRef)

aspect

anyOf(boolean, ExprRef)

baseline

anyOf(TextBaseline, ExprRef)

For text marks, the vertical text baseline. One of "alphabetic" (default), "top", "middle", "bottom", "line-top", "line-bottom", or an expression reference that provides one of the valid values. The "line-top" and "line-bottom" values operate similarly to "top" and "bottom", but are calculated relative to the lineHeight rather than fontSize alone.

For range marks, the vertical alignment of the marks. One of "top", "middle", "bottom".

Note: Expression reference is not supported for range marks.

blend

anyOf(Blend, ExprRef)

color

anyOf(Color, Gradient, ExprRef)

Default color.

Default value: "#4682b4"

Note:

  • This property cannot be used in a style config.

  • The fill and stroke properties have higher precedence than color and will override color.

cornerRadius

anyOf(number, ExprRef)

cornerRadiusBottomLeft

anyOf(number, ExprRef)

cornerRadiusBottomRight

anyOf(number, ExprRef)

cornerRadiusTopLeft

anyOf(number, ExprRef)

cornerRadiusTopRight

anyOf(number, ExprRef)

cursor

anyOf(Cursor, ExprRef)

description

anyOf(string, ExprRef)

dir

anyOf(TextDirection, ExprRef)

dx

anyOf(number, ExprRef)

dy

anyOf(number, ExprRef)

ellipsis

anyOf(string, ExprRef)

endAngle

anyOf(number, ExprRef)

fill

anyOf(Color, Gradient, null, ExprRef)

Default fill color. This property has higher precedence than config.color. Set to null to remove fill.

Default value: (None)

fillOpacity

anyOf(number, ExprRef)

filled

boolean

Whether the mark’s color should be used as fill color instead of stroke color.

Default value: false for all point, line, and rule marks as well as geoshape marks for graticule data sources; otherwise, true.

Note: This property cannot be used in a style config.

font

anyOf(string, ExprRef)

fontSize

anyOf(number, ExprRef)

fontStyle

anyOf(FontStyle, ExprRef)

fontWeight

anyOf(FontWeight, ExprRef)

height

anyOf(number, ExprRef)

href

anyOf(URI, ExprRef)

innerRadius

anyOf(number, ExprRef)

The inner radius in pixels of arc marks. innerRadius is an alias for radius2.

Default value: 0

interpolate

anyOf(Interpolate, ExprRef)

invalid

[‘filter’, None]

Defines how Vega-Lite should handle marks for invalid values (null and NaN).

  • If set to "filter" (default), all data items with null values will be skipped (for line, trail, and area marks) or filtered (for other marks).

  • If null, all data items are included. In this case, invalid values will be interpreted as zeroes.

limit

anyOf(number, ExprRef)

lineBreak

anyOf(string, ExprRef)

lineHeight

anyOf(number, ExprRef)

opacity

anyOf(number, ExprRef)

The overall opacity (value between [0,1]).

Default value: 0.7 for non-aggregate plots with point, tick, circle, or square marks or layered bar charts and 1 otherwise.

order

[null, boolean]

For line and trail marks, this order property can be set to null or false to make the lines use the original order in the data sources.

orient

Orientation

The orientation of a non-stacked bar, tick, area, and line charts. The value is either horizontal (default) or vertical.

  • For bar, rule and tick, this determines whether the size of the bar and tick should be applied to x or y dimension.

  • For area, this property determines the orient property of the Vega output.

  • For line and trail marks, this property determines the sort order of the points in the line if config.sortLineBy is not specified. For stacked charts, this is always determined by the orientation of the stack; therefore explicitly specified value will be ignored.

outerRadius

anyOf(number, ExprRef)

The outer radius in pixels of arc marks. outerRadius is an alias for radius.

Default value: 0

padAngle

anyOf(number, ExprRef)

radius

anyOf(number, ExprRef)

For arc mark, the primary (outer) radius in pixels.

For text marks, polar coordinate radial offset, in pixels, of the text from the origin determined by the x and y properties.

Default value: min(plot_width, plot_height)/2

radius2

anyOf(number, ExprRef)

The secondary (inner) radius in pixels of arc marks.

Default value: 0

shape

anyOf(anyOf(SymbolShape, string), ExprRef)

size

anyOf(number, ExprRef)

Default size for marks.

  • For point/circle/square, this represents the pixel area of the marks. Note that this value sets the area of the symbol; the side lengths will increase with the square root of this value.

  • For bar, this represents the band size of the bar, in pixels.

  • For text, this represents the font size, in pixels.

Default value:

  • 30 for point, circle, square marks; width/height’s step

  • 2 for bar marks with discrete dimensions;

  • 5 for bar marks with continuous dimensions;

  • 11 for text marks.

smooth

anyOf(boolean, ExprRef)

startAngle

anyOf(number, ExprRef)

stroke

anyOf(Color, Gradient, null, ExprRef)

Default stroke color. This property has higher precedence than config.color. Set to null to remove stroke.

Default value: (None)

strokeCap

anyOf(StrokeCap, ExprRef)

strokeDash

anyOf(array(number), ExprRef)

strokeDashOffset

anyOf(number, ExprRef)

strokeJoin

anyOf(StrokeJoin, ExprRef)

strokeMiterLimit

anyOf(number, ExprRef)

strokeOffset

anyOf(number, ExprRef)

strokeOpacity

anyOf(number, ExprRef)

strokeWidth

anyOf(number, ExprRef)

tension

anyOf(number, ExprRef)

text

anyOf(Text, ExprRef)

theta

anyOf(number, ExprRef)

  • For arc marks, the arc length in radians if theta2 is not specified, otherwise the start arc angle. (A value of 0 indicates up or “north”, increasing values proceed clockwise.)

  • For text marks, polar coordinate angle in radians.

theta2

anyOf(number, ExprRef)

The end angle of arc marks in radians. A value of 0 indicates up or “north”, increasing values proceed clockwise.

timeUnitBandPosition

number

Default relative band position for a time unit. If set to 0, the marks will be positioned at the beginning of the time unit band step. If set to 0.5, the marks will be positioned in the middle of the time unit band step.

timeUnitBandSize

number

Default relative band size for a time unit. If set to 1, the bandwidth of the marks will be equal to the time unit band step. If set to 0.5, bandwidth of the marks will be half of the time unit band step.

tooltip

anyOf(number, string, boolean, TooltipContent, ExprRef, null)

The tooltip text string to show upon mouse hover or an object defining which fields should the tooltip be derived from.

  • If tooltip is true or {"content": "encoding"}, then all fields from encoding will be used.

  • If tooltip is {"content": "data"}, then all fields that appear in the highlighted data point will be used.

  • If set to null or false, then no tooltip will be used.

See the tooltip documentation for a detailed discussion about tooltip in Vega-Lite.

Default value: null

url

anyOf(URI, ExprRef)

width

anyOf(number, ExprRef)

x

anyOf(number, string, ExprRef)

X coordinates of the marks, or width of horizontal "bar" and "area" without specified x2 or width.

The value of this channel can be a number or a string "width" for the width of the plot.

x2

anyOf(number, string, ExprRef)

X2 coordinates for ranged "area", "bar", "rect", and "rule".

The value of this channel can be a number or a string "width" for the width of the plot.

y

anyOf(number, string, ExprRef)

Y coordinates of the marks, or height of vertical "bar" and "area" without specified y2 or height.

The value of this channel can be a number or a string "height" for the height of the plot.

y2

anyOf(number, string, ExprRef)

Y2 coordinates for ranged "area", "bar", "rect", and "rule".

The value of this channel can be a number or a string "height" for the height of the plot.

In addition to the default mark properties above, default values can be further customized using named styles defined as keyword arguments to the Chart.configure_style() method. Styles can then be invoked by including a style property within a mark definition object.

Scale Configuration#

Scales can be configured using Chart.configure_scale(), which has the following properties:

Property

Type

Description

bandPaddingInner

anyOf(number, ExprRef)

Default inner padding for x and y band scales.

Default value:

  • nestedOffsetPaddingInner for x/y scales with nested x/y offset scales.

  • barBandPaddingInner for bar marks (0.1 by default)

  • rectBandPaddingInner for rect and other marks (0 by default)

bandPaddingOuter

anyOf(number, ExprRef)

Default outer padding for x and y band scales.

Default value: paddingInner/2 (which makes width/height = number of unique values * step)

bandWithNestedOffsetPaddingInner

anyOf(number, ExprRef)

Default inner padding for x and y band scales with nested xOffset and yOffset encoding.

Default value: 0.2

bandWithNestedOffsetPaddingOuter

anyOf(number, ExprRef)

Default outer padding for x and y band scales with nested xOffset and yOffset encoding.

Default value: 0.2

barBandPaddingInner

anyOf(number, ExprRef)

Default inner padding for x and y band-ordinal scales of "bar" marks.

Default value: 0.1

clamp

anyOf(boolean, ExprRef)

If true, values that exceed the data domain are clamped to either the minimum or maximum range value

continuousPadding

anyOf(number, ExprRef)

Default padding for continuous x/y scales.

Default: The bar width for continuous x-scale of a vertical bar and continuous y-scale of a horizontal bar.; 0 otherwise.

maxBandSize

number

The default max value for mapping quantitative fields to bar’s size/bandSize.

If undefined (default), we will use the axis’s size (width or height) - 1.

maxFontSize

number

The default max value for mapping quantitative fields to text’s size/fontSize.

Default value: 40

maxOpacity

number

Default max opacity for mapping a field to opacity.

Default value: 0.8

maxSize

number

Default max value for point size scale.

maxStrokeWidth

number

Default max strokeWidth for the scale of strokeWidth for rule and line marks and of size for trail marks.

Default value: 4

minBandSize

number

The default min value for mapping quantitative fields to bar and tick’s size/bandSize scale with zero=false.

Default value: 2

minFontSize

number

The default min value for mapping quantitative fields to tick’s size/fontSize scale with zero=false

Default value: 8

minOpacity

number

Default minimum opacity for mapping a field to opacity.

Default value: 0.3

minSize

number

Default minimum value for point size scale with zero=false.

Default value: 9

minStrokeWidth

number

Default minimum strokeWidth for the scale of strokeWidth for rule and line marks and of size for trail marks with zero=false.

Default value: 1

offsetBandPaddingInner

anyOf(number, ExprRef)

Default padding inner for xOffset/yOffset’s band scales.

Default Value: 0

offsetBandPaddingOuter

anyOf(number, ExprRef)

Default padding outer for xOffset/yOffset’s band scales.

Default Value: 0

pointPadding

anyOf(number, ExprRef)

Default outer padding for x and y point-ordinal scales.

Default value: 0.5 (which makes width/height = number of unique values * step)

quantileCount

number

Default range cardinality for quantile scale.

Default value: 4

quantizeCount

number

Default range cardinality for quantize scale.

Default value: 4

rectBandPaddingInner

anyOf(number, ExprRef)

Default inner padding for x and y band-ordinal scales of "rect" marks.

Default value: 0

round

anyOf(boolean, ExprRef)

If true, rounds numeric output values to integers. This can be helpful for snapping to the pixel grid. (Only available for x, y, and size scales.)

useUnaggregatedDomain

boolean

Use the source data range before aggregation as scale domain instead of aggregated data for aggregate axis.

This is equivalent to setting domain to "unaggregate" for aggregated quantitative fields by default.

This property only works with aggregate functions that produce values within the raw data domain ("mean", "average", "median", "q1", "q3", "min", "max"). For other aggregations that produce values outside of the raw data domain (e.g. "count", "sum"), this property is ignored.

Default value: false

xReverse

anyOf(boolean, ExprRef)

Reverse x-scale by default (useful for right-to-left charts).

Scale Range Configuration#

Scale ranges can be configured using Chart.configure_range(), which has the following properties:

Property

Type

Description

category

anyOf(RangeScheme, array(Color))

Default color scheme for categorical data.

diverging

anyOf(RangeScheme, array(Color))

Default color scheme for diverging quantitative ramps.

heatmap

anyOf(RangeScheme, array(Color))

Default color scheme for quantitative heatmaps.

ordinal

anyOf(RangeScheme, array(Color))

Default color scheme for rank-ordered data.

ramp

anyOf(RangeScheme, array(Color))

Default color scheme for sequential quantitative ramps.

symbol

array(SymbolShape)

Array of symbol names or paths for the default shape palette.

Projection Configuration#

Chart.configure_projection()

Property

Type

Description

center

anyOf(Vector2<number>, ExprRef)

clipAngle

anyOf(number, ExprRef)

clipExtent

anyOf(Vector2<Vector2<number>>, ExprRef)

coefficient

anyOf(number, ExprRef)

distance

anyOf(number, ExprRef)

extent

anyOf(Vector2<Vector2<number>>, ExprRef)

fit

anyOf(array(GeoJsonFeature), array(Fit), ExprRef)

fraction

anyOf(number, ExprRef)

lobes

anyOf(number, ExprRef)

parallel

anyOf(number, ExprRef)

parallels

anyOf(array(number), ExprRef)

pointRadius

anyOf(number, ExprRef)

precision

anyOf(number, ExprRef)

radius

anyOf(number, ExprRef)

ratio

anyOf(number, ExprRef)

reflectX

anyOf(boolean, ExprRef)

reflectY

anyOf(boolean, ExprRef)

rotate

anyOf(anyOf(Vector2<number>, Vector3<number>), ExprRef)

scale

anyOf(number, ExprRef)

The projection’s scale (zoom) factor, overriding automatic fitting. The default scale is projection-specific. The scale factor corresponds linearly to the distance between projected points; however, scale factor values are not equivalent across projections.

size

anyOf(Vector2<number>, ExprRef)

spacing

anyOf(number, ExprRef)

tilt

anyOf(number, ExprRef)

translate

anyOf(Vector2<number>, ExprRef)

The projection’s translation offset as a two-element array [tx, ty].

type

anyOf(ProjectionType, ExprRef)

The cartographic projection to use. This value is case-insensitive, for example "albers" and "Albers" indicate the same projection type. You can find all valid projection types in the documentation.

Default value: equalEarth

Selection Configuration#

Chart.configure_selection()

Property

Type

Description

interval

IntervalSelectionConfigWithoutType

The default definition for an interval selection. All properties and transformations for an interval selection definition (except type) may be specified here.

For instance, setting interval to {"translate": false} disables the ability to move interval selections by default.

point

PointSelectionConfigWithoutType

The default definition for a point selection. All properties and transformations for a point selection definition (except type) may be specified here.

For instance, setting point to {"on": "dblclick"} populates point selections on double-click by default.

Title Configuration#

The Chart.configure_title() method allows configuration of the chart title, including the font, color, placement, and orientation. Here is an example:

import altair as alt
from vega_datasets import data

source = data.cars.url

chart = alt.Chart(source).mark_point().encode(
    x='Horsepower:Q',
    y='Miles_per_Gallon:Q',
).properties(
    title='Cars Data'
)

chart.configure_title(
    fontSize=20,
    font='Courier',
    anchor='start',
    color='gray'
)

Additional title configuration options are listed in the following table:

Property

Type

Description

align

Align

Horizontal text alignment for title text. One of "left", "center", or "right".

anchor

anyOf(TitleAnchor, ExprRef)

angle

anyOf(number, ExprRef)

aria

anyOf(boolean, ExprRef)

baseline

TextBaseline

Vertical text baseline for title and subtitle text. One of "alphabetic" (default), "top", "middle", "bottom", "line-top", or "line-bottom". The "line-top" and "line-bottom" values operate similarly to "top" and "bottom", but are calculated relative to the lineHeight rather than fontSize alone.

color

anyOf(anyOf(null, Color), ExprRef)

dx

anyOf(number, ExprRef)

dy

anyOf(number, ExprRef)

font

anyOf(string, ExprRef)

fontSize

anyOf(number, ExprRef)

fontStyle

anyOf(FontStyle, ExprRef)

fontWeight

anyOf(FontWeight, ExprRef)

frame

anyOf(anyOf(TitleFrame, string), ExprRef)

limit

anyOf(number, ExprRef)

lineHeight

anyOf(number, ExprRef)

offset

anyOf(number, ExprRef)

orient

anyOf(TitleOrient, ExprRef)

subtitleColor

anyOf(anyOf(null, Color), ExprRef)

subtitleFont

anyOf(string, ExprRef)

subtitleFontSize

anyOf(number, ExprRef)

subtitleFontStyle

anyOf(FontStyle, ExprRef)

subtitleFontWeight

anyOf(FontWeight, ExprRef)

subtitleLineHeight

anyOf(number, ExprRef)

subtitlePadding

anyOf(number, ExprRef)

zindex

anyOf(number, ExprRef)

View Configuration#

The Chart.configure_view() method allows you to configure aspects of the chart’s view, i.e. the area of the screen in which the data and scales are drawn. Here is an example to demonstrate some of the visual features that can be controlled:

import altair as alt
from vega_datasets import data

source = data.cars.url

chart = alt.Chart(source).mark_point().encode(
    x='Horsepower:Q',
    y='Miles_per_Gallon:Q',
)

chart.configure_view(
    continuousHeight=200,
    continuousWidth=200,
    strokeWidth=4,
    fill='#FFEEDD',
    stroke='red',
)

Additional properties are summarized in the following table:

Property

Type

Description

clip

boolean

Whether the view should be clipped.

continuousHeight

number

The default height when the plot has a continuous y-field for x or latitude, or has arc marks.

Default value: 200

continuousWidth

number

The default width when the plot has a continuous field for x or longitude, or has arc marks.

Default value: 200

cornerRadius

anyOf(number, ExprRef)

cursor

Cursor

The mouse cursor used over the view. Any valid CSS cursor type can be used.

discreteHeight

anyOf(number, dict)

The default height when the plot has non arc marks and either a discrete y-field or no y-field. The height can be either a number indicating a fixed height or an object in the form of {step: number} defining the height per discrete step.

Default value: a step size based on config.view.step.

discreteWidth

anyOf(number, dict)

The default width when the plot has non-arc marks and either a discrete x-field or no x-field. The width can be either a number indicating a fixed width or an object in the form of {step: number} defining the width per discrete step.

Default value: a step size based on config.view.step.

fill

anyOf(Color, null, ExprRef)

The fill color.

Default value: undefined

fillOpacity

anyOf(number, ExprRef)

opacity

anyOf(number, ExprRef)

The overall opacity (value between [0,1]).

Default value: 0.7 for non-aggregate plots with point, tick, circle, or square marks or layered bar charts and 1 otherwise.

step

number

Default step size for x-/y- discrete fields.

stroke

anyOf(Color, null, ExprRef)

The stroke color.

Default value: "#ddd"

strokeCap

anyOf(StrokeCap, ExprRef)

strokeDash

anyOf(array(number), ExprRef)

strokeDashOffset

anyOf(number, ExprRef)

strokeJoin

anyOf(StrokeJoin, ExprRef)

strokeMiterLimit

anyOf(number, ExprRef)

strokeOpacity

anyOf(number, ExprRef)

strokeWidth

anyOf(number, ExprRef)

Altair Themes#

Altair makes available a theme registry that lets users apply chart configurations globally within any Python session. This is done via the alt.themes object.

The themes registry consists of functions which define a specification dictionary that will be added to every created chart. For example, the default theme configures the default size of a single chart:

>>> import altair as alt
>>> default = alt.themes.get()
>>> default()
{'config': {'view': {'continuousWidth': 400, 'continuousHeight': 300}}}

You can see that any chart you create will have this theme applied, and these configurations added to its specification:

import altair as alt
from vega_datasets import data

chart = alt.Chart(data.cars.url).mark_point().encode(
    x='Horsepower:Q',
    y='Miles_per_Gallon:Q'
)

chart.to_dict()
    {'config': {'view': {'continuousWidth': 400, 'continuousHeight': 300}}, 'data': {'url': 'https://cdn.jsdelivr.net/npm/vega-datasets@v1.29.0/data/cars.json'}, 'mark': 'point', 'encoding': {'x': {'field': 'Horsepower', 'type': 'quantitative'}, 'y': {'field': 'Miles_per_Gallon', 'type': 'quantitative'}}, '$schema': 'https://vega.github.io/schema/vega-lite/v5.2.0.json'}

The rendered chart will then reflect these configurations:

chart

Changing the Theme#

If you would like to enable any other theme for the length of your Python session, you can call alt.themes.enable(theme_name). For example, Altair includes a theme in which the chart background is opaque rather than transparent:

alt.themes.enable('opaque')
chart.to_dict()
    {'config': {'background': 'white', 'view': {'continuousWidth': 400, 'continuousHeight': 300}}, 'data': {'url': 'https://cdn.jsdelivr.net/npm/vega-datasets@v1.29.0/data/cars.json'}, 'mark': 'point', 'encoding': {'x': {'field': 'Horsepower', 'type': 'quantitative'}, 'y': {'field': 'Miles_per_Gallon', 'type': 'quantitative'}}, '$schema': 'https://vega.github.io/schema/vega-lite/v5.2.0.json'}
chart

Notice that the background color of the chart is now set to white. If you would like no theme applied to your chart, you can use the theme named 'none':

alt.themes.enable('none')
chart.to_dict()
    {'data': {'url': 'https://cdn.jsdelivr.net/npm/vega-datasets@v1.29.0/data/cars.json'}, 'mark': 'point', 'encoding': {'x': {'field': 'Horsepower', 'type': 'quantitative'}, 'y': {'field': 'Miles_per_Gallon', 'type': 'quantitative'}}, '$schema': 'https://vega.github.io/schema/vega-lite/v5.2.0.json'}
chart

Because the view configuration is not set, the chart is smaller than the default rendering.

If you would like to use any theme just for a single chart, you can use the with statement to enable a temporary theme:

with alt.themes.enable('default'):
    spec = chart.to_json()

Currently Altair does not offer many built-in themes, but we plan to add more options in the future.

Defining a Custom Theme#

The theme registry also allows defining and registering custom themes. A theme is simply a function that returns a dictionary of default values to be added to the chart specification at rendering time, which is then registered and activated.

For example, here we define a theme in which all marks are drawn with black fill unless otherwise specified:

import altair as alt
from vega_datasets import data

# define the theme by returning the dictionary of configurations
def black_marks():
    return {
        'config': {
            'view': {
                'height': 300,
                'width': 400,
            },
            'mark': {
                'color': 'black',
                'fill': 'black'
            }
        }
    }

# register the custom theme under a chosen name
alt.themes.register('black_marks', black_marks)

# enable the newly registered theme
alt.themes.enable('black_marks')

# draw the chart
cars = data.cars.url
alt.Chart(cars).mark_point().encode(
    x='Horsepower:Q',
    y='Miles_per_Gallon:Q'
)

If you want to restore the default theme, use:

alt.themes.enable('default')

For more ideas on themes, see the Vega Themes repository.