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:
- Chart Configuration
Chart.configure()
- Axis Configuration
Chart.configure_axis()
- Legend Configuration
Chart.configure_legend()
- Scale Configuration
Chart.configure_scale()
- Scale Range Configuration
Chart.configure_range()
- Projection Configuration
Chart.configure_projection()
- Selection Configuration
Chart.configure_selection()
- View Configuration
Chart.configure_view()
Chart Configuration¶
The Chart.configure()
method adds a Config
instance to the chart,
and has the following attributes:
Property | Type | Description |
---|---|---|
area | AreaConfig |
Area-Specific Config |
autosize | anyOf(AutosizeType , AutoSizeParams ) |
Sets how the visualization size should be determined. If a string, should be one of Default value: |
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 | VgAxisConfig |
Specific axis config for axes with “band” scales. |
axisBottom | VgAxisConfig |
Specific axis config for x-axis along the bottom edge of the chart. |
axisLeft | VgAxisConfig |
Specific axis config for y-axis along the left edge of the chart. |
axisRight | VgAxisConfig |
Specific axis config for y-axis along the right edge of the chart. |
axisTop | VgAxisConfig |
Specific axis config for x-axis along the top edge of the chart. |
axisX | VgAxisConfig |
X-axis specific config. |
axisY | VgAxisConfig |
Y-axis specific config. |
background | string |
CSS color property to use as the background of visualization. Default value: none (transparent) |
bar | BarConfig |
Bar-Specific Config |
circle | MarkConfig |
Circle-Specific Config |
countTitle | string |
Default axis and legend title for count fields. Default value: |
datasets | Datasets |
A global data store for named datasets. This is a mapping from names to inline datasets.
This can be an array of objects or primitive values or a string. Arrays of primitive values are ingested as objects with a data property. |
fieldTitle | [‘verbal’, ‘functional’, ‘plain’] | Defines how Vega-Lite generates title for fields. There are three possible styles:
|
geoshape | MarkConfig |
Geoshape-Specific Config |
header | HeaderConfig |
Header configuration, which determines default properties for all header. For a full list of header configuration options, please see the corresponding section of in the header documentation. |
invalidValues | [‘filter’, None] | Defines how Vega-Lite should handle invalid values (
|
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 |
mark | MarkConfig |
Mark Config |
numberFormat | string |
D3 Number format for axis labels and text tables. For example “s” for SI units. Use D3’s number format pattern. |
padding | Padding |
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 Default value: |
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 | MarkConfig |
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 |
stack | StackOffset |
Default stack offset for stackable mark. |
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 | TextConfig |
Text-Specific Config |
tick | TickConfig |
Tick-Specific Config |
timeFormat | string |
Default datetime format for axis and legend labels. The format can be set directly on each axis and legend. Use D3’s time format pattern. Default value: |
title | VgTitleConfig |
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 |
---|---|---|
bandPosition | number |
An interpolation fraction indicating where, for band scales, axis ticks should be positioned. A value of 0 places ticks at the left edge of their bands. A value of 0.5 places ticks in the middle of their bands. |
domain | boolean |
A boolean flag indicating if the domain (the axis baseline) should be included as part of the axis. Default value: |
domainColor | string |
Color of axis domain line. Default value: (none, using Vega default). |
domainWidth | number |
Stroke width of axis domain line Default value: (none, using Vega default). |
grid | boolean |
A boolean flag indicating if grid lines should be included as part of the axis Default value: |
gridColor | string |
Color of gridlines. |
gridDash | array(number ) |
The offset (in pixels) into which to begin drawing with the grid dash array. |
gridOpacity | number |
The stroke opacity of grid (value between [0,1]) Default value: ( |
gridWidth | number |
The grid width, in pixels. |
labelAngle | number |
The rotation angle of the axis labels. Default value: |
labelBound | [boolean, number] | Indicates if labels should be hidden if they exceed the axis range. If Default value: |
labelColor | string |
The color of the tick label, can be in hex color code or regular color name. |
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: |
labelFont | string |
The font of the tick label. |
labelFontSize | number |
The font size of the label, in pixels. |
labelLimit | number |
Maximum allowed pixel width of axis tick labels. |
labelOverlap | anyOf(boolean , [‘parity’], [‘greedy’]) |
The strategy to use for resolving overlap of axis labels. If Default value: |
labelPadding | number |
The padding, in pixels, between axis and text labels. |
labels | boolean |
A boolean flag indicating if labels should be included as part of the axis. Default value: |
maxExtent | number |
The maximum extent in pixels that axis ticks and labels should use. This determines a maximum offset value for axis titles. Default value: |
minExtent | number |
The minimum extent in pixels that axis ticks and labels should use. This determines a minimum offset value for axis titles. Default value: |
shortTimeLabels | boolean |
Whether month names and weekday names should be abbreviated. Default value: |
tickColor | string |
The color of the axis’s tick. |
tickRound | boolean |
Boolean flag indicating if pixel position values should be rounded to the nearest integer. |
tickSize | number |
The size in pixels of axis ticks. |
tickWidth | number |
The width, in pixels, of ticks. |
ticks | boolean |
Boolean value that determines whether the axis should include ticks. |
titleAlign | string |
Horizontal text alignment of axis titles. |
titleAngle | number |
Angle in degrees of axis titles. |
titleBaseline | string |
Vertical text baseline for axis titles. |
titleColor | string |
Color of the title, can be in hex color code or regular color name. |
titleFont | string |
Font of the title. (e.g., "Helvetica Neue" ). |
titleFontSize | number |
Font size of the title. |
titleFontWeight | FontWeight |
Font weight of the 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 | number |
Maximum allowed pixel width of axis titles. |
titleMaxLength | number |
Max length for axis title if the title is automatically generated from the field’s description. |
titlePadding | number |
The padding, in pixels, between title and axis. |
titleX | number |
X-coordinate of the axis title relative to the axis group. |
titleY | number |
Y-coordinate of the axis title relative to the axis group. |
Legend Configuration¶
Legend properties can be configured using Chart.configure_legend()
,
which has the following properties:
Property | Type | Description |
---|---|---|
cornerRadius | number |
Corner radius for the full legend. |
entryPadding | number |
Padding (in pixels) between legend entries in a symbol legend. |
fillColor | string |
Background fill color for the full legend. |
gradientHeight | number |
The height of the gradient, in pixels. |
gradientLabelBaseline | string |
Text baseline for color ramp gradient labels. |
gradientLabelLimit | number |
The maximum allowed length in pixels of color ramp gradient labels. |
gradientLabelOffset | number |
Vertical offset in pixels for color ramp gradient labels. |
gradientStrokeColor | string |
The color of the gradient stroke, can be in hex color code or regular color name. |
gradientStrokeWidth | number |
The width of the gradient stroke, in pixels. |
gradientWidth | number |
The width of the gradient, in pixels. |
labelAlign | string |
The alignment of the legend label, can be left, middle or right. |
labelBaseline | string |
The position of the baseline of legend label, can be top, middle or bottom. |
labelColor | string |
The color of the legend label, can be in hex color code or regular color name. |
labelFont | string |
The font of the legend label. |
labelFontSize | number |
The font size of legend label. Default value: |
labelLimit | number |
Maximum allowed pixel width of axis tick labels. |
labelOffset | number |
The offset of the legend label. |
offset | number |
The offset, in pixels, by which to displace the legend from the edge of the enclosing group or data rectangle. Default value: |
orient | LegendOrient |
The orientation of the legend, which determines how the legend is positioned within the scene. One of “left”, “right”, “top-left”, “top-right”, “bottom-left”, “bottom-right”, “none”. Default value: |
padding | number |
The padding, in pixels, between the legend and axis. |
shortTimeLabels | boolean |
Whether month names and weekday names should be abbreviated. Default value: |
strokeColor | string |
Border stroke color for the full legend. |
strokeDash | array(number ) |
Border stroke dash pattern for the full legend. |
strokeWidth | number |
Border stroke width for the full legend. |
symbolColor | string |
The color of the legend symbol, |
symbolSize | number |
The size of the legend symbol, in pixels. |
symbolStrokeWidth | number |
The width of the symbol’s stroke. |
symbolType | string |
Default shape type (such as “circle”) for legend symbols. |
titleAlign | string |
Horizontal text alignment for legend titles. |
titleBaseline | string |
Vertical text baseline for legend titles. |
titleColor | string |
The color of the legend title, can be in hex color code or regular color name. |
titleFont | string |
The font of the legend title. |
titleFontSize | number |
The font size of the legend title. |
titleFontWeight | FontWeight |
The font weight of the legend 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 | number |
Maximum allowed pixel width of axis titles. |
titlePadding | number |
The padding, in pixels, between title and legend. |
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()
Each of the above methods accepts the following properties:
Property | Type | Description |
---|---|---|
align | HorizontalAlign |
The horizontal alignment of the text. One of "left" , "right" , "center" . |
angle | number |
The rotation angle of the text, in degrees. |
baseline | VerticalAlign |
The vertical alignment of the text. One of Default value: |
color | string |
Default color. Note that Default value: ■ Note: This property cannot be used in a style config. |
cornerRadius | number |
The radius in pixels of rounded rectangle corners. Default value: |
cursor | Cursor |
The mouse cursor used over the mark. Any valid CSS cursor type can be used. |
dir | Dir |
The direction of the text. One of Default value: |
dx | number |
The horizontal offset, in pixels, between the text label and its anchor point. The offset is applied after rotation by the angle property. |
dy | number |
The vertical offset, in pixels, between the text label and its anchor point. The offset is applied after rotation by the angle property. |
ellipsis | string |
The ellipsis string for text truncated in response to the limit parameter. Default value: |
fill | string |
Default Fill Color. This has higher precedence than Default value: (None) |
fillOpacity | number |
The fill opacity (value between [0,1]). Default value: |
filled | boolean |
Whether the mark’s color should be used as fill color instead of stroke color. Default value: Applicable for: Note: This property cannot be used in a style config. |
font | string |
The typeface to set the text in (e.g., "Helvetica Neue" ). |
fontSize | number |
The font size, in pixels. |
fontStyle | FontStyle |
The font style (e.g., "italic" ). |
fontWeight | FontWeight |
The font weight.
This can be either a string (e.g "bold" , "normal" ) or a number (100 , 200 , 300 , …, 900 where "normal" = 400 and "bold" = 700 ). |
href | string |
A URL to load upon mouse click. If defined, the mark acts as a hyperlink. |
interpolate | Interpolate |
The line interpolation method to use for line and area marks. One of the following:
|
limit | number |
The maximum length of the text mark in pixels. The text value will be automatically truncated if the rendered size exceeds the limit. Default value: |
opacity | number |
The overall opacity (value between [0,1]). Default value: |
orient | Orient |
The orientation of a non-stacked bar, tick, area, and line charts. The value is either horizontal (default) or vertical.
|
radius | number |
Polar coordinate radial offset, in pixels, of the text label from the origin determined by the x and y properties. |
shape | string |
The default symbol shape to use. One of: Default value: |
size | number |
The pixel area each the point/circle/square. For example: in the case of circles, the radius is determined in part by the square root of the size value. Default value: |
stroke | string |
Default Stroke Color. This has higher precedence than Default value: (None) |
strokeCap | StrokeCap |
The stroke cap for line ending style. One of Default value: |
strokeDash | array(number ) |
An array of alternating stroke, space lengths for creating dashed or dotted lines. |
strokeDashOffset | number |
The offset (in pixels) into which to begin drawing with the stroke dash array. |
strokeJoin | StrokeJoin |
The stroke line join method. One of Default value: |
strokeMiterLimit | number |
The miter limit at which to bevel a line join. |
strokeOpacity | number |
The stroke opacity (value between [0,1]). Default value: |
strokeWidth | number |
The stroke width, in pixels. |
tension | number |
Depending on the interpolation type, sets the tension parameter (for line and area marks). |
text | string |
Placeholder text if the text channel is not specified |
theta | number |
Polar coordinate angle, in radians, of the text label from the origin determined by the x and y properties. Values for theta follow the same convention of arc mark startAngle and endAngle properties: angles are measured in radians, with 0 indicating “north”. |
tooltip | – | The tooltip text to show upon mouse hover. |
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 | number |
Default inner padding for Default value: |
bandPaddingOuter | number |
Default outer padding for x and y band-ordinal scales.
If not specified, by default, band scale’s paddingOuter is paddingInner/2. |
clamp | boolean |
If true, values that exceed the data domain are clamped to either the minimum or maximum range value |
continuousPadding | number |
Default padding for continuous scales. Default: |
maxBandSize | number |
The default max value for mapping quantitative fields to bar’s size/bandSize. If undefined (default), we will use the scale’s |
maxFontSize | number |
The default max value for mapping quantitative fields to text’s size/fontSize. Default value: |
maxOpacity | number |
Default max opacity for mapping a field to opacity. Default value: |
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: |
minBandSize | number |
The default min value for mapping quantitative fields to bar and tick’s size/bandSize scale with zero=false. Default value: |
minFontSize | number |
The default min value for mapping quantitative fields to tick’s size/fontSize scale with zero=false Default value: |
minOpacity | number |
Default minimum opacity for mapping a field to opacity. Default value: |
minSize | number |
Default minimum value for point size scale with zero=false. Default value: |
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: |
pointPadding | number |
Default outer padding for Default value: |
rangeStep | [number, null] | Default range step for band and point scales of (1) the Default value: |
round | boolean |
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.) |
textXRangeStep | number |
Default range step for Default value: |
useUnaggregatedDomain | boolean |
Use the source data range before aggregation as scale domain instead of aggregated data for aggregate axis. This is equivalent to setting This property only works with aggregate functions that produce values within the raw data domain ( Default value: |
Scale Range Configuration¶
Scale ranges can be configured using Chart.configure_range()
, which has
the following properties:
Property | Type | Description |
---|---|---|
category | anyOf(array(string ), VgScheme ) |
Default range for nominal (categorical) fields. |
diverging | anyOf(array(string ), VgScheme ) |
Default range for diverging quantitative fields. |
heatmap | anyOf(array(string ), VgScheme ) |
Default range for quantitative heatmaps. |
ordinal | anyOf(array(string ), VgScheme ) |
Default range for ordinal fields. |
ramp | anyOf(array(string ), VgScheme ) |
Default range for quantitative and temporal fields. |
symbol | array(string ) |
Default range palette for the shape channel. |
Projection Configuration¶
Chart.configure_projection()
Property | Type | Description |
---|---|---|
center | array(number ) |
Sets the projection’s center to the specified center, a two-element array of longitude and latitude in degrees. Default value: |
clipAngle | number |
Sets the projection’s clipping circle radius to the specified angle in degrees. If null , switches to antimeridian cutting rather than small-circle clipping. |
clipExtent | array(array(number )) |
Sets the projection’s viewport clip extent to the specified bounds in pixels. The extent bounds are specified as an array [[x0, y0], [x1, y1]] , where x0 is the left-side of the viewport, y0 is the top, x1 is the right and y1 is the bottom. If null , no viewport clipping is performed. |
coefficient | number |
|
distance | number |
|
fraction | number |
|
lobes | number |
|
parallel | number |
|
precision | dict | Sets the threshold for the projection’s adaptive resampling to the specified value in pixels. This value corresponds to the Douglas–Peucker distance. If precision is not specified, returns the projection’s current resampling precision which defaults to √0.5 ≅ 0.70710… . |
radius | number |
|
ratio | number |
|
rotate | array(number ) |
Sets the projection’s three-axis rotation to the specified angles, which must be a two- or three-element array of numbers [ Default value: |
spacing | number |
|
tilt | number |
|
type | ProjectionType |
The cartographic projection to use. This value is case-insensitive, for example Default value: |
Selection Configuration¶
Chart.configure_selection()
Property | Type | Description |
---|---|---|
interval | IntervalSelectionConfig |
The default definition for an For instance, setting |
multi | MultiSelectionConfig |
The default definition for a For instance, setting |
single | SingleSelectionConfig |
The default definition for a For instance, setting |
View Configuration¶
Chart.configure_view()
Property | Type | Description |
---|---|---|
clip | boolean |
Whether the view should be clipped. |
fill | string |
The fill color. Default value: (none) |
fillOpacity | number |
The fill opacity (value between [0,1]). Default value: (none) |
height | number |
The default height of the single plot or each plot in a trellis plot when the visualization has a continuous (non-ordinal) y-scale with Default value: |
stroke | string |
The stroke color. Default value: (none) |
strokeDash | array(number ) |
An array of alternating stroke, space lengths for creating dashed or dotted lines. Default value: (none) |
strokeDashOffset | number |
The offset (in pixels) into which to begin drawing with the stroke dash array. Default value: (none) |
strokeJoin | StrokeJoin |
The stroke line join method. One of miter (default), round or bevel. Default value: ‘miter’ |
strokeMiterLimit | number |
The stroke line join method. One of miter (default), round or bevel. Default value: ‘miter’ |
strokeOpacity | number |
The stroke opacity (value between [0,1]). Default value: (none) |
strokeWidth | number |
The stroke width, in pixels. Default value: (none) |
width | number |
The default width of the single plot or each plot in a trellis plot when the visualization has a continuous (non-ordinal) x-scale or ordinal x-scale with Default value: |
Removing the border¶
By default, charts have both a grid and an outside border. To create a chart with no border, you will need to remove the both.
As an example, let’s start with a simple scatter plot.
import altair as alt
from vega_datasets import data
iris = data.iris()
alt.Chart(iris).mark_point().encode(
x='petalWidth',
y='petalLength',
color='species'
)
First remove the grid using the Chart.configure_axis()
method.
import altair as alt
from vega_datasets import data
iris = data.iris()
alt.Chart(iris).mark_point().encode(
x='petalWidth',
y='petalLength',
color='species'
).configure_axis(
grid=False
)
You’ll note that while the inside rules are gone, the outside border remains. Hide it by setting the strokeOpacity option on Chart.configure_view()
to 0.
import altair as alt
from vega_datasets import data
iris = data.iris()
alt.Chart(iris).mark_point().encode(
x='petalWidth',
y='petalLength',
color='species'
).configure_axis(
grid=False
).configure_view(
strokeWidth=0
)
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': {'height': 300, 'width': 400}}}
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': {'width': 400, 'height': 300}}, 'data': {'url': 'https://vega.github.io/vega-datasets/data/cars.json'}, 'mark': 'point', 'encoding': {'x': {'type': 'quantitative', 'field': 'Horsepower'}, 'y': {'type': 'quantitative', 'field': 'Miles_per_Gallon'}}, '$schema': 'https://vega.github.io/schema/vega-lite/v2.6.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': {'width': 400, 'height': 300}}, 'data': {'url': 'https://vega.github.io/vega-datasets/data/cars.json'}, 'mark': 'point', 'encoding': {'x': {'type': 'quantitative', 'field': 'Horsepower'}, 'y': {'type': 'quantitative', 'field': 'Miles_per_Gallon'}}, '$schema': 'https://vega.github.io/schema/vega-lite/v2.6.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://vega.github.io/vega-datasets/data/cars.json'}, 'mark': 'point', 'encoding': {'x': {'type': 'quantitative', 'field': 'Horsepower'}, 'y': {'type': 'quantitative', 'field': 'Miles_per_Gallon'}}, '$schema': 'https://vega.github.io/schema/vega-lite/v2.6.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.