Chart Classes
Chart classes provide high-level interfaces for creating and configuring different types of Datawrapper charts.
Base Chart
- class datawrapper.charts.BaseChart(*, chart_type: ~typing.Literal['column-chart', 'd3-area', 'd3-arrow-plot', 'd3-bars', 'd3-bars-stacked', 'd3-lines', 'd3-scatter-plot', 'locator-map', 'multiple-columns'], data: ~pandas.DataFrame | list[dict] = <factory>, transformations: ~datawrapper.charts.models.transforms.Transform | dict[str, ~typing.Any] = <factory>, title: str = '', intro: str = '', notes: str = '', source_name: str = '', source_url: str = '', byline: str = '', aria_description: str = '', hide_title: bool = False, language: str = 'en-US', theme: str = 'datawrapper', autoDarkMode: bool = False, dark_mode_invert: bool = True, get_the_data: bool = False, download_image: bool = False, download_pdf: bool = False, download_svg: bool = False, embed: bool = False, force_attribution: bool = False, share_buttons: bool = False, share_url: str = '', logo: bool = False, logo_id: str = '', custom: dict[str, ~typing.Any] = <factory>, forkable: bool = True, chart_id: str | None = None)[source]
Bases:
BaseModelA base class for Datawrapper charts published via its API.
- classmethod convert_column_format_dicts(data: dict[str, Any]) dict[str, Any][source]
Convert dictionary items in transformation to Transform objects.
- classmethod deserialize_data(csv_data: str | DataFrame) DataFrame[source]
Parse CSV string from Datawrapper API into DataFrame.
- Parameters:
csv_data – The CSV data from the chart data endpoint
- Returns:
DataFrame containing the parsed CSV data
- classmethod deserialize_model(api_response: dict[str, Any]) dict[str, Any][source]
Parse Datawrapper API response into model initialization data.
This base implementation handles common fields. Subclasses should override to handle chart-specific visualize settings.
- Parameters:
api_response – The JSON response from the chart metadata endpoint
- Returns:
Dictionary that can be used to initialize the model (without data)
- classmethod get(chart_id: str, access_token: str | None = None) BaseChart[source]
Fetch an existing chart from the Datawrapper API.
- Parameters:
chart_id – The ID of the chart to fetch
access_token – Optional Datawrapper API access token. If not provided, will use DATAWRAPPER_ACCESS_TOKEN environment variable.
- Returns:
An instance of the chart class with data populated from the API.
- Raises:
ValueError – If no access token is available or chart type doesn’t match.
Exception – If the API request fails.
- classmethod model_construct(_fields_set: set[str] | None = None, **values: Any) Self
Creates a new instance of the Model class with validated data.
Creates a new model setting __dict__ and __pydantic_fields_set__ from trusted or pre-validated data. Default values are respected, but no other validation is performed.
- !!! note
model_construct() generally respects the model_config.extra setting on the provided model. That is, if model_config.extra == ‘allow’, then all extra passed values are added to the model instance’s __dict__ and __pydantic_extra__ fields. If model_config.extra == ‘ignore’ (the default), then all extra passed values are ignored. Because no validation is performed with a call to model_construct(), having model_config.extra == ‘forbid’ does not result in an error if extra values are passed, but they will be ignored.
- Parameters:
_fields_set – A set of field names that were originally explicitly set during instantiation. If provided, this is directly used for the [model_fields_set][pydantic.BaseModel.model_fields_set] attribute. Otherwise, the field names from the values argument will be used.
values – Trusted or pre-validated data dictionary.
- Returns:
A new instance of the Model class with validated data.
- classmethod model_json_schema(by_alias: bool = True, ref_template: str = '#/$defs/{model}', schema_generator: type[GenerateJsonSchema] = <class 'pydantic.json_schema.GenerateJsonSchema'>, mode: Literal['validation', 'serialization']='validation', *, union_format: Literal['any_of', 'primitive_type_array']='any_of') dict[str, Any]
Generates a JSON schema for a model class.
- Parameters:
by_alias – Whether to use attribute aliases or not.
ref_template – The reference template.
union_format –
The format to use when combining schemas from unions together. Can be one of:
’any_of’: Use the [anyOf](https://json-schema.org/understanding-json-schema/reference/combining#anyOf)
keyword to combine schemas (the default). - ‘primitive_type_array’: Use the [type](https://json-schema.org/understanding-json-schema/reference/type) keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive type (string, boolean, null, integer or number) or contains constraints/metadata, falls back to any_of.
schema_generator – To override the logic used to generate the JSON schema, as a subclass of GenerateJsonSchema with your desired modifications
mode – The mode in which to generate the schema.
- Returns:
The JSON schema for the given model class.
- classmethod model_parametrized_name(params: tuple[type[Any], ...]) str
Compute the class name for parametrizations of generic classes.
This method can be overridden to achieve a custom naming scheme for generic BaseModels.
- Parameters:
params – Tuple of types of the class. Given a generic class Model with 2 type variables and a concrete model Model[str, int], the value (str, int) would be passed to params.
- Returns:
String representing the new class where params are passed to cls as type variables.
- Raises:
TypeError – Raised when trying to generate concrete names for non-generic models.
- classmethod model_rebuild(*, force: bool = False, raise_errors: bool = True, _parent_namespace_depth: int = 2, _types_namespace: MappingNamespace | None = None) bool | None
Try to rebuild the pydantic-core schema for the model.
This may be necessary when one of the annotations is a ForwardRef which could not be resolved during the initial attempt to build the schema, and automatic rebuilding fails.
- Parameters:
force – Whether to force the rebuilding of the model schema, defaults to False.
raise_errors – Whether to raise errors, defaults to True.
_parent_namespace_depth – The depth level of the parent namespace, defaults to 2.
_types_namespace – The types namespace, defaults to None.
- Returns:
Returns None if the schema is already “complete” and rebuilding was not required. If rebuilding _was_ required, returns True if rebuilding was successful, otherwise False.
- classmethod model_validate(obj: Any, *, strict: bool | None = None, extra: Literal['allow', 'ignore', 'forbid'] | None = None, from_attributes: bool | None = None, context: Any | None = None, by_alias: bool | None = None, by_name: bool | None = None) Self
Validate a pydantic model instance.
- Parameters:
obj – The object to validate.
strict – Whether to enforce types strictly.
extra – Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.
from_attributes – Whether to extract data from object attributes.
context – Additional context to pass to the validator.
by_alias – Whether to use the field’s alias when validating against the provided input data.
by_name – Whether to use the field’s name when validating against the provided input data.
- Raises:
ValidationError – If the object could not be validated.
- Returns:
The validated model instance.
- classmethod model_validate_json(json_data: str | bytes | bytearray, *, strict: bool | None = None, extra: Literal['allow', 'ignore', 'forbid'] | None = None, context: Any | None = None, by_alias: bool | None = None, by_name: bool | None = None) Self
- !!! abstract “Usage Documentation”
[JSON Parsing](../concepts/json.md#json-parsing)
Validate the given JSON data against the Pydantic model.
- Parameters:
json_data – The JSON data to validate.
strict – Whether to enforce types strictly.
extra – Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.
context – Extra variables to pass to the validator.
by_alias – Whether to use the field’s alias when validating against the provided input data.
by_name – Whether to use the field’s name when validating against the provided input data.
- Returns:
The validated Pydantic model.
- Raises:
ValidationError – If json_data is not a JSON string or the object could not be validated.
- classmethod model_validate_strings(obj: Any, *, strict: bool | None = None, extra: Literal['allow', 'ignore', 'forbid'] | None = None, context: Any | None = None, by_alias: bool | None = None, by_name: bool | None = None) Self
Validate the given object with string data against the Pydantic model.
- Parameters:
obj – The object containing string data to validate.
strict – Whether to enforce types strictly.
extra – Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.
context – Extra variables to pass to the validator.
by_alias – Whether to use the field’s alias when validating against the provided input data.
by_name – Whether to use the field’s name when validating against the provided input data.
- Returns:
The validated Pydantic model.
- classmethod warn_on_unrecognized_fields(data: dict[str, Any]) dict[str, Any][source]
Warn users about unrecognized fields that don’t match model fields or aliases.
This validator checks incoming data against the model’s defined fields and their aliases, issuing warnings for any keys that don’t match. This helps catch typos and misunderstandings about the API without breaking initialization.
- copy(*, include: AbstractSetIntStr | MappingIntStrAny | None = None, exclude: AbstractSetIntStr | MappingIntStrAny | None = None, update: Dict[str, Any] | None = None, deep: bool = False) Self
Returns a copy of the model.
- !!! warning “Deprecated”
This method is now deprecated; use model_copy instead.
If you need include or exclude, use:
`python {test="skip" lint="skip"} data = self.model_dump(include=include, exclude=exclude, round_trip=True) data = {**data, **(update or {})} copied = self.model_validate(data) `- Parameters:
include – Optional set or mapping specifying which fields to include in the copied model.
exclude – Optional set or mapping specifying which fields to exclude in the copied model.
update – Optional dictionary of field-value pairs to override field values in the copied model.
deep – If True, the values of fields that are Pydantic models will be deep-copied.
- Returns:
A copy of the model with included, excluded and updated fields as specified.
- create(access_token: str | None = None, folder_id: int | None = None) BaseChart[source]
Create a new chart via the Datawrapper API.
- Parameters:
access_token – Optional Datawrapper API access token. If not provided, will use DATAWRAPPER_ACCESS_TOKEN environment variable.
folder_id – Optional folder ID to create the chart in.
- Returns:
Self, to enable method chaining. The chart ID is stored in self.chart_id.
- Raises:
ValueError – If no access token is available or API returns invalid response.
Exception – If the API request fails.
- delete(access_token: str | None = None) bool[source]
Delete the chart via the Datawrapper API.
- Parameters:
access_token – Optional Datawrapper API access token. If not provided, will use DATAWRAPPER_ACCESS_TOKEN environment variable.
- Returns:
True if the chart was deleted successfully.
- Raises:
ValueError – If no chart_id is set or no access token is available.
Exception – If the API request fails.
- display(access_token: str | None = None) IFrame[source]
Display the chart as an IFrame in a Jupyter notebook.
- Parameters:
access_token – Optional Datawrapper API access token. If not provided, will use DATAWRAPPER_ACCESS_TOKEN environment variable.
- Returns:
An IPython.display.IFrame object displaying the chart.
- Raises:
ValueError – If no chart_id is set or no access token is available.
Exception – If the API request fails.
- duplicate(access_token: str | None = None) BaseChart[source]
Duplicate the chart and create a new editable copy via the Datawrapper API.
- Parameters:
access_token – Optional Datawrapper API access token. If not provided, will use DATAWRAPPER_ACCESS_TOKEN environment variable.
- Returns:
A new BaseChart instance representing the duplicated chart.
- Raises:
ValueError – If no chart_id is set or no access token is available.
Exception – If the API request fails.
- export_pdf(*, width: int | None = None, height: int | None = None, plain: bool = False, unit: Literal['px', 'mm', 'inch'] = 'px', mode: Literal['rgb', 'cmyk'] = 'rgb', scale: int = 1, zoom: int = 2, transparent: bool = False, border_width: int = 0, border_color: str | None = None, logo: Literal['auto', 'on', 'off'] = 'auto', logo_id: str | None = None, dark: bool = False, ligatures: bool = True, full_vector: bool = False, download: bool = False, access_token: str | None = None, timeout: int = 30) bytes[source]
Export chart as PDF and return the raw bytes.
- Parameters:
width – Width of visualization. If not specified, uses chart width.
height – Height of visualization. If not specified, uses chart height.
plain – If True, exports only the visualization without header/footer.
unit – Unit for measurements: “px”, “mm”, or “inch”.
mode – Color mode: “rgb” or “cmyk”.
scale – Size multiplier that changes actual dimensions (e.g., 2 = 2x size).
zoom – Resolution multiplier for sharper output at same visual size (e.g., 2 = 2x DPI).
transparent – If True, exports with transparent background.
border_width – Margin around visualization.
border_color – Color of the border (e.g., “#FFFFFF”). If not specified, uses chart background color.
logo – Logo display mode: “auto”, “on”, or “off”.
logo_id – Custom logo ID (pattern: ^[a-zA-Z0-9-]+$).
dark – If True, exports in dark mode.
ligatures – If True (default), enables typography ligatures.
full_vector – If True, exports as full vector output.
download – If True, includes download headers in response.
access_token – Optional Datawrapper API access token.
timeout – Timeout for the API request in seconds.
- Returns:
Raw PDF document data as bytes.
- Raises:
ValueError – If no chart_id is set or invalid parameters provided.
Exception – If the API request fails.
Example
>>> chart = BarChart.get(chart_id="abc123") >>> pdf_data = chart.export_pdf(unit="mm", mode="cmyk") >>> Path("chart.pdf").write_bytes(pdf_data)
- export_png(*, width: int | None = None, height: int | None = None, plain: bool = False, scale: int = 1, zoom: int = 2, transparent: bool = False, border_width: int = 0, border_color: str | None = None, logo: Literal['auto', 'on', 'off'] = 'auto', logo_id: str | None = None, dark: bool = False, ligatures: bool = True, full_vector: bool = False, download: bool = False, access_token: str | None = None, timeout: int = 30) bytes[source]
Export chart as PNG and return the raw bytes.
- Parameters:
width – Width of visualization in pixels. If not specified, uses chart width.
height – Height of visualization in pixels. If not specified, uses chart height.
plain – If True, exports only the visualization without header/footer.
scale – Size multiplier that changes actual dimensions (e.g., 2 = 2x size).
zoom – Resolution multiplier for sharper output at same visual size (e.g., 2 = 2x DPI).
transparent – If True, exports with transparent background.
border_width – Margin around visualization in pixels.
border_color – Color of the border (e.g., “#FFFFFF”). If not specified, uses chart background color.
logo – Logo display mode: “auto”, “on”, or “off”.
logo_id – Custom logo ID (pattern: ^[a-zA-Z0-9-]+$).
dark – If True, exports in dark mode.
ligatures – If True (default), enables typography ligatures.
full_vector – If True, exports as full vector output.
download – If True, includes download headers in response.
access_token – Optional Datawrapper API access token.
timeout – Timeout for the API request in seconds.
- Returns:
Raw PNG image data as bytes.
- Raises:
ValueError – If no chart_id is set.
Exception – If the API request fails.
Example
>>> chart = LineChart.get(chart_id="abc123") >>> png_data = chart.export_png(zoom=3, transparent=True) >>> Path("chart.png").write_bytes(png_data)
- export_svg(*, width: int | None = None, height: int | None = None, plain: bool = False, scale: int = 1, zoom: int = 2, transparent: bool = False, border_width: int = 0, border_color: str | None = None, logo: Literal['auto', 'on', 'off'] = 'auto', logo_id: str | None = None, dark: bool = False, ligatures: bool = True, full_vector: bool = False, download: bool = False, access_token: str | None = None, timeout: int = 30) bytes[source]
Export chart as SVG and return the raw bytes.
- Parameters:
width – Width of visualization. If not specified, uses chart width.
height – Height of visualization. If not specified, uses chart height.
plain – If True, exports only the visualization without header/footer.
scale – Size multiplier that changes actual dimensions (e.g., 2 = 2x size).
zoom – Resolution multiplier for sharper output at same visual size (e.g., 2 = 2x DPI).
transparent – If True, exports with transparent background.
border_width – Margin around visualization in pixels.
border_color – Color of the border (e.g., “#FFFFFF”). If not specified, uses chart background color.
logo – Logo display mode: “auto”, “on”, or “off”.
logo_id – Custom logo ID (pattern: ^[a-zA-Z0-9-]+$).
dark – If True, exports in dark mode.
ligatures – If True (default), enables typography ligatures.
full_vector – If True, exports as full vector output.
download – If True, includes download headers in response.
access_token – Optional Datawrapper API access token.
timeout – Timeout for the API request in seconds.
- Returns:
Raw SVG document data as bytes.
- Raises:
ValueError – If no chart_id is set.
Exception – If the API request fails.
Example
>>> chart = ColumnChart.get(chart_id="abc123") >>> svg_data = chart.export_svg(plain=True) >>> Path("chart.svg").write_bytes(svg_data)
- fork(access_token: str | None = None) BaseChart[source]
Fork the chart and create an editable copy via the Datawrapper API.
- Parameters:
access_token – Optional Datawrapper API access token. If not provided, will use DATAWRAPPER_ACCESS_TOKEN environment variable.
- Returns:
A new BaseChart instance representing the forked chart.
- Raises:
ValueError – If no chart_id is set or no access token is available.
Exception – If the API request fails.
- get_display_urls(access_token: str | None = None) list[dict][source]
Get the URLs for the published chart, table or map.
- Parameters:
access_token – Optional Datawrapper API access token. If not provided, will use DATAWRAPPER_ACCESS_TOKEN environment variable.
- Returns:
A list of dictionaries containing the display URLs for the chart.
- Raises:
ValueError – If no chart_id is set or no access token is available.
Exception – If the API request fails.
- get_editor_url() str[source]
Get the Datawrapper editor URL for this chart.
- Returns:
The Datawrapper editor URL as a string.
- Raises:
ValueError – If no chart_id is set.
- get_iframe_code(responsive: bool = False, access_token: str | None = None) str[source]
Get the iframe embed code for the chart, table, or map.
- Parameters:
responsive – Whether to return responsive iframe code, by default False
access_token – Optional Datawrapper API access token. If not provided, will use DATAWRAPPER_ACCESS_TOKEN environment variable.
- Returns:
The iframe embed code as a string.
- Raises:
ValueError – If no chart_id is set or no access token is available.
Exception – If the API request fails.
- get_png_url() str[source]
Get the fallback PNG image URL for noscript tags.
- Returns:
//datawrapper.dwcdn.net/{chart_id}/full.png
- Return type:
The PNG image URL in the format https
- Raises:
ValueError – If no chart_id is set.
- get_public_url() str[source]
Get the public URL for the published chart.
- Returns:
//datawrapper.dwcdn.net/{chart_id}/
- Return type:
The public URL in the format https
- Raises:
ValueError – If no chart_id is set.
Note
This method returns the URL regardless of whether the chart is actually published. If the chart is not published, the URL will not be accessible. Use publish() to publish the chart before accessing this URL.
- model_copy(*, update: Mapping[str, Any] | None = None, deep: bool = False) Self
- !!! abstract “Usage Documentation”
[model_copy](../concepts/models.md#model-copy)
Returns a copy of the model.
- !!! note
The underlying instance’s [__dict__][object.__dict__] attribute is copied. This might have unexpected side effects if you store anything in it, on top of the model fields (e.g. the value of [cached properties][functools.cached_property]).
- Parameters:
update – Values to change/add in the new model. Note: the data is not validated before creating the new model. You should trust this data.
deep – Set to True to make a deep copy of the model.
- Returns:
New model instance.
- model_dump(*, mode: Literal['json', 'python'] | str = 'python', include: set[int] | set[str] | Mapping[int, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | Mapping[str, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | None = None, exclude: set[int] | set[str] | Mapping[int, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | Mapping[str, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | None = None, context: Any | None = None, by_alias: bool | None = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, exclude_computed_fields: bool = False, round_trip: bool = False, warnings: bool | Literal['none', 'warn', 'error'] = True, fallback: Callable[[Any], Any] | None = None, serialize_as_any: bool = False, polymorphic_serialization: bool | None = None) dict[str, Any]
- !!! abstract “Usage Documentation”
[model_dump](../concepts/serialization.md#python-mode)
Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
- Parameters:
mode – The mode in which to_python should run. If mode is ‘json’, the output will only contain JSON serializable types. If mode is ‘python’, the output may contain non-JSON-serializable Python objects.
include – A set of fields to include in the output.
exclude – A set of fields to exclude from the output.
context – Additional context to pass to the serializer.
by_alias – Whether to use the field’s alias in the dictionary key if defined.
exclude_unset – Whether to exclude fields that have not been explicitly set.
exclude_defaults – Whether to exclude fields that are set to their default value.
exclude_none – Whether to exclude fields that have a value of None.
exclude_computed_fields – Whether to exclude computed fields. While this can be useful for round-tripping, it is usually recommended to use the dedicated round_trip parameter instead.
round_trip – If True, dumped values should be valid as input for non-idempotent types such as Json[T].
warnings – How to handle serialization errors. False/”none” ignores them, True/”warn” logs errors, “error” raises a [PydanticSerializationError][pydantic_core.PydanticSerializationError].
fallback – A function to call when an unknown value is encountered. If not provided, a [PydanticSerializationError][pydantic_core.PydanticSerializationError] error is raised.
serialize_as_any – Whether to serialize fields with duck-typing serialization behavior.
polymorphic_serialization – Whether to use model and dataclass polymorphic serialization for this call.
- Returns:
A dictionary representation of the model.
- model_dump_json(*, indent: int | None = None, ensure_ascii: bool = False, include: set[int] | set[str] | Mapping[int, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | Mapping[str, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | None = None, exclude: set[int] | set[str] | Mapping[int, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | Mapping[str, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | None = None, context: Any | None = None, by_alias: bool | None = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, exclude_computed_fields: bool = False, round_trip: bool = False, warnings: bool | Literal['none', 'warn', 'error'] = True, fallback: Callable[[Any], Any] | None = None, serialize_as_any: bool = False, polymorphic_serialization: bool | None = None) str
- !!! abstract “Usage Documentation”
[model_dump_json](../concepts/serialization.md#json-mode)
Generates a JSON representation of the model using Pydantic’s to_json method.
- Parameters:
indent – Indentation to use in the JSON output. If None is passed, the output will be compact.
ensure_ascii – If True, the output is guaranteed to have all incoming non-ASCII characters escaped. If False (the default), these characters will be output as-is.
include – Field(s) to include in the JSON output.
exclude – Field(s) to exclude from the JSON output.
context – Additional context to pass to the serializer.
by_alias – Whether to serialize using field aliases.
exclude_unset – Whether to exclude fields that have not been explicitly set.
exclude_defaults – Whether to exclude fields that are set to their default value.
exclude_none – Whether to exclude fields that have a value of None.
exclude_computed_fields – Whether to exclude computed fields. While this can be useful for round-tripping, it is usually recommended to use the dedicated round_trip parameter instead.
round_trip – If True, dumped values should be valid as input for non-idempotent types such as Json[T].
warnings – How to handle serialization errors. False/”none” ignores them, True/”warn” logs errors, “error” raises a [PydanticSerializationError][pydantic_core.PydanticSerializationError].
fallback – A function to call when an unknown value is encountered. If not provided, a [PydanticSerializationError][pydantic_core.PydanticSerializationError] error is raised.
serialize_as_any – Whether to serialize fields with duck-typing serialization behavior.
polymorphic_serialization – Whether to use model and dataclass polymorphic serialization for this call.
- Returns:
A JSON string representation of the model.
- model_post_init(context: Any, /) None
Override this method to perform additional initialization after __init__ and model_construct. This is useful if you want to do some validation that requires the entire model to be initialized.
- publish(access_token: str | None = None) BaseChart[source]
Publish the chart via the Datawrapper API.
- Parameters:
access_token – Optional Datawrapper API access token. If not provided, will use DATAWRAPPER_ACCESS_TOKEN environment variable.
- Returns:
Self, to enable method chaining.
- Raises:
ValueError – If no chart_id is set or no access token is available.
Exception – If the API request fails or publishing fails.
- serialize_data() str | None[source]
Convert data to CSV string for API upload.
- Returns:
CSV string representation of the data, or None if data is empty.
- update(access_token: str | None = None) BaseChart[source]
Update an existing chart via the Datawrapper API.
- Parameters:
access_token – Optional Datawrapper API access token. If not provided, will use DATAWRAPPER_ACCESS_TOKEN environment variable.
- Returns:
Self, to enable method chaining.
- Raises:
ValueError – If no chart_id is set or no access token is available.
Exception – If the API request fails.
- aria_description: str
The alternative text for screen readers
- auto_dark_mode: bool
Whether the chart should automatically flip to dark mode when the user’s system is in dark mode
- byline: str
The byline that appears below the chart
- chart_id: str | None
The chart ID after creation (populated by create() method)
- chart_type: Literal['column-chart', 'd3-area', 'd3-arrow-plot', 'd3-bars', 'd3-bars-stacked', 'd3-lines', 'd3-scatter-plot', 'locator-map', 'multiple-columns']
The type of datawrapper chart to create
- custom: dict[str, Any]
A dictionary of custom tags to attach to the chart
- dark_mode_invert: bool
Whether to invert colors in dark mode
- data: DataFrame | list[dict]
The data to use for the chart
- download_image: bool
Whether to allow PNG download
- download_pdf: bool
Whether to allow PDF download
- download_svg: bool
Whether to allow SVG download
- embed: bool
Whether to allow embedding
- force_attribution: bool
Whether to attribute the chart to datawrapper
- forkable: bool
Whether to allow other users to fork this visualization
- get_the_data: bool
Whether to allow data downloads
- hide_title: bool
Whether or not to hide the title
- intro: str
The intro text that appears above the chart
- language: str
The locale of the chart, which defines decimal and thousand separators as well as translations of month and weekday names.
- logo: bool
Whether to show a logo
- logo_id: str
The id of the logo to show
- model_config = {'arbitrary_types_allowed': True, 'json_schema_extra': {'examples': [{'chart_type': 'd3-lines', 'language': 'en-US', 'source_name': 'Reuters', 'title': 'Sample Chart Title'}, {'chart_type': 'd3-lines', 'language': 'en-US', 'source_name': 'Reuters', 'title': 'Sample Chart Title', 'transformations': {'column-format': [{'column': 'sales', 'number-prepend': '$', 'type': 'number'}], 'column-order': [0, 1, 2], 'external-data': '', 'horizontal-header': True, 'transpose': False, 'upload-method': 'copy', 'use-datawrapper-cdn': True, 'vertical-header': True}}, {'chart_type': 'd3-lines', 'language': 'en-US', 'source_name': 'Reuters', 'title': 'Sample Chart Title', 'transformations': {'column-format': [{'column': 'sales', 'number-prepend': '$', 'type': 'number'}], 'column-order': [0, 1, 2], 'external-data': '', 'horizontal-header': True, 'transpose': False, 'upload-method': 'copy', 'use-datawrapper-cdn': True, 'vertical-header': True}}]}, 'populate_by_name': True, 'use_enum_values': True, 'validate_assignment': True, 'validate_by_alias': True, 'validate_by_name': True, 'validate_default': True}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- property model_extra: dict[str, Any] | None
Get extra fields set during validation.
- Returns:
A dictionary of extra fields, or None if config.extra is not set to “allow”.
- property model_fields_set: set[str]
Returns the set of fields that have been explicitly set on this model instance.
- Returns:
- A set of strings representing the fields that have been set,
i.e. that were not filled from defaults.
- notes: str
The footnotes that appear below the chart
Whether to show social media share buttons
What URL to share
- source_name: str
The source name that appears below the chart
- source_url: str
The source URL that appears below the chart
- theme: str
The theme of the chart
- title: str
The headline that appears above the chart
- transformations: Transform | dict[str, Any]
The metadata options for the data columns in the “Check and Describe” tab
Area Chart
- class datawrapper.charts.AreaChart(*, chart_type: Literal['d3-area'] = 'd3-area', data: DataFrame | list[dict] = <factory>, transformations: Transform | dict[str, ~typing.Any]=<factory>, title: str = '', intro: str = '', notes: str = '', source_name: str = '', source_url: str = '', byline: str = '', aria_description: str = '', hide_title: bool = False, language: str = 'en-US', theme: str = 'datawrapper', autoDarkMode: bool = False, dark_mode_invert: bool = True, get_the_data: bool = False, download_image: bool = False, download_pdf: bool = False, download_svg: bool = False, embed: bool = False, force_attribution: bool = False, share_buttons: bool = False, share_url: str = '', logo: bool = False, logo_id: str = '', custom: dict[str, ~typing.Any]=<factory>, forkable: bool = True, chart_id: str | None = None, text_annotations: Any, ~typing.Any]]=<factory>, range_annotations: Any, ~typing.Any]]=<factory>, custom_ticks_x: list[Any] | None = None, custom_ticks_y: list[Any] | None = None, custom_range_x: list[~typing.Any] | tuple[~typing.Any, ~typing.Any] | None=None, custom_range_y: list[~typing.Any] | tuple[~typing.Any, ~typing.Any] | None=None, x_grid_format: DateFormat | NumberFormat | str | None = None, y_grid_format: NumberFormat | str | None = None, x_grid: GridDisplay | str | bool | None = 'off', y_grid: GridDisplay | str | bool | None = 'on', y_grid_labels: GridLabelPosition | str = 'auto', y_grid_label_align: GridLabelAlign | str = 'left', base_color: str | int = 0, area_opacity: float = 0.8, interpolation: LineInterpolation | str = 'linear', sort_areas: Literal['keep', 'asc', 'desc']='keep', stack_areas: bool = False, stack_to_100: bool = False, area_separator_lines: bool = False, area_separator_color: str | int = '#4682b4', color_category: dict[str, str]=<factory>, show_color_key: bool = False, show_tooltips: bool = True, tooltip_x_format: DateFormat | NumberFormat | str = '', tooltip_number_format: DateFormat | NumberFormat | str = '', plot_height_mode: PlotHeightMode | str = 'fixed', plot_height_fixed: int | float = 300, plot_height_ratio: float = 0.5)[source]
Bases:
GridDisplayMixin,GridFormatMixin,CustomRangeMixin,CustomTicksMixin,AnnotationsMixin,BaseChartA base class for the Datawrapper API’s area chart.
- classmethod convert_column_format_dicts(data: dict[str, Any]) dict[str, Any]
Convert dictionary items in transformation to Transform objects.
- classmethod deserialize_data(csv_data: str | DataFrame) DataFrame
Parse CSV string from Datawrapper API into DataFrame.
- Parameters:
csv_data – The CSV data from the chart data endpoint
- Returns:
DataFrame containing the parsed CSV data
- classmethod deserialize_model(api_response: dict[str, Any]) dict[str, Any][source]
Parse Datawrapper API response including area chart specific fields.
- Parameters:
api_response – The JSON response from the chart metadata endpoint
- Returns:
Dictionary that can be used to initialize the AreaChart model
- classmethod get(chart_id: str, access_token: str | None = None) BaseChart
Fetch an existing chart from the Datawrapper API.
- Parameters:
chart_id – The ID of the chart to fetch
access_token – Optional Datawrapper API access token. If not provided, will use DATAWRAPPER_ACCESS_TOKEN environment variable.
- Returns:
An instance of the chart class with data populated from the API.
- Raises:
ValueError – If no access token is available or chart type doesn’t match.
Exception – If the API request fails.
- classmethod model_construct(_fields_set: set[str] | None = None, **values: Any) Self
Creates a new instance of the Model class with validated data.
Creates a new model setting __dict__ and __pydantic_fields_set__ from trusted or pre-validated data. Default values are respected, but no other validation is performed.
- !!! note
model_construct() generally respects the model_config.extra setting on the provided model. That is, if model_config.extra == ‘allow’, then all extra passed values are added to the model instance’s __dict__ and __pydantic_extra__ fields. If model_config.extra == ‘ignore’ (the default), then all extra passed values are ignored. Because no validation is performed with a call to model_construct(), having model_config.extra == ‘forbid’ does not result in an error if extra values are passed, but they will be ignored.
- Parameters:
_fields_set – A set of field names that were originally explicitly set during instantiation. If provided, this is directly used for the [model_fields_set][pydantic.BaseModel.model_fields_set] attribute. Otherwise, the field names from the values argument will be used.
values – Trusted or pre-validated data dictionary.
- Returns:
A new instance of the Model class with validated data.
- classmethod model_json_schema(by_alias: bool = True, ref_template: str = '#/$defs/{model}', schema_generator: type[GenerateJsonSchema] = <class 'pydantic.json_schema.GenerateJsonSchema'>, mode: Literal['validation', 'serialization']='validation', *, union_format: Literal['any_of', 'primitive_type_array']='any_of') dict[str, Any]
Generates a JSON schema for a model class.
- Parameters:
by_alias – Whether to use attribute aliases or not.
ref_template – The reference template.
union_format –
The format to use when combining schemas from unions together. Can be one of:
’any_of’: Use the [anyOf](https://json-schema.org/understanding-json-schema/reference/combining#anyOf)
keyword to combine schemas (the default). - ‘primitive_type_array’: Use the [type](https://json-schema.org/understanding-json-schema/reference/type) keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive type (string, boolean, null, integer or number) or contains constraints/metadata, falls back to any_of.
schema_generator – To override the logic used to generate the JSON schema, as a subclass of GenerateJsonSchema with your desired modifications
mode – The mode in which to generate the schema.
- Returns:
The JSON schema for the given model class.
- classmethod model_parametrized_name(params: tuple[type[Any], ...]) str
Compute the class name for parametrizations of generic classes.
This method can be overridden to achieve a custom naming scheme for generic BaseModels.
- Parameters:
params – Tuple of types of the class. Given a generic class Model with 2 type variables and a concrete model Model[str, int], the value (str, int) would be passed to params.
- Returns:
String representing the new class where params are passed to cls as type variables.
- Raises:
TypeError – Raised when trying to generate concrete names for non-generic models.
- classmethod model_rebuild(*, force: bool = False, raise_errors: bool = True, _parent_namespace_depth: int = 2, _types_namespace: MappingNamespace | None = None) bool | None
Try to rebuild the pydantic-core schema for the model.
This may be necessary when one of the annotations is a ForwardRef which could not be resolved during the initial attempt to build the schema, and automatic rebuilding fails.
- Parameters:
force – Whether to force the rebuilding of the model schema, defaults to False.
raise_errors – Whether to raise errors, defaults to True.
_parent_namespace_depth – The depth level of the parent namespace, defaults to 2.
_types_namespace – The types namespace, defaults to None.
- Returns:
Returns None if the schema is already “complete” and rebuilding was not required. If rebuilding _was_ required, returns True if rebuilding was successful, otherwise False.
- classmethod model_validate(obj: Any, *, strict: bool | None = None, extra: Literal['allow', 'ignore', 'forbid'] | None = None, from_attributes: bool | None = None, context: Any | None = None, by_alias: bool | None = None, by_name: bool | None = None) Self
Validate a pydantic model instance.
- Parameters:
obj – The object to validate.
strict – Whether to enforce types strictly.
extra – Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.
from_attributes – Whether to extract data from object attributes.
context – Additional context to pass to the validator.
by_alias – Whether to use the field’s alias when validating against the provided input data.
by_name – Whether to use the field’s name when validating against the provided input data.
- Raises:
ValidationError – If the object could not be validated.
- Returns:
The validated model instance.
- classmethod model_validate_json(json_data: str | bytes | bytearray, *, strict: bool | None = None, extra: Literal['allow', 'ignore', 'forbid'] | None = None, context: Any | None = None, by_alias: bool | None = None, by_name: bool | None = None) Self
- !!! abstract “Usage Documentation”
[JSON Parsing](../concepts/json.md#json-parsing)
Validate the given JSON data against the Pydantic model.
- Parameters:
json_data – The JSON data to validate.
strict – Whether to enforce types strictly.
extra – Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.
context – Extra variables to pass to the validator.
by_alias – Whether to use the field’s alias when validating against the provided input data.
by_name – Whether to use the field’s name when validating against the provided input data.
- Returns:
The validated Pydantic model.
- Raises:
ValidationError – If json_data is not a JSON string or the object could not be validated.
- classmethod model_validate_strings(obj: Any, *, strict: bool | None = None, extra: Literal['allow', 'ignore', 'forbid'] | None = None, context: Any | None = None, by_alias: bool | None = None, by_name: bool | None = None) Self
Validate the given object with string data against the Pydantic model.
- Parameters:
obj – The object containing string data to validate.
strict – Whether to enforce types strictly.
extra – Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.
context – Extra variables to pass to the validator.
by_alias – Whether to use the field’s alias when validating against the provided input data.
by_name – Whether to use the field’s name when validating against the provided input data.
- Returns:
The validated Pydantic model.
- classmethod validate_interpolation(v: LineInterpolation | str) LineInterpolation | str[source]
Validate that interpolation is a valid LineInterpolation value.
- classmethod validate_plot_height_mode(v: PlotHeightMode | str) PlotHeightMode | str[source]
Validate that plot_height_mode is a valid PlotHeightMode value.
- classmethod warn_on_unrecognized_fields(data: dict[str, Any]) dict[str, Any]
Warn users about unrecognized fields that don’t match model fields or aliases.
This validator checks incoming data against the model’s defined fields and their aliases, issuing warnings for any keys that don’t match. This helps catch typos and misunderstandings about the API without breaking initialization.
- copy(*, include: AbstractSetIntStr | MappingIntStrAny | None = None, exclude: AbstractSetIntStr | MappingIntStrAny | None = None, update: Dict[str, Any] | None = None, deep: bool = False) Self
Returns a copy of the model.
- !!! warning “Deprecated”
This method is now deprecated; use model_copy instead.
If you need include or exclude, use:
`python {test="skip" lint="skip"} data = self.model_dump(include=include, exclude=exclude, round_trip=True) data = {**data, **(update or {})} copied = self.model_validate(data) `- Parameters:
include – Optional set or mapping specifying which fields to include in the copied model.
exclude – Optional set or mapping specifying which fields to exclude in the copied model.
update – Optional dictionary of field-value pairs to override field values in the copied model.
deep – If True, the values of fields that are Pydantic models will be deep-copied.
- Returns:
A copy of the model with included, excluded and updated fields as specified.
- create(access_token: str | None = None, folder_id: int | None = None) BaseChart
Create a new chart via the Datawrapper API.
- Parameters:
access_token – Optional Datawrapper API access token. If not provided, will use DATAWRAPPER_ACCESS_TOKEN environment variable.
folder_id – Optional folder ID to create the chart in.
- Returns:
Self, to enable method chaining. The chart ID is stored in self.chart_id.
- Raises:
ValueError – If no access token is available or API returns invalid response.
Exception – If the API request fails.
- delete(access_token: str | None = None) bool
Delete the chart via the Datawrapper API.
- Parameters:
access_token – Optional Datawrapper API access token. If not provided, will use DATAWRAPPER_ACCESS_TOKEN environment variable.
- Returns:
True if the chart was deleted successfully.
- Raises:
ValueError – If no chart_id is set or no access token is available.
Exception – If the API request fails.
- display(access_token: str | None = None) IFrame
Display the chart as an IFrame in a Jupyter notebook.
- Parameters:
access_token – Optional Datawrapper API access token. If not provided, will use DATAWRAPPER_ACCESS_TOKEN environment variable.
- Returns:
An IPython.display.IFrame object displaying the chart.
- Raises:
ValueError – If no chart_id is set or no access token is available.
Exception – If the API request fails.
- duplicate(access_token: str | None = None) BaseChart
Duplicate the chart and create a new editable copy via the Datawrapper API.
- Parameters:
access_token – Optional Datawrapper API access token. If not provided, will use DATAWRAPPER_ACCESS_TOKEN environment variable.
- Returns:
A new BaseChart instance representing the duplicated chart.
- Raises:
ValueError – If no chart_id is set or no access token is available.
Exception – If the API request fails.
- export_pdf(*, width: int | None = None, height: int | None = None, plain: bool = False, unit: Literal['px', 'mm', 'inch'] = 'px', mode: Literal['rgb', 'cmyk'] = 'rgb', scale: int = 1, zoom: int = 2, transparent: bool = False, border_width: int = 0, border_color: str | None = None, logo: Literal['auto', 'on', 'off'] = 'auto', logo_id: str | None = None, dark: bool = False, ligatures: bool = True, full_vector: bool = False, download: bool = False, access_token: str | None = None, timeout: int = 30) bytes
Export chart as PDF and return the raw bytes.
- Parameters:
width – Width of visualization. If not specified, uses chart width.
height – Height of visualization. If not specified, uses chart height.
plain – If True, exports only the visualization without header/footer.
unit – Unit for measurements: “px”, “mm”, or “inch”.
mode – Color mode: “rgb” or “cmyk”.
scale – Size multiplier that changes actual dimensions (e.g., 2 = 2x size).
zoom – Resolution multiplier for sharper output at same visual size (e.g., 2 = 2x DPI).
transparent – If True, exports with transparent background.
border_width – Margin around visualization.
border_color – Color of the border (e.g., “#FFFFFF”). If not specified, uses chart background color.
logo – Logo display mode: “auto”, “on”, or “off”.
logo_id – Custom logo ID (pattern: ^[a-zA-Z0-9-]+$).
dark – If True, exports in dark mode.
ligatures – If True (default), enables typography ligatures.
full_vector – If True, exports as full vector output.
download – If True, includes download headers in response.
access_token – Optional Datawrapper API access token.
timeout – Timeout for the API request in seconds.
- Returns:
Raw PDF document data as bytes.
- Raises:
ValueError – If no chart_id is set or invalid parameters provided.
Exception – If the API request fails.
Example
>>> chart = BarChart.get(chart_id="abc123") >>> pdf_data = chart.export_pdf(unit="mm", mode="cmyk") >>> Path("chart.pdf").write_bytes(pdf_data)
- export_png(*, width: int | None = None, height: int | None = None, plain: bool = False, scale: int = 1, zoom: int = 2, transparent: bool = False, border_width: int = 0, border_color: str | None = None, logo: Literal['auto', 'on', 'off'] = 'auto', logo_id: str | None = None, dark: bool = False, ligatures: bool = True, full_vector: bool = False, download: bool = False, access_token: str | None = None, timeout: int = 30) bytes
Export chart as PNG and return the raw bytes.
- Parameters:
width – Width of visualization in pixels. If not specified, uses chart width.
height – Height of visualization in pixels. If not specified, uses chart height.
plain – If True, exports only the visualization without header/footer.
scale – Size multiplier that changes actual dimensions (e.g., 2 = 2x size).
zoom – Resolution multiplier for sharper output at same visual size (e.g., 2 = 2x DPI).
transparent – If True, exports with transparent background.
border_width – Margin around visualization in pixels.
border_color – Color of the border (e.g., “#FFFFFF”). If not specified, uses chart background color.
logo – Logo display mode: “auto”, “on”, or “off”.
logo_id – Custom logo ID (pattern: ^[a-zA-Z0-9-]+$).
dark – If True, exports in dark mode.
ligatures – If True (default), enables typography ligatures.
full_vector – If True, exports as full vector output.
download – If True, includes download headers in response.
access_token – Optional Datawrapper API access token.
timeout – Timeout for the API request in seconds.
- Returns:
Raw PNG image data as bytes.
- Raises:
ValueError – If no chart_id is set.
Exception – If the API request fails.
Example
>>> chart = LineChart.get(chart_id="abc123") >>> png_data = chart.export_png(zoom=3, transparent=True) >>> Path("chart.png").write_bytes(png_data)
- export_svg(*, width: int | None = None, height: int | None = None, plain: bool = False, scale: int = 1, zoom: int = 2, transparent: bool = False, border_width: int = 0, border_color: str | None = None, logo: Literal['auto', 'on', 'off'] = 'auto', logo_id: str | None = None, dark: bool = False, ligatures: bool = True, full_vector: bool = False, download: bool = False, access_token: str | None = None, timeout: int = 30) bytes
Export chart as SVG and return the raw bytes.
- Parameters:
width – Width of visualization. If not specified, uses chart width.
height – Height of visualization. If not specified, uses chart height.
plain – If True, exports only the visualization without header/footer.
scale – Size multiplier that changes actual dimensions (e.g., 2 = 2x size).
zoom – Resolution multiplier for sharper output at same visual size (e.g., 2 = 2x DPI).
transparent – If True, exports with transparent background.
border_width – Margin around visualization in pixels.
border_color – Color of the border (e.g., “#FFFFFF”). If not specified, uses chart background color.
logo – Logo display mode: “auto”, “on”, or “off”.
logo_id – Custom logo ID (pattern: ^[a-zA-Z0-9-]+$).
dark – If True, exports in dark mode.
ligatures – If True (default), enables typography ligatures.
full_vector – If True, exports as full vector output.
download – If True, includes download headers in response.
access_token – Optional Datawrapper API access token.
timeout – Timeout for the API request in seconds.
- Returns:
Raw SVG document data as bytes.
- Raises:
ValueError – If no chart_id is set.
Exception – If the API request fails.
Example
>>> chart = ColumnChart.get(chart_id="abc123") >>> svg_data = chart.export_svg(plain=True) >>> Path("chart.svg").write_bytes(svg_data)
- fork(access_token: str | None = None) BaseChart
Fork the chart and create an editable copy via the Datawrapper API.
- Parameters:
access_token – Optional Datawrapper API access token. If not provided, will use DATAWRAPPER_ACCESS_TOKEN environment variable.
- Returns:
A new BaseChart instance representing the forked chart.
- Raises:
ValueError – If no chart_id is set or no access token is available.
Exception – If the API request fails.
- get_display_urls(access_token: str | None = None) list[dict]
Get the URLs for the published chart, table or map.
- Parameters:
access_token – Optional Datawrapper API access token. If not provided, will use DATAWRAPPER_ACCESS_TOKEN environment variable.
- Returns:
A list of dictionaries containing the display URLs for the chart.
- Raises:
ValueError – If no chart_id is set or no access token is available.
Exception – If the API request fails.
- get_editor_url() str
Get the Datawrapper editor URL for this chart.
- Returns:
The Datawrapper editor URL as a string.
- Raises:
ValueError – If no chart_id is set.
- get_iframe_code(responsive: bool = False, access_token: str | None = None) str
Get the iframe embed code for the chart, table, or map.
- Parameters:
responsive – Whether to return responsive iframe code, by default False
access_token – Optional Datawrapper API access token. If not provided, will use DATAWRAPPER_ACCESS_TOKEN environment variable.
- Returns:
The iframe embed code as a string.
- Raises:
ValueError – If no chart_id is set or no access token is available.
Exception – If the API request fails.
- get_png_url() str
Get the fallback PNG image URL for noscript tags.
- Returns:
//datawrapper.dwcdn.net/{chart_id}/full.png
- Return type:
The PNG image URL in the format https
- Raises:
ValueError – If no chart_id is set.
- get_public_url() str
Get the public URL for the published chart.
- Returns:
//datawrapper.dwcdn.net/{chart_id}/
- Return type:
The public URL in the format https
- Raises:
ValueError – If no chart_id is set.
Note
This method returns the URL regardless of whether the chart is actually published. If the chart is not published, the URL will not be accessible. Use publish() to publish the chart before accessing this URL.
- model_copy(*, update: Mapping[str, Any] | None = None, deep: bool = False) Self
- !!! abstract “Usage Documentation”
[model_copy](../concepts/models.md#model-copy)
Returns a copy of the model.
- !!! note
The underlying instance’s [__dict__][object.__dict__] attribute is copied. This might have unexpected side effects if you store anything in it, on top of the model fields (e.g. the value of [cached properties][functools.cached_property]).
- Parameters:
update – Values to change/add in the new model. Note: the data is not validated before creating the new model. You should trust this data.
deep – Set to True to make a deep copy of the model.
- Returns:
New model instance.
- model_dump(*, mode: Literal['json', 'python'] | str = 'python', include: set[int] | set[str] | Mapping[int, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | Mapping[str, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | None = None, exclude: set[int] | set[str] | Mapping[int, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | Mapping[str, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | None = None, context: Any | None = None, by_alias: bool | None = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, exclude_computed_fields: bool = False, round_trip: bool = False, warnings: bool | Literal['none', 'warn', 'error'] = True, fallback: Callable[[Any], Any] | None = None, serialize_as_any: bool = False, polymorphic_serialization: bool | None = None) dict[str, Any]
- !!! abstract “Usage Documentation”
[model_dump](../concepts/serialization.md#python-mode)
Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
- Parameters:
mode – The mode in which to_python should run. If mode is ‘json’, the output will only contain JSON serializable types. If mode is ‘python’, the output may contain non-JSON-serializable Python objects.
include – A set of fields to include in the output.
exclude – A set of fields to exclude from the output.
context – Additional context to pass to the serializer.
by_alias – Whether to use the field’s alias in the dictionary key if defined.
exclude_unset – Whether to exclude fields that have not been explicitly set.
exclude_defaults – Whether to exclude fields that are set to their default value.
exclude_none – Whether to exclude fields that have a value of None.
exclude_computed_fields – Whether to exclude computed fields. While this can be useful for round-tripping, it is usually recommended to use the dedicated round_trip parameter instead.
round_trip – If True, dumped values should be valid as input for non-idempotent types such as Json[T].
warnings – How to handle serialization errors. False/”none” ignores them, True/”warn” logs errors, “error” raises a [PydanticSerializationError][pydantic_core.PydanticSerializationError].
fallback – A function to call when an unknown value is encountered. If not provided, a [PydanticSerializationError][pydantic_core.PydanticSerializationError] error is raised.
serialize_as_any – Whether to serialize fields with duck-typing serialization behavior.
polymorphic_serialization – Whether to use model and dataclass polymorphic serialization for this call.
- Returns:
A dictionary representation of the model.
- model_dump_json(*, indent: int | None = None, ensure_ascii: bool = False, include: set[int] | set[str] | Mapping[int, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | Mapping[str, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | None = None, exclude: set[int] | set[str] | Mapping[int, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | Mapping[str, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | None = None, context: Any | None = None, by_alias: bool | None = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, exclude_computed_fields: bool = False, round_trip: bool = False, warnings: bool | Literal['none', 'warn', 'error'] = True, fallback: Callable[[Any], Any] | None = None, serialize_as_any: bool = False, polymorphic_serialization: bool | None = None) str
- !!! abstract “Usage Documentation”
[model_dump_json](../concepts/serialization.md#json-mode)
Generates a JSON representation of the model using Pydantic’s to_json method.
- Parameters:
indent – Indentation to use in the JSON output. If None is passed, the output will be compact.
ensure_ascii – If True, the output is guaranteed to have all incoming non-ASCII characters escaped. If False (the default), these characters will be output as-is.
include – Field(s) to include in the JSON output.
exclude – Field(s) to exclude from the JSON output.
context – Additional context to pass to the serializer.
by_alias – Whether to serialize using field aliases.
exclude_unset – Whether to exclude fields that have not been explicitly set.
exclude_defaults – Whether to exclude fields that are set to their default value.
exclude_none – Whether to exclude fields that have a value of None.
exclude_computed_fields – Whether to exclude computed fields. While this can be useful for round-tripping, it is usually recommended to use the dedicated round_trip parameter instead.
round_trip – If True, dumped values should be valid as input for non-idempotent types such as Json[T].
warnings – How to handle serialization errors. False/”none” ignores them, True/”warn” logs errors, “error” raises a [PydanticSerializationError][pydantic_core.PydanticSerializationError].
fallback – A function to call when an unknown value is encountered. If not provided, a [PydanticSerializationError][pydantic_core.PydanticSerializationError] error is raised.
serialize_as_any – Whether to serialize fields with duck-typing serialization behavior.
polymorphic_serialization – Whether to use model and dataclass polymorphic serialization for this call.
- Returns:
A JSON string representation of the model.
- model_post_init(context: Any, /) None
Override this method to perform additional initialization after __init__ and model_construct. This is useful if you want to do some validation that requires the entire model to be initialized.
- publish(access_token: str | None = None) BaseChart
Publish the chart via the Datawrapper API.
- Parameters:
access_token – Optional Datawrapper API access token. If not provided, will use DATAWRAPPER_ACCESS_TOKEN environment variable.
- Returns:
Self, to enable method chaining.
- Raises:
ValueError – If no chart_id is set or no access token is available.
Exception – If the API request fails or publishing fails.
- serialize_data() str | None
Convert data to CSV string for API upload.
- Returns:
CSV string representation of the data, or None if data is empty.
- update(access_token: str | None = None) BaseChart
Update an existing chart via the Datawrapper API.
- Parameters:
access_token – Optional Datawrapper API access token. If not provided, will use DATAWRAPPER_ACCESS_TOKEN environment variable.
- Returns:
Self, to enable method chaining.
- Raises:
ValueError – If no chart_id is set or no access token is available.
Exception – If the API request fails.
- area_opacity: float
The opacity of the areas
- area_separator_color: str | int
The color of the separator lines between areas
- area_separator_lines: bool
Whether or not to show separator lines between areas
- aria_description
The alternative text for screen readers
- auto_dark_mode
Whether the chart should automatically flip to dark mode when the user’s system is in dark mode
- base_color: str | int
The base color for layers (palette index or hex string)
- byline
The byline that appears below the chart
- chart_id
The chart ID after creation (populated by create() method)
- chart_type: Literal['d3-area']
The type of datawrapper chart to create
- color_category: dict[str, str]
A mapping of layer names to colors
- custom
A dictionary of custom tags to attach to the chart
- dark_mode_invert
Whether to invert colors in dark mode
- data
The data to use for the chart
- download_image
Whether to allow PNG download
- download_pdf
Whether to allow PDF download
- download_svg
Whether to allow SVG download
- embed
Whether to allow embedding
- force_attribution
Whether to attribute the chart to datawrapper
- forkable
Whether to allow other users to fork this visualization
- get_the_data
Whether to allow data downloads
- hide_title
Whether or not to hide the title
- interpolation: LineInterpolation | str
The interpolation method to use when drawing lines
- intro
The intro text that appears above the chart
- language
The locale of the chart, which defines decimal and thousand separators as well as translations of month and weekday names.
- logo
Whether to show a logo
- logo_id
The id of the logo to show
- model_config = {'arbitrary_types_allowed': True, 'json_schema_extra': {'examples': [{'area_opacity': 0.8, 'chart-type': 'd3-area', 'data': year Region A Region B 0 2020 100 80 1 2021 120 90 2 2022 140 100, 'source_name': 'Census Bureau', 'stack_areas': True, 'title': 'Population Growth Over Time'}]}, 'populate_by_name': True, 'strict': True, 'use_enum_values': True, 'validate_assignment': True, 'validate_by_alias': True, 'validate_by_name': True, 'validate_default': True}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- property model_extra: dict[str, Any] | None
Get extra fields set during validation.
- Returns:
A dictionary of extra fields, or None if config.extra is not set to “allow”.
- property model_fields_set: set[str]
Returns the set of fields that have been explicitly set on this model instance.
- Returns:
- A set of strings representing the fields that have been set,
i.e. that were not filled from defaults.
- notes
The footnotes that appear below the chart
- plot_height_fixed: int | float
The fixed height of the plot
- plot_height_mode: PlotHeightMode | str
How to set the plot height
- plot_height_ratio: float
The ratio of the plot height
Whether to show social media share buttons
What URL to share
- show_color_key: bool
Whether or not to show the color key above the chart
- show_tooltips: bool
Whether or not to show tooltips on hover
- sort_areas: Literal['keep', 'asc', 'desc']
How to sort area layers
- source_name
The source name that appears below the chart
- source_url
The source URL that appears below the chart
- stack_areas: bool
Whether or not to stack areas
- stack_to_100: bool
Whether or not to stack areas to 100%
- theme
The theme of the chart
- title
The headline that appears above the chart
- tooltip_number_format: DateFormat | NumberFormat | str
The format of the number tooltip (use DateFormat or NumberFormat enum or custom format strings)
- tooltip_x_format: DateFormat | NumberFormat | str
The format for the x-axis tooltips (use DateFormat or NumberFormat enum or custom format strings)
- transformations
The metadata options for the data columns in the “Check and Describe” tab
- y_grid_label_align: GridLabelAlign | str
Which side to put the y-axis labels on
- y_grid_labels: GridLabelPosition | str
The labeling of the y grid labels
Arrow Chart
- class datawrapper.charts.ArrowChart(*, chart_type: Literal['d3-arrow-plot'] = 'd3-arrow-plot', data: DataFrame | list[dict] = <factory>, transformations: Transform | dict[str, ~typing.Any]=<factory>, title: str = '', intro: str = '', notes: str = '', source_name: str = '', source_url: str = '', byline: str = '', aria_description: str = '', hide_title: bool = False, language: str = 'en-US', theme: str = 'datawrapper', autoDarkMode: bool = False, dark_mode_invert: bool = True, get_the_data: bool = False, download_image: bool = False, download_pdf: bool = False, download_svg: bool = False, embed: bool = False, force_attribution: bool = False, share_buttons: bool = False, share_url: str = '', logo: bool = False, logo_id: str = '', custom: dict[str, ~typing.Any]=<factory>, forkable: bool = True, chart_id: str | None = None, base_color: str | int = 0, color_category: dict[str, str]=<factory>, thick_arrows: bool = True, y_grid: str = 'on', replace_flags: ReplaceFlagsType | str = 'off', sort_ranges: bool = False, sort_by: Literal['end', 'start', 'difference', 'change']='end', reverse_order: bool = False, value_label_format: DateFormat | NumberFormat | str = '', range_value_labels: str = '', custom_range: list[~typing.Any] | tuple[~typing.Any, ~typing.Any]=<factory>, range_extent: Literal['nice', 'custom', 'data']='nice', start_column: str | None = None, end_column: str | None = None, color_column: str | None = None, label_column: str | None = None, groups_column: str | None = None, arrow_key: bool = False)[source]
Bases:
BaseChartA base class for the Datawrapper API’s arrow chart.
- classmethod convert_column_format_dicts(data: dict[str, Any]) dict[str, Any]
Convert dictionary items in transformation to Transform objects.
- classmethod deserialize_data(csv_data: str | DataFrame) DataFrame
Parse CSV string from Datawrapper API into DataFrame.
- Parameters:
csv_data – The CSV data from the chart data endpoint
- Returns:
DataFrame containing the parsed CSV data
- classmethod deserialize_model(api_response: dict[str, Any]) dict[str, Any][source]
Parse Datawrapper API response including arrow chart specific fields.
- Parameters:
api_response – The JSON response from the chart metadata endpoint
- Returns:
Dictionary that can be used to initialize the ArrowChart model
- classmethod get(chart_id: str, access_token: str | None = None) BaseChart
Fetch an existing chart from the Datawrapper API.
- Parameters:
chart_id – The ID of the chart to fetch
access_token – Optional Datawrapper API access token. If not provided, will use DATAWRAPPER_ACCESS_TOKEN environment variable.
- Returns:
An instance of the chart class with data populated from the API.
- Raises:
ValueError – If no access token is available or chart type doesn’t match.
Exception – If the API request fails.
- classmethod model_construct(_fields_set: set[str] | None = None, **values: Any) Self
Creates a new instance of the Model class with validated data.
Creates a new model setting __dict__ and __pydantic_fields_set__ from trusted or pre-validated data. Default values are respected, but no other validation is performed.
- !!! note
model_construct() generally respects the model_config.extra setting on the provided model. That is, if model_config.extra == ‘allow’, then all extra passed values are added to the model instance’s __dict__ and __pydantic_extra__ fields. If model_config.extra == ‘ignore’ (the default), then all extra passed values are ignored. Because no validation is performed with a call to model_construct(), having model_config.extra == ‘forbid’ does not result in an error if extra values are passed, but they will be ignored.
- Parameters:
_fields_set – A set of field names that were originally explicitly set during instantiation. If provided, this is directly used for the [model_fields_set][pydantic.BaseModel.model_fields_set] attribute. Otherwise, the field names from the values argument will be used.
values – Trusted or pre-validated data dictionary.
- Returns:
A new instance of the Model class with validated data.
- classmethod model_json_schema(by_alias: bool = True, ref_template: str = '#/$defs/{model}', schema_generator: type[GenerateJsonSchema] = <class 'pydantic.json_schema.GenerateJsonSchema'>, mode: Literal['validation', 'serialization']='validation', *, union_format: Literal['any_of', 'primitive_type_array']='any_of') dict[str, Any]
Generates a JSON schema for a model class.
- Parameters:
by_alias – Whether to use attribute aliases or not.
ref_template – The reference template.
union_format –
The format to use when combining schemas from unions together. Can be one of:
’any_of’: Use the [anyOf](https://json-schema.org/understanding-json-schema/reference/combining#anyOf)
keyword to combine schemas (the default). - ‘primitive_type_array’: Use the [type](https://json-schema.org/understanding-json-schema/reference/type) keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive type (string, boolean, null, integer or number) or contains constraints/metadata, falls back to any_of.
schema_generator – To override the logic used to generate the JSON schema, as a subclass of GenerateJsonSchema with your desired modifications
mode – The mode in which to generate the schema.
- Returns:
The JSON schema for the given model class.
- classmethod model_parametrized_name(params: tuple[type[Any], ...]) str
Compute the class name for parametrizations of generic classes.
This method can be overridden to achieve a custom naming scheme for generic BaseModels.
- Parameters:
params – Tuple of types of the class. Given a generic class Model with 2 type variables and a concrete model Model[str, int], the value (str, int) would be passed to params.
- Returns:
String representing the new class where params are passed to cls as type variables.
- Raises:
TypeError – Raised when trying to generate concrete names for non-generic models.
- classmethod model_rebuild(*, force: bool = False, raise_errors: bool = True, _parent_namespace_depth: int = 2, _types_namespace: MappingNamespace | None = None) bool | None
Try to rebuild the pydantic-core schema for the model.
This may be necessary when one of the annotations is a ForwardRef which could not be resolved during the initial attempt to build the schema, and automatic rebuilding fails.
- Parameters:
force – Whether to force the rebuilding of the model schema, defaults to False.
raise_errors – Whether to raise errors, defaults to True.
_parent_namespace_depth – The depth level of the parent namespace, defaults to 2.
_types_namespace – The types namespace, defaults to None.
- Returns:
Returns None if the schema is already “complete” and rebuilding was not required. If rebuilding _was_ required, returns True if rebuilding was successful, otherwise False.
- classmethod model_validate(obj: Any, *, strict: bool | None = None, extra: Literal['allow', 'ignore', 'forbid'] | None = None, from_attributes: bool | None = None, context: Any | None = None, by_alias: bool | None = None, by_name: bool | None = None) Self
Validate a pydantic model instance.
- Parameters:
obj – The object to validate.
strict – Whether to enforce types strictly.
extra – Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.
from_attributes – Whether to extract data from object attributes.
context – Additional context to pass to the validator.
by_alias – Whether to use the field’s alias when validating against the provided input data.
by_name – Whether to use the field’s name when validating against the provided input data.
- Raises:
ValidationError – If the object could not be validated.
- Returns:
The validated model instance.
- classmethod model_validate_json(json_data: str | bytes | bytearray, *, strict: bool | None = None, extra: Literal['allow', 'ignore', 'forbid'] | None = None, context: Any | None = None, by_alias: bool | None = None, by_name: bool | None = None) Self
- !!! abstract “Usage Documentation”
[JSON Parsing](../concepts/json.md#json-parsing)
Validate the given JSON data against the Pydantic model.
- Parameters:
json_data – The JSON data to validate.
strict – Whether to enforce types strictly.
extra – Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.
context – Extra variables to pass to the validator.
by_alias – Whether to use the field’s alias when validating against the provided input data.
by_name – Whether to use the field’s name when validating against the provided input data.
- Returns:
The validated Pydantic model.
- Raises:
ValidationError – If json_data is not a JSON string or the object could not be validated.
- classmethod model_validate_strings(obj: Any, *, strict: bool | None = None, extra: Literal['allow', 'ignore', 'forbid'] | None = None, context: Any | None = None, by_alias: bool | None = None, by_name: bool | None = None) Self
Validate the given object with string data against the Pydantic model.
- Parameters:
obj – The object containing string data to validate.
strict – Whether to enforce types strictly.
extra – Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.
context – Extra variables to pass to the validator.
by_alias – Whether to use the field’s alias when validating against the provided input data.
by_name – Whether to use the field’s name when validating against the provided input data.
- Returns:
The validated Pydantic model.
- classmethod validate_replace_flags(v: ReplaceFlagsType | str) ReplaceFlagsType | str[source]
Validate that replace_flags is a valid ReplaceFlagsType value.
- classmethod warn_on_unrecognized_fields(data: dict[str, Any]) dict[str, Any]
Warn users about unrecognized fields that don’t match model fields or aliases.
This validator checks incoming data against the model’s defined fields and their aliases, issuing warnings for any keys that don’t match. This helps catch typos and misunderstandings about the API without breaking initialization.
- copy(*, include: AbstractSetIntStr | MappingIntStrAny | None = None, exclude: AbstractSetIntStr | MappingIntStrAny | None = None, update: Dict[str, Any] | None = None, deep: bool = False) Self
Returns a copy of the model.
- !!! warning “Deprecated”
This method is now deprecated; use model_copy instead.
If you need include or exclude, use:
`python {test="skip" lint="skip"} data = self.model_dump(include=include, exclude=exclude, round_trip=True) data = {**data, **(update or {})} copied = self.model_validate(data) `- Parameters:
include – Optional set or mapping specifying which fields to include in the copied model.
exclude – Optional set or mapping specifying which fields to exclude in the copied model.
update – Optional dictionary of field-value pairs to override field values in the copied model.
deep – If True, the values of fields that are Pydantic models will be deep-copied.
- Returns:
A copy of the model with included, excluded and updated fields as specified.
- create(access_token: str | None = None, folder_id: int | None = None) BaseChart
Create a new chart via the Datawrapper API.
- Parameters:
access_token – Optional Datawrapper API access token. If not provided, will use DATAWRAPPER_ACCESS_TOKEN environment variable.
folder_id – Optional folder ID to create the chart in.
- Returns:
Self, to enable method chaining. The chart ID is stored in self.chart_id.
- Raises:
ValueError – If no access token is available or API returns invalid response.
Exception – If the API request fails.
- delete(access_token: str | None = None) bool
Delete the chart via the Datawrapper API.
- Parameters:
access_token – Optional Datawrapper API access token. If not provided, will use DATAWRAPPER_ACCESS_TOKEN environment variable.
- Returns:
True if the chart was deleted successfully.
- Raises:
ValueError – If no chart_id is set or no access token is available.
Exception – If the API request fails.
- display(access_token: str | None = None) IFrame
Display the chart as an IFrame in a Jupyter notebook.
- Parameters:
access_token – Optional Datawrapper API access token. If not provided, will use DATAWRAPPER_ACCESS_TOKEN environment variable.
- Returns:
An IPython.display.IFrame object displaying the chart.
- Raises:
ValueError – If no chart_id is set or no access token is available.
Exception – If the API request fails.
- duplicate(access_token: str | None = None) BaseChart
Duplicate the chart and create a new editable copy via the Datawrapper API.
- Parameters:
access_token – Optional Datawrapper API access token. If not provided, will use DATAWRAPPER_ACCESS_TOKEN environment variable.
- Returns:
A new BaseChart instance representing the duplicated chart.
- Raises:
ValueError – If no chart_id is set or no access token is available.
Exception – If the API request fails.
- export_pdf(*, width: int | None = None, height: int | None = None, plain: bool = False, unit: Literal['px', 'mm', 'inch'] = 'px', mode: Literal['rgb', 'cmyk'] = 'rgb', scale: int = 1, zoom: int = 2, transparent: bool = False, border_width: int = 0, border_color: str | None = None, logo: Literal['auto', 'on', 'off'] = 'auto', logo_id: str | None = None, dark: bool = False, ligatures: bool = True, full_vector: bool = False, download: bool = False, access_token: str | None = None, timeout: int = 30) bytes
Export chart as PDF and return the raw bytes.
- Parameters:
width – Width of visualization. If not specified, uses chart width.
height – Height of visualization. If not specified, uses chart height.
plain – If True, exports only the visualization without header/footer.
unit – Unit for measurements: “px”, “mm”, or “inch”.
mode – Color mode: “rgb” or “cmyk”.
scale – Size multiplier that changes actual dimensions (e.g., 2 = 2x size).
zoom – Resolution multiplier for sharper output at same visual size (e.g., 2 = 2x DPI).
transparent – If True, exports with transparent background.
border_width – Margin around visualization.
border_color – Color of the border (e.g., “#FFFFFF”). If not specified, uses chart background color.
logo – Logo display mode: “auto”, “on”, or “off”.
logo_id – Custom logo ID (pattern: ^[a-zA-Z0-9-]+$).
dark – If True, exports in dark mode.
ligatures – If True (default), enables typography ligatures.
full_vector – If True, exports as full vector output.
download – If True, includes download headers in response.
access_token – Optional Datawrapper API access token.
timeout – Timeout for the API request in seconds.
- Returns:
Raw PDF document data as bytes.
- Raises:
ValueError – If no chart_id is set or invalid parameters provided.
Exception – If the API request fails.
Example
>>> chart = BarChart.get(chart_id="abc123") >>> pdf_data = chart.export_pdf(unit="mm", mode="cmyk") >>> Path("chart.pdf").write_bytes(pdf_data)
- export_png(*, width: int | None = None, height: int | None = None, plain: bool = False, scale: int = 1, zoom: int = 2, transparent: bool = False, border_width: int = 0, border_color: str | None = None, logo: Literal['auto', 'on', 'off'] = 'auto', logo_id: str | None = None, dark: bool = False, ligatures: bool = True, full_vector: bool = False, download: bool = False, access_token: str | None = None, timeout: int = 30) bytes
Export chart as PNG and return the raw bytes.
- Parameters:
width – Width of visualization in pixels. If not specified, uses chart width.
height – Height of visualization in pixels. If not specified, uses chart height.
plain – If True, exports only the visualization without header/footer.
scale – Size multiplier that changes actual dimensions (e.g., 2 = 2x size).
zoom – Resolution multiplier for sharper output at same visual size (e.g., 2 = 2x DPI).
transparent – If True, exports with transparent background.
border_width – Margin around visualization in pixels.
border_color – Color of the border (e.g., “#FFFFFF”). If not specified, uses chart background color.
logo – Logo display mode: “auto”, “on”, or “off”.
logo_id – Custom logo ID (pattern: ^[a-zA-Z0-9-]+$).
dark – If True, exports in dark mode.
ligatures – If True (default), enables typography ligatures.
full_vector – If True, exports as full vector output.
download – If True, includes download headers in response.
access_token – Optional Datawrapper API access token.
timeout – Timeout for the API request in seconds.
- Returns:
Raw PNG image data as bytes.
- Raises:
ValueError – If no chart_id is set.
Exception – If the API request fails.
Example
>>> chart = LineChart.get(chart_id="abc123") >>> png_data = chart.export_png(zoom=3, transparent=True) >>> Path("chart.png").write_bytes(png_data)
- export_svg(*, width: int | None = None, height: int | None = None, plain: bool = False, scale: int = 1, zoom: int = 2, transparent: bool = False, border_width: int = 0, border_color: str | None = None, logo: Literal['auto', 'on', 'off'] = 'auto', logo_id: str | None = None, dark: bool = False, ligatures: bool = True, full_vector: bool = False, download: bool = False, access_token: str | None = None, timeout: int = 30) bytes
Export chart as SVG and return the raw bytes.
- Parameters:
width – Width of visualization. If not specified, uses chart width.
height – Height of visualization. If not specified, uses chart height.
plain – If True, exports only the visualization without header/footer.
scale – Size multiplier that changes actual dimensions (e.g., 2 = 2x size).
zoom – Resolution multiplier for sharper output at same visual size (e.g., 2 = 2x DPI).
transparent – If True, exports with transparent background.
border_width – Margin around visualization in pixels.
border_color – Color of the border (e.g., “#FFFFFF”). If not specified, uses chart background color.
logo – Logo display mode: “auto”, “on”, or “off”.
logo_id – Custom logo ID (pattern: ^[a-zA-Z0-9-]+$).
dark – If True, exports in dark mode.
ligatures – If True (default), enables typography ligatures.
full_vector – If True, exports as full vector output.
download – If True, includes download headers in response.
access_token – Optional Datawrapper API access token.
timeout – Timeout for the API request in seconds.
- Returns:
Raw SVG document data as bytes.
- Raises:
ValueError – If no chart_id is set.
Exception – If the API request fails.
Example
>>> chart = ColumnChart.get(chart_id="abc123") >>> svg_data = chart.export_svg(plain=True) >>> Path("chart.svg").write_bytes(svg_data)
- fork(access_token: str | None = None) BaseChart
Fork the chart and create an editable copy via the Datawrapper API.
- Parameters:
access_token – Optional Datawrapper API access token. If not provided, will use DATAWRAPPER_ACCESS_TOKEN environment variable.
- Returns:
A new BaseChart instance representing the forked chart.
- Raises:
ValueError – If no chart_id is set or no access token is available.
Exception – If the API request fails.
- get_display_urls(access_token: str | None = None) list[dict]
Get the URLs for the published chart, table or map.
- Parameters:
access_token – Optional Datawrapper API access token. If not provided, will use DATAWRAPPER_ACCESS_TOKEN environment variable.
- Returns:
A list of dictionaries containing the display URLs for the chart.
- Raises:
ValueError – If no chart_id is set or no access token is available.
Exception – If the API request fails.
- get_editor_url() str
Get the Datawrapper editor URL for this chart.
- Returns:
The Datawrapper editor URL as a string.
- Raises:
ValueError – If no chart_id is set.
- get_iframe_code(responsive: bool = False, access_token: str | None = None) str
Get the iframe embed code for the chart, table, or map.
- Parameters:
responsive – Whether to return responsive iframe code, by default False
access_token – Optional Datawrapper API access token. If not provided, will use DATAWRAPPER_ACCESS_TOKEN environment variable.
- Returns:
The iframe embed code as a string.
- Raises:
ValueError – If no chart_id is set or no access token is available.
Exception – If the API request fails.
- get_png_url() str
Get the fallback PNG image URL for noscript tags.
- Returns:
//datawrapper.dwcdn.net/{chart_id}/full.png
- Return type:
The PNG image URL in the format https
- Raises:
ValueError – If no chart_id is set.
- get_public_url() str
Get the public URL for the published chart.
- Returns:
//datawrapper.dwcdn.net/{chart_id}/
- Return type:
The public URL in the format https
- Raises:
ValueError – If no chart_id is set.
Note
This method returns the URL regardless of whether the chart is actually published. If the chart is not published, the URL will not be accessible. Use publish() to publish the chart before accessing this URL.
- model_copy(*, update: Mapping[str, Any] | None = None, deep: bool = False) Self
- !!! abstract “Usage Documentation”
[model_copy](../concepts/models.md#model-copy)
Returns a copy of the model.
- !!! note
The underlying instance’s [__dict__][object.__dict__] attribute is copied. This might have unexpected side effects if you store anything in it, on top of the model fields (e.g. the value of [cached properties][functools.cached_property]).
- Parameters:
update – Values to change/add in the new model. Note: the data is not validated before creating the new model. You should trust this data.
deep – Set to True to make a deep copy of the model.
- Returns:
New model instance.
- model_dump(*, mode: Literal['json', 'python'] | str = 'python', include: set[int] | set[str] | Mapping[int, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | Mapping[str, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | None = None, exclude: set[int] | set[str] | Mapping[int, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | Mapping[str, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | None = None, context: Any | None = None, by_alias: bool | None = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, exclude_computed_fields: bool = False, round_trip: bool = False, warnings: bool | Literal['none', 'warn', 'error'] = True, fallback: Callable[[Any], Any] | None = None, serialize_as_any: bool = False, polymorphic_serialization: bool | None = None) dict[str, Any]
- !!! abstract “Usage Documentation”
[model_dump](../concepts/serialization.md#python-mode)
Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
- Parameters:
mode – The mode in which to_python should run. If mode is ‘json’, the output will only contain JSON serializable types. If mode is ‘python’, the output may contain non-JSON-serializable Python objects.
include – A set of fields to include in the output.
exclude – A set of fields to exclude from the output.
context – Additional context to pass to the serializer.
by_alias – Whether to use the field’s alias in the dictionary key if defined.
exclude_unset – Whether to exclude fields that have not been explicitly set.
exclude_defaults – Whether to exclude fields that are set to their default value.
exclude_none – Whether to exclude fields that have a value of None.
exclude_computed_fields – Whether to exclude computed fields. While this can be useful for round-tripping, it is usually recommended to use the dedicated round_trip parameter instead.
round_trip – If True, dumped values should be valid as input for non-idempotent types such as Json[T].
warnings – How to handle serialization errors. False/”none” ignores them, True/”warn” logs errors, “error” raises a [PydanticSerializationError][pydantic_core.PydanticSerializationError].
fallback – A function to call when an unknown value is encountered. If not provided, a [PydanticSerializationError][pydantic_core.PydanticSerializationError] error is raised.
serialize_as_any – Whether to serialize fields with duck-typing serialization behavior.
polymorphic_serialization – Whether to use model and dataclass polymorphic serialization for this call.
- Returns:
A dictionary representation of the model.
- model_dump_json(*, indent: int | None = None, ensure_ascii: bool = False, include: set[int] | set[str] | Mapping[int, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | Mapping[str, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | None = None, exclude: set[int] | set[str] | Mapping[int, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | Mapping[str, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | None = None, context: Any | None = None, by_alias: bool | None = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, exclude_computed_fields: bool = False, round_trip: bool = False, warnings: bool | Literal['none', 'warn', 'error'] = True, fallback: Callable[[Any], Any] | None = None, serialize_as_any: bool = False, polymorphic_serialization: bool | None = None) str
- !!! abstract “Usage Documentation”
[model_dump_json](../concepts/serialization.md#json-mode)
Generates a JSON representation of the model using Pydantic’s to_json method.
- Parameters:
indent – Indentation to use in the JSON output. If None is passed, the output will be compact.
ensure_ascii – If True, the output is guaranteed to have all incoming non-ASCII characters escaped. If False (the default), these characters will be output as-is.
include – Field(s) to include in the JSON output.
exclude – Field(s) to exclude from the JSON output.
context – Additional context to pass to the serializer.
by_alias – Whether to serialize using field aliases.
exclude_unset – Whether to exclude fields that have not been explicitly set.
exclude_defaults – Whether to exclude fields that are set to their default value.
exclude_none – Whether to exclude fields that have a value of None.
exclude_computed_fields – Whether to exclude computed fields. While this can be useful for round-tripping, it is usually recommended to use the dedicated round_trip parameter instead.
round_trip – If True, dumped values should be valid as input for non-idempotent types such as Json[T].
warnings – How to handle serialization errors. False/”none” ignores them, True/”warn” logs errors, “error” raises a [PydanticSerializationError][pydantic_core.PydanticSerializationError].
fallback – A function to call when an unknown value is encountered. If not provided, a [PydanticSerializationError][pydantic_core.PydanticSerializationError] error is raised.
serialize_as_any – Whether to serialize fields with duck-typing serialization behavior.
polymorphic_serialization – Whether to use model and dataclass polymorphic serialization for this call.
- Returns:
A JSON string representation of the model.
- model_post_init(context: Any, /) None
Override this method to perform additional initialization after __init__ and model_construct. This is useful if you want to do some validation that requires the entire model to be initialized.
- publish(access_token: str | None = None) BaseChart
Publish the chart via the Datawrapper API.
- Parameters:
access_token – Optional Datawrapper API access token. If not provided, will use DATAWRAPPER_ACCESS_TOKEN environment variable.
- Returns:
Self, to enable method chaining.
- Raises:
ValueError – If no chart_id is set or no access token is available.
Exception – If the API request fails or publishing fails.
- serialize_data() str | None
Convert data to CSV string for API upload.
- Returns:
CSV string representation of the data, or None if data is empty.
- update(access_token: str | None = None) BaseChart
Update an existing chart via the Datawrapper API.
- Parameters:
access_token – Optional Datawrapper API access token. If not provided, will use DATAWRAPPER_ACCESS_TOKEN environment variable.
- Returns:
Self, to enable method chaining.
- Raises:
ValueError – If no chart_id is set or no access token is available.
Exception – If the API request fails.
- aria_description
The alternative text for screen readers
- arrow_key: bool
Label on the first arrow that shows column names
- auto_dark_mode
Whether the chart should automatically flip to dark mode when the user’s system is in dark mode
- base_color: str | int
The base color for the arrows
- byline
The byline that appears below the chart
- chart_id
The chart ID after creation (populated by create() method)
- chart_type: Literal['d3-arrow-plot']
The type of datawrapper chart to create
- color_category: dict[str, str]
A mapping of layer names to colors
- color_column: str | None
The column to color by
- custom
A dictionary of custom tags to attach to the chart
- custom_range: list[Any] | tuple[Any, Any]
The custom range for the x axis
- dark_mode_invert
Whether to invert colors in dark mode
- data
The data to use for the chart
- download_image
Whether to allow PNG download
- download_pdf
Whether to allow PDF download
- download_svg
Whether to allow SVG download
- embed
Whether to allow embedding
- end_column: str | None
The column that arrows should end at
- force_attribution
Whether to attribute the chart to datawrapper
- forkable
Whether to allow other users to fork this visualization
- get_the_data
Whether to allow data downloads
- groups_column: str | None
The column to group arrows by
- hide_title
Whether or not to hide the title
- intro
The intro text that appears above the chart
- label_column: str | None
The column to label by
- language
The locale of the chart, which defines decimal and thousand separators as well as translations of month and weekday names.
- logo
Whether to show a logo
- logo_id
The id of the logo to show
- model_config = {'arbitrary_types_allowed': True, 'json_schema_extra': {'examples': [{'chart-type': 'd3-arrow-plot', 'data': Region 2020 2023 0 North 100 110 1 South 150 160 2 East 120 115 3 West 90 95, 'end_column': '2023', 'source_name': 'Census Bureau', 'start_column': '2020', 'thick_arrows': True, 'title': 'Population Change by Region'}]}, 'populate_by_name': True, 'strict': True, 'use_enum_values': True, 'validate_assignment': True, 'validate_by_alias': True, 'validate_by_name': True, 'validate_default': True}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- property model_extra: dict[str, Any] | None
Get extra fields set during validation.
- Returns:
A dictionary of extra fields, or None if config.extra is not set to “allow”.
- property model_fields_set: set[str]
Returns the set of fields that have been explicitly set on this model instance.
- Returns:
- A set of strings representing the fields that have been set,
i.e. that were not filled from defaults.
- notes
The footnotes that appear below the chart
- range_extent: Literal['nice', 'custom', 'data']
The type of range on the x-axis
- range_value_labels: str
The field you want to use for the value labels
- replace_flags: ReplaceFlagsType | str
Whether to replace country codes with flags (use ReplaceFlagsType enum or raw string)
- reverse_order: bool
Reverse the order of the ranges
Whether to show social media share buttons
What URL to share
- sort_by: Literal['end', 'start', 'difference', 'change']
How to sort the ranges
- sort_ranges: bool
Whether to sort the ranges
- source_name
The source name that appears below the chart
- source_url
The source URL that appears below the chart
- start_column: str | None
The column that arrows should start at
- theme
The theme of the chart
- thick_arrows: bool
Thicken the arrows
- title
The headline that appears above the chart
- transformations
The metadata options for the data columns in the “Check and Describe” tab
- value_label_format: DateFormat | NumberFormat | str
The number format for value labels (use DateFormat or NumberFormat enum or custom format strings)
- y_grid: str
Show the y-axis grid lines
Bar Chart
- class datawrapper.charts.BarChart(*, chart_type: Literal['d3-bars'] = 'd3-bars', data: DataFrame | list[dict] = <factory>, transformations: Transform | dict[str, ~typing.Any]=<factory>, title: str = '', intro: str = '', notes: str = '', source_name: str = '', source_url: str = '', byline: str = '', aria_description: str = '', hide_title: bool = False, language: str = 'en-US', theme: str = 'datawrapper', autoDarkMode: bool = False, dark_mode_invert: bool = True, get_the_data: bool = False, download_image: bool = False, download_pdf: bool = False, download_svg: bool = False, embed: bool = False, force_attribution: bool = False, share_buttons: bool = False, share_url: str = '', logo: bool = False, logo_id: str = '', custom: dict[str, ~typing.Any]=<factory>, forkable: bool = True, chart_id: str | None = None, text_annotations: Any, ~typing.Any]]=<factory>, range_annotations: Any, ~typing.Any]]=<factory>, label_column: str = '', label_alignment: Literal['left', 'right']='left', block_labels: bool = False, show_value_labels: bool = True, value_label_alignment: ValueLabelAlignment | str = 'left', value_label_format: DateFormat | NumberFormat | str = '', swap_labels: bool = False, replace_flags: ReplaceFlagsType | str = 'off', show_color_key: bool = False, stack_color_legend: bool = False, exclude_from_color_key: list[str] = <factory>, bar_column: str = '', custom_range: list[~typing.Any] | tuple[~typing.Any, ~typing.Any]=<factory>, force_grid: bool = False, custom_grid_lines: list[Any] = <factory>, tick_position: Literal['top', 'bottom']='top', axis_label_format: DateFormat | NumberFormat | str = '', base_color: str | int = 0, color_column: str = '', color_category: dict[str, str]=<factory>, category_labels: dict[str, str]=<factory>, category_order: list[str] = <factory>, rules: bool = False, thick: bool = False, background: bool = False, sort_bars: bool = False, reverse_order: bool = False, groups_column: str | None = None, show_group_labels: bool = True, show_category_labels: bool = True, overlays: list[~datawrapper.charts.bar.BarOverlay | dict[str, ~typing.Any]]=<factory>, highlighted_series: list[str] = <factory>)[source]
Bases:
AnnotationsMixin,BaseChartA base class for the Datawrapper API’s bar chart.
- classmethod convert_column_format_dicts(data: dict[str, Any]) dict[str, Any]
Convert dictionary items in transformation to Transform objects.
- classmethod deserialize_data(csv_data: str | DataFrame) DataFrame
Parse CSV string from Datawrapper API into DataFrame.
- Parameters:
csv_data – The CSV data from the chart data endpoint
- Returns:
DataFrame containing the parsed CSV data
- classmethod deserialize_model(api_response: dict[str, Any]) dict[str, Any][source]
Parse Datawrapper API response including bar chart specific fields.
- Parameters:
api_response – The JSON response from the chart metadata endpoint
- Returns:
Dictionary that can be used to initialize the BarChart model
- classmethod get(chart_id: str, access_token: str | None = None) BaseChart
Fetch an existing chart from the Datawrapper API.
- Parameters:
chart_id – The ID of the chart to fetch
access_token – Optional Datawrapper API access token. If not provided, will use DATAWRAPPER_ACCESS_TOKEN environment variable.
- Returns:
An instance of the chart class with data populated from the API.
- Raises:
ValueError – If no access token is available or chart type doesn’t match.
Exception – If the API request fails.
- classmethod model_construct(_fields_set: set[str] | None = None, **values: Any) Self
Creates a new instance of the Model class with validated data.
Creates a new model setting __dict__ and __pydantic_fields_set__ from trusted or pre-validated data. Default values are respected, but no other validation is performed.
- !!! note
model_construct() generally respects the model_config.extra setting on the provided model. That is, if model_config.extra == ‘allow’, then all extra passed values are added to the model instance’s __dict__ and __pydantic_extra__ fields. If model_config.extra == ‘ignore’ (the default), then all extra passed values are ignored. Because no validation is performed with a call to model_construct(), having model_config.extra == ‘forbid’ does not result in an error if extra values are passed, but they will be ignored.
- Parameters:
_fields_set – A set of field names that were originally explicitly set during instantiation. If provided, this is directly used for the [model_fields_set][pydantic.BaseModel.model_fields_set] attribute. Otherwise, the field names from the values argument will be used.
values – Trusted or pre-validated data dictionary.
- Returns:
A new instance of the Model class with validated data.
- classmethod model_json_schema(by_alias: bool = True, ref_template: str = '#/$defs/{model}', schema_generator: type[GenerateJsonSchema] = <class 'pydantic.json_schema.GenerateJsonSchema'>, mode: Literal['validation', 'serialization']='validation', *, union_format: Literal['any_of', 'primitive_type_array']='any_of') dict[str, Any]
Generates a JSON schema for a model class.
- Parameters:
by_alias – Whether to use attribute aliases or not.
ref_template – The reference template.
union_format –
The format to use when combining schemas from unions together. Can be one of:
’any_of’: Use the [anyOf](https://json-schema.org/understanding-json-schema/reference/combining#anyOf)
keyword to combine schemas (the default). - ‘primitive_type_array’: Use the [type](https://json-schema.org/understanding-json-schema/reference/type) keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive type (string, boolean, null, integer or number) or contains constraints/metadata, falls back to any_of.
schema_generator – To override the logic used to generate the JSON schema, as a subclass of GenerateJsonSchema with your desired modifications
mode – The mode in which to generate the schema.
- Returns:
The JSON schema for the given model class.
- classmethod model_parametrized_name(params: tuple[type[Any], ...]) str
Compute the class name for parametrizations of generic classes.
This method can be overridden to achieve a custom naming scheme for generic BaseModels.
- Parameters:
params – Tuple of types of the class. Given a generic class Model with 2 type variables and a concrete model Model[str, int], the value (str, int) would be passed to params.
- Returns:
String representing the new class where params are passed to cls as type variables.
- Raises:
TypeError – Raised when trying to generate concrete names for non-generic models.
- classmethod model_rebuild(*, force: bool = False, raise_errors: bool = True, _parent_namespace_depth: int = 2, _types_namespace: MappingNamespace | None = None) bool | None
Try to rebuild the pydantic-core schema for the model.
This may be necessary when one of the annotations is a ForwardRef which could not be resolved during the initial attempt to build the schema, and automatic rebuilding fails.
- Parameters:
force – Whether to force the rebuilding of the model schema, defaults to False.
raise_errors – Whether to raise errors, defaults to True.
_parent_namespace_depth – The depth level of the parent namespace, defaults to 2.
_types_namespace – The types namespace, defaults to None.
- Returns:
Returns None if the schema is already “complete” and rebuilding was not required. If rebuilding _was_ required, returns True if rebuilding was successful, otherwise False.
- classmethod model_validate(obj: Any, *, strict: bool | None = None, extra: Literal['allow', 'ignore', 'forbid'] | None = None, from_attributes: bool | None = None, context: Any | None = None, by_alias: bool | None = None, by_name: bool | None = None) Self
Validate a pydantic model instance.
- Parameters:
obj – The object to validate.
strict – Whether to enforce types strictly.
extra – Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.
from_attributes – Whether to extract data from object attributes.
context – Additional context to pass to the validator.
by_alias – Whether to use the field’s alias when validating against the provided input data.
by_name – Whether to use the field’s name when validating against the provided input data.
- Raises:
ValidationError – If the object could not be validated.
- Returns:
The validated model instance.
- classmethod model_validate_json(json_data: str | bytes | bytearray, *, strict: bool | None = None, extra: Literal['allow', 'ignore', 'forbid'] | None = None, context: Any | None = None, by_alias: bool | None = None, by_name: bool | None = None) Self
- !!! abstract “Usage Documentation”
[JSON Parsing](../concepts/json.md#json-parsing)
Validate the given JSON data against the Pydantic model.
- Parameters:
json_data – The JSON data to validate.
strict – Whether to enforce types strictly.
extra – Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.
context – Extra variables to pass to the validator.
by_alias – Whether to use the field’s alias when validating against the provided input data.
by_name – Whether to use the field’s name when validating against the provided input data.
- Returns:
The validated Pydantic model.
- Raises:
ValidationError – If json_data is not a JSON string or the object could not be validated.
- classmethod model_validate_strings(obj: Any, *, strict: bool | None = None, extra: Literal['allow', 'ignore', 'forbid'] | None = None, context: Any | None = None, by_alias: bool | None = None, by_name: bool | None = None) Self
Validate the given object with string data against the Pydantic model.
- Parameters:
obj – The object containing string data to validate.
strict – Whether to enforce types strictly.
extra – Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.
context – Extra variables to pass to the validator.
by_alias – Whether to use the field’s alias when validating against the provided input data.
by_name – Whether to use the field’s name when validating against the provided input data.
- Returns:
The validated Pydantic model.
- classmethod validate_replace_flags(v: ReplaceFlagsType | str) ReplaceFlagsType | str[source]
Validate that replace_flags is a valid ReplaceFlagsType value.
- classmethod warn_on_unrecognized_fields(data: dict[str, Any]) dict[str, Any]
Warn users about unrecognized fields that don’t match model fields or aliases.
This validator checks incoming data against the model’s defined fields and their aliases, issuing warnings for any keys that don’t match. This helps catch typos and misunderstandings about the API without breaking initialization.
- copy(*, include: AbstractSetIntStr | MappingIntStrAny | None = None, exclude: AbstractSetIntStr | MappingIntStrAny | None = None, update: Dict[str, Any] | None = None, deep: bool = False) Self
Returns a copy of the model.
- !!! warning “Deprecated”
This method is now deprecated; use model_copy instead.
If you need include or exclude, use:
`python {test="skip" lint="skip"} data = self.model_dump(include=include, exclude=exclude, round_trip=True) data = {**data, **(update or {})} copied = self.model_validate(data) `- Parameters:
include – Optional set or mapping specifying which fields to include in the copied model.
exclude – Optional set or mapping specifying which fields to exclude in the copied model.
update – Optional dictionary of field-value pairs to override field values in the copied model.
deep – If True, the values of fields that are Pydantic models will be deep-copied.
- Returns:
A copy of the model with included, excluded and updated fields as specified.
- create(access_token: str | None = None, folder_id: int | None = None) BaseChart
Create a new chart via the Datawrapper API.
- Parameters:
access_token – Optional Datawrapper API access token. If not provided, will use DATAWRAPPER_ACCESS_TOKEN environment variable.
folder_id – Optional folder ID to create the chart in.
- Returns:
Self, to enable method chaining. The chart ID is stored in self.chart_id.
- Raises:
ValueError – If no access token is available or API returns invalid response.
Exception – If the API request fails.
- delete(access_token: str | None = None) bool
Delete the chart via the Datawrapper API.
- Parameters:
access_token – Optional Datawrapper API access token. If not provided, will use DATAWRAPPER_ACCESS_TOKEN environment variable.
- Returns:
True if the chart was deleted successfully.
- Raises:
ValueError – If no chart_id is set or no access token is available.
Exception – If the API request fails.
- display(access_token: str | None = None) IFrame
Display the chart as an IFrame in a Jupyter notebook.
- Parameters:
access_token – Optional Datawrapper API access token. If not provided, will use DATAWRAPPER_ACCESS_TOKEN environment variable.
- Returns:
An IPython.display.IFrame object displaying the chart.
- Raises:
ValueError – If no chart_id is set or no access token is available.
Exception – If the API request fails.
- duplicate(access_token: str | None = None) BaseChart
Duplicate the chart and create a new editable copy via the Datawrapper API.
- Parameters:
access_token – Optional Datawrapper API access token. If not provided, will use DATAWRAPPER_ACCESS_TOKEN environment variable.
- Returns:
A new BaseChart instance representing the duplicated chart.
- Raises:
ValueError – If no chart_id is set or no access token is available.
Exception – If the API request fails.
- export_pdf(*, width: int | None = None, height: int | None = None, plain: bool = False, unit: Literal['px', 'mm', 'inch'] = 'px', mode: Literal['rgb', 'cmyk'] = 'rgb', scale: int = 1, zoom: int = 2, transparent: bool = False, border_width: int = 0, border_color: str | None = None, logo: Literal['auto', 'on', 'off'] = 'auto', logo_id: str | None = None, dark: bool = False, ligatures: bool = True, full_vector: bool = False, download: bool = False, access_token: str | None = None, timeout: int = 30) bytes
Export chart as PDF and return the raw bytes.
- Parameters:
width – Width of visualization. If not specified, uses chart width.
height – Height of visualization. If not specified, uses chart height.
plain – If True, exports only the visualization without header/footer.
unit – Unit for measurements: “px”, “mm”, or “inch”.
mode – Color mode: “rgb” or “cmyk”.
scale – Size multiplier that changes actual dimensions (e.g., 2 = 2x size).
zoom – Resolution multiplier for sharper output at same visual size (e.g., 2 = 2x DPI).
transparent – If True, exports with transparent background.
border_width – Margin around visualization.
border_color – Color of the border (e.g., “#FFFFFF”). If not specified, uses chart background color.
logo – Logo display mode: “auto”, “on”, or “off”.
logo_id – Custom logo ID (pattern: ^[a-zA-Z0-9-]+$).
dark – If True, exports in dark mode.
ligatures – If True (default), enables typography ligatures.
full_vector – If True, exports as full vector output.
download – If True, includes download headers in response.
access_token – Optional Datawrapper API access token.
timeout – Timeout for the API request in seconds.
- Returns:
Raw PDF document data as bytes.
- Raises:
ValueError – If no chart_id is set or invalid parameters provided.
Exception – If the API request fails.
Example
>>> chart = BarChart.get(chart_id="abc123") >>> pdf_data = chart.export_pdf(unit="mm", mode="cmyk") >>> Path("chart.pdf").write_bytes(pdf_data)
- export_png(*, width: int | None = None, height: int | None = None, plain: bool = False, scale: int = 1, zoom: int = 2, transparent: bool = False, border_width: int = 0, border_color: str | None = None, logo: Literal['auto', 'on', 'off'] = 'auto', logo_id: str | None = None, dark: bool = False, ligatures: bool = True, full_vector: bool = False, download: bool = False, access_token: str | None = None, timeout: int = 30) bytes
Export chart as PNG and return the raw bytes.
- Parameters:
width – Width of visualization in pixels. If not specified, uses chart width.
height – Height of visualization in pixels. If not specified, uses chart height.
plain – If True, exports only the visualization without header/footer.
scale – Size multiplier that changes actual dimensions (e.g., 2 = 2x size).
zoom – Resolution multiplier for sharper output at same visual size (e.g., 2 = 2x DPI).
transparent – If True, exports with transparent background.
border_width – Margin around visualization in pixels.
border_color – Color of the border (e.g., “#FFFFFF”). If not specified, uses chart background color.
logo – Logo display mode: “auto”, “on”, or “off”.
logo_id – Custom logo ID (pattern: ^[a-zA-Z0-9-]+$).
dark – If True, exports in dark mode.
ligatures – If True (default), enables typography ligatures.
full_vector – If True, exports as full vector output.
download – If True, includes download headers in response.
access_token – Optional Datawrapper API access token.
timeout – Timeout for the API request in seconds.
- Returns:
Raw PNG image data as bytes.
- Raises:
ValueError – If no chart_id is set.
Exception – If the API request fails.
Example
>>> chart = LineChart.get(chart_id="abc123") >>> png_data = chart.export_png(zoom=3, transparent=True) >>> Path("chart.png").write_bytes(png_data)
- export_svg(*, width: int | None = None, height: int | None = None, plain: bool = False, scale: int = 1, zoom: int = 2, transparent: bool = False, border_width: int = 0, border_color: str | None = None, logo: Literal['auto', 'on', 'off'] = 'auto', logo_id: str | None = None, dark: bool = False, ligatures: bool = True, full_vector: bool = False, download: bool = False, access_token: str | None = None, timeout: int = 30) bytes
Export chart as SVG and return the raw bytes.
- Parameters:
width – Width of visualization. If not specified, uses chart width.
height – Height of visualization. If not specified, uses chart height.
plain – If True, exports only the visualization without header/footer.
scale – Size multiplier that changes actual dimensions (e.g., 2 = 2x size).
zoom – Resolution multiplier for sharper output at same visual size (e.g., 2 = 2x DPI).
transparent – If True, exports with transparent background.
border_width – Margin around visualization in pixels.
border_color – Color of the border (e.g., “#FFFFFF”). If not specified, uses chart background color.
logo – Logo display mode: “auto”, “on”, or “off”.
logo_id – Custom logo ID (pattern: ^[a-zA-Z0-9-]+$).
dark – If True, exports in dark mode.
ligatures – If True (default), enables typography ligatures.
full_vector – If True, exports as full vector output.
download – If True, includes download headers in response.
access_token – Optional Datawrapper API access token.
timeout – Timeout for the API request in seconds.
- Returns:
Raw SVG document data as bytes.
- Raises:
ValueError – If no chart_id is set.
Exception – If the API request fails.
Example
>>> chart = ColumnChart.get(chart_id="abc123") >>> svg_data = chart.export_svg(plain=True) >>> Path("chart.svg").write_bytes(svg_data)
- fork(access_token: str | None = None) BaseChart
Fork the chart and create an editable copy via the Datawrapper API.
- Parameters:
access_token – Optional Datawrapper API access token. If not provided, will use DATAWRAPPER_ACCESS_TOKEN environment variable.
- Returns:
A new BaseChart instance representing the forked chart.
- Raises:
ValueError – If no chart_id is set or no access token is available.
Exception – If the API request fails.
- get_display_urls(access_token: str | None = None) list[dict]
Get the URLs for the published chart, table or map.
- Parameters:
access_token – Optional Datawrapper API access token. If not provided, will use DATAWRAPPER_ACCESS_TOKEN environment variable.
- Returns:
A list of dictionaries containing the display URLs for the chart.
- Raises:
ValueError – If no chart_id is set or no access token is available.
Exception – If the API request fails.
- get_editor_url() str
Get the Datawrapper editor URL for this chart.
- Returns:
The Datawrapper editor URL as a string.
- Raises:
ValueError – If no chart_id is set.
- get_iframe_code(responsive: bool = False, access_token: str | None = None) str
Get the iframe embed code for the chart, table, or map.
- Parameters:
responsive – Whether to return responsive iframe code, by default False
access_token – Optional Datawrapper API access token. If not provided, will use DATAWRAPPER_ACCESS_TOKEN environment variable.
- Returns:
The iframe embed code as a string.
- Raises:
ValueError – If no chart_id is set or no access token is available.
Exception – If the API request fails.
- get_png_url() str
Get the fallback PNG image URL for noscript tags.
- Returns:
//datawrapper.dwcdn.net/{chart_id}/full.png
- Return type:
The PNG image URL in the format https
- Raises:
ValueError – If no chart_id is set.
- get_public_url() str
Get the public URL for the published chart.
- Returns:
//datawrapper.dwcdn.net/{chart_id}/
- Return type:
The public URL in the format https
- Raises:
ValueError – If no chart_id is set.
Note
This method returns the URL regardless of whether the chart is actually published. If the chart is not published, the URL will not be accessible. Use publish() to publish the chart before accessing this URL.
- model_copy(*, update: Mapping[str, Any] | None = None, deep: bool = False) Self
- !!! abstract “Usage Documentation”
[model_copy](../concepts/models.md#model-copy)
Returns a copy of the model.
- !!! note
The underlying instance’s [__dict__][object.__dict__] attribute is copied. This might have unexpected side effects if you store anything in it, on top of the model fields (e.g. the value of [cached properties][functools.cached_property]).
- Parameters:
update – Values to change/add in the new model. Note: the data is not validated before creating the new model. You should trust this data.
deep – Set to True to make a deep copy of the model.
- Returns:
New model instance.
- model_dump(*, mode: Literal['json', 'python'] | str = 'python', include: set[int] | set[str] | Mapping[int, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | Mapping[str, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | None = None, exclude: set[int] | set[str] | Mapping[int, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | Mapping[str, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | None = None, context: Any | None = None, by_alias: bool | None = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, exclude_computed_fields: bool = False, round_trip: bool = False, warnings: bool | Literal['none', 'warn', 'error'] = True, fallback: Callable[[Any], Any] | None = None, serialize_as_any: bool = False, polymorphic_serialization: bool | None = None) dict[str, Any]
- !!! abstract “Usage Documentation”
[model_dump](../concepts/serialization.md#python-mode)
Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
- Parameters:
mode – The mode in which to_python should run. If mode is ‘json’, the output will only contain JSON serializable types. If mode is ‘python’, the output may contain non-JSON-serializable Python objects.
include – A set of fields to include in the output.
exclude – A set of fields to exclude from the output.
context – Additional context to pass to the serializer.
by_alias – Whether to use the field’s alias in the dictionary key if defined.
exclude_unset – Whether to exclude fields that have not been explicitly set.
exclude_defaults – Whether to exclude fields that are set to their default value.
exclude_none – Whether to exclude fields that have a value of None.
exclude_computed_fields – Whether to exclude computed fields. While this can be useful for round-tripping, it is usually recommended to use the dedicated round_trip parameter instead.
round_trip – If True, dumped values should be valid as input for non-idempotent types such as Json[T].
warnings – How to handle serialization errors. False/”none” ignores them, True/”warn” logs errors, “error” raises a [PydanticSerializationError][pydantic_core.PydanticSerializationError].
fallback – A function to call when an unknown value is encountered. If not provided, a [PydanticSerializationError][pydantic_core.PydanticSerializationError] error is raised.
serialize_as_any – Whether to serialize fields with duck-typing serialization behavior.
polymorphic_serialization – Whether to use model and dataclass polymorphic serialization for this call.
- Returns:
A dictionary representation of the model.
- model_dump_json(*, indent: int | None = None, ensure_ascii: bool = False, include: set[int] | set[str] | Mapping[int, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | Mapping[str, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | None = None, exclude: set[int] | set[str] | Mapping[int, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | Mapping[str, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | None = None, context: Any | None = None, by_alias: bool | None = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, exclude_computed_fields: bool = False, round_trip: bool = False, warnings: bool | Literal['none', 'warn', 'error'] = True, fallback: Callable[[Any], Any] | None = None, serialize_as_any: bool = False, polymorphic_serialization: bool | None = None) str
- !!! abstract “Usage Documentation”
[model_dump_json](../concepts/serialization.md#json-mode)
Generates a JSON representation of the model using Pydantic’s to_json method.
- Parameters:
indent – Indentation to use in the JSON output. If None is passed, the output will be compact.
ensure_ascii – If True, the output is guaranteed to have all incoming non-ASCII characters escaped. If False (the default), these characters will be output as-is.
include – Field(s) to include in the JSON output.
exclude – Field(s) to exclude from the JSON output.
context – Additional context to pass to the serializer.
by_alias – Whether to serialize using field aliases.
exclude_unset – Whether to exclude fields that have not been explicitly set.
exclude_defaults – Whether to exclude fields that are set to their default value.
exclude_none – Whether to exclude fields that have a value of None.
exclude_computed_fields – Whether to exclude computed fields. While this can be useful for round-tripping, it is usually recommended to use the dedicated round_trip parameter instead.
round_trip – If True, dumped values should be valid as input for non-idempotent types such as Json[T].
warnings – How to handle serialization errors. False/”none” ignores them, True/”warn” logs errors, “error” raises a [PydanticSerializationError][pydantic_core.PydanticSerializationError].
fallback – A function to call when an unknown value is encountered. If not provided, a [PydanticSerializationError][pydantic_core.PydanticSerializationError] error is raised.
serialize_as_any – Whether to serialize fields with duck-typing serialization behavior.
polymorphic_serialization – Whether to use model and dataclass polymorphic serialization for this call.
- Returns:
A JSON string representation of the model.
- model_post_init(context: Any, /) None
Override this method to perform additional initialization after __init__ and model_construct. This is useful if you want to do some validation that requires the entire model to be initialized.
- publish(access_token: str | None = None) BaseChart
Publish the chart via the Datawrapper API.
- Parameters:
access_token – Optional Datawrapper API access token. If not provided, will use DATAWRAPPER_ACCESS_TOKEN environment variable.
- Returns:
Self, to enable method chaining.
- Raises:
ValueError – If no chart_id is set or no access token is available.
Exception – If the API request fails or publishing fails.
- serialize_data() str | None
Convert data to CSV string for API upload.
- Returns:
CSV string representation of the data, or None if data is empty.
- update(access_token: str | None = None) BaseChart
Update an existing chart via the Datawrapper API.
- Parameters:
access_token – Optional Datawrapper API access token. If not provided, will use DATAWRAPPER_ACCESS_TOKEN environment variable.
- Returns:
Self, to enable method chaining.
- Raises:
ValueError – If no chart_id is set or no access token is available.
Exception – If the API request fails.
- aria_description
The alternative text for screen readers
- auto_dark_mode
Whether the chart should automatically flip to dark mode when the user’s system is in dark mode
- axis_label_format: DateFormat | NumberFormat | str
The format of the axis labels (use DateFormat or NumberFormat enum or custom format strings)
- background: bool
Fill the background of the bar’s full potential with a light color
- bar_column: str
The column with the value for the bars
- base_color: str | int
The default color for the chart (palette index or hex string)
- block_labels: bool
Whether to move labels to a separate line
- byline
The byline that appears below the chart
- category_labels: dict[str, str]
Dictionary mapping category names to their display labels in the color legend
- category_order: list[str]
List defining the order in which categories appear in the chart and legend
- chart_id
The chart ID after creation (populated by create() method)
- chart_type: Literal['d3-bars']
The type of datawrapper chart to create
- color_category: dict[str, str]
A mapping of layer names to colors
- color_column: str
The name of the column with the color for the bars
- custom
A dictionary of custom tags to attach to the chart
- custom_grid_lines: list[Any]
Set custom grid lines
- custom_range: list[Any] | tuple[Any, Any]
The custom range for the x axis
- dark_mode_invert
Whether to invert colors in dark mode
- data
The data to use for the chart
- download_image
Whether to allow PNG download
- download_pdf
Whether to allow PDF download
- download_svg
Whether to allow SVG download
- embed
Whether to allow embedding
- exclude_from_color_key: list[str]
A list of column to exclude from the color key
- force_attribution
Whether to attribute the chart to datawrapper
- force_grid: bool
Whether or not to show the x grid
- forkable
Whether to allow other users to fork this visualization
- get_the_data
Whether to allow data downloads
- groups_column: str | None
The column to use for grouping bars
- hide_title
Whether or not to hide the title
- highlighted_series: list[str]
A list of the highlighted series
- intro
The intro text that appears above the chart
- label_alignment: Literal['left', 'right']
On which side are the labels aligned
- label_column: str
The column with the labels for the bars
- language
The locale of the chart, which defines decimal and thousand separators as well as translations of month and weekday names.
- logo
Whether to show a logo
- logo_id
The id of the logo to show
- model_config = {'arbitrary_types_allowed': True, 'json_schema_extra': {'examples': [{'background': True, 'chart-type': 'd3-bars', 'custom-range': [0, 100], 'data': Country turnout 0 Malta (2022) 85.6 1 Turkey (2023) 87.0 2 Belgium (2024) 88.5 3 Romania (2020) 33.2 4 Bulgaria (2024) 33.4 5 Albania (2021) 46.3 6 United Kingdom (2024) 60.0 7 Germany (2021) 76.4 8 Sweden (2022) 83.8 9 Spain (2023) 66.0 10 France (2024) 66.7, 'highlighted-series': ['Malta (2022)', 'Turkey (2023)', 'Belgium (2024)', 'Romania (2020)', 'Bulgaria (2024)', 'Albania (2021)'], 'sort-bars': True, 'source_name': 'Parties & Elections, 2024', 'source_url': 'https://parties-and-elections.eu/', 'tick-position': 'top', 'title': 'European countries with lowest & highest voter turnout'}]}, 'populate_by_name': True, 'strict': True, 'use_enum_values': True, 'validate_assignment': True, 'validate_by_alias': True, 'validate_by_name': True, 'validate_default': True}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- property model_extra: dict[str, Any] | None
Get extra fields set during validation.
- Returns:
A dictionary of extra fields, or None if config.extra is not set to “allow”.
- property model_fields_set: set[str]
Returns the set of fields that have been explicitly set on this model instance.
- Returns:
- A set of strings representing the fields that have been set,
i.e. that were not filled from defaults.
- notes
The footnotes that appear below the chart
- overlays: list[BarOverlay | dict[str, Any]]
A list of bar overlays
- replace_flags: ReplaceFlagsType | str
Whether to replace country codes with flag
- reverse_order: bool
Whether to reverse the sort order
- rules: bool
Draw a separating line between bars
Whether to show social media share buttons
What URL to share
- show_category_labels: bool
Whether to show the value labels
- show_color_key: bool
Whether to show the color key
- show_group_labels: bool
Whether to show the group labels
- show_value_labels: bool
Whether or not to show value labels with the bars
- sort_bars: bool
Whether to sort the bars
- source_name
The source name that appears below the chart
- source_url
The source URL that appears below the chart
- stack_color_legend: bool
Whether to stack the color key
- swap_labels: bool
Whether to swap labels and values
- theme
The theme of the chart
- thick_bars: bool
Make the bars thicker
- tick_position: Literal['top', 'bottom']
The position of the ticks
- title
The headline that appears above the chart
- transformations
The metadata options for the data columns in the “Check and Describe” tab
- value_label_alignment: ValueLabelAlignment | str
The alignment of the value labels
- value_label_format: DateFormat | NumberFormat | str
The format of the value labels (use DateFormat or NumberFormat enum or custom format strings)
Column Chart
- class datawrapper.charts.ColumnChart(*, chart_type: Literal['column-chart'] = 'column-chart', data: DataFrame | list[dict] = <factory>, transformations: Transform | dict[str, ~typing.Any]=<factory>, title: str = '', intro: str = '', notes: str = '', source_name: str = '', source_url: str = '', byline: str = '', aria_description: str = '', hide_title: bool = False, language: str = 'en-US', theme: str = 'datawrapper', autoDarkMode: bool = False, dark_mode_invert: bool = True, get_the_data: bool = False, download_image: bool = False, download_pdf: bool = False, download_svg: bool = False, embed: bool = False, force_attribution: bool = False, share_buttons: bool = False, share_url: str = '', logo: bool = False, logo_id: str = '', custom: dict[str, ~typing.Any]=<factory>, forkable: bool = True, chart_id: str | None = None, custom_ticks_x: list[Any] | None = None, custom_ticks_y: list[Any] | None = None, custom_range_x: list[~typing.Any] | tuple[~typing.Any, ~typing.Any] | None=None, custom_range_y: list[~typing.Any] | tuple[~typing.Any, ~typing.Any] | None=None, x_grid_format: DateFormat | NumberFormat | str | None = None, y_grid_format: NumberFormat | str | None = None, x_grid: GridDisplay | str | bool | None = 'off', y_grid: GridDisplay | str | bool | None = 'on', text_annotations: Any, ~typing.Any]]=<factory>, range_annotations: Any, ~typing.Any]]=<factory>, y_grid_labels: GridLabelPosition | str = 'outside', y_grid_label_align: GridLabelAlign | str = 'left', base_color: str | int = 0, negative_color: str | None = None, color_category: dict[str, str]=<factory>, category_labels: dict[str, str]=<factory>, category_order: list[str] = <factory>, exclude_from_color_key: list[str] = <factory>, bar_padding: int = 30, plot_height_mode: PlotHeightMode | str = 'fixed', plot_height_fixed: int | float = 300, plot_height_ratio: float = 0.5, show_color_key: bool = False, show_value_labels: ValueLabelDisplay | str = 'hover', value_labels_format: DateFormat | NumberFormat | str = '', value_labels_placement: ValueLabelPlacement | str = 'outside', highlighted_series: list[str] = <factory>)[source]
Bases:
AnnotationsMixin,GridDisplayMixin,GridFormatMixin,CustomRangeMixin,CustomTicksMixin,BaseChartA base class for the Datawrapper API’s column chart.
- classmethod convert_column_format_dicts(data: dict[str, Any]) dict[str, Any]
Convert dictionary items in transformation to Transform objects.
- classmethod deserialize_data(csv_data: str | DataFrame) DataFrame
Parse CSV string from Datawrapper API into DataFrame.
- Parameters:
csv_data – The CSV data from the chart data endpoint
- Returns:
DataFrame containing the parsed CSV data
- classmethod deserialize_model(api_response: dict[str, Any]) dict[str, Any][source]
Parse Datawrapper API response including column chart specific fields.
- Parameters:
api_response – The JSON response from the chart metadata endpoint
chart_data – The CSV data from the chart data endpoint
- Returns:
Dictionary that can be used to initialize the ColumnChart model
- classmethod get(chart_id: str, access_token: str | None = None) BaseChart
Fetch an existing chart from the Datawrapper API.
- Parameters:
chart_id – The ID of the chart to fetch
access_token – Optional Datawrapper API access token. If not provided, will use DATAWRAPPER_ACCESS_TOKEN environment variable.
- Returns:
An instance of the chart class with data populated from the API.
- Raises:
ValueError – If no access token is available or chart type doesn’t match.
Exception – If the API request fails.
- classmethod model_construct(_fields_set: set[str] | None = None, **values: Any) Self
Creates a new instance of the Model class with validated data.
Creates a new model setting __dict__ and __pydantic_fields_set__ from trusted or pre-validated data. Default values are respected, but no other validation is performed.
- !!! note
model_construct() generally respects the model_config.extra setting on the provided model. That is, if model_config.extra == ‘allow’, then all extra passed values are added to the model instance’s __dict__ and __pydantic_extra__ fields. If model_config.extra == ‘ignore’ (the default), then all extra passed values are ignored. Because no validation is performed with a call to model_construct(), having model_config.extra == ‘forbid’ does not result in an error if extra values are passed, but they will be ignored.
- Parameters:
_fields_set – A set of field names that were originally explicitly set during instantiation. If provided, this is directly used for the [model_fields_set][pydantic.BaseModel.model_fields_set] attribute. Otherwise, the field names from the values argument will be used.
values – Trusted or pre-validated data dictionary.
- Returns:
A new instance of the Model class with validated data.
- classmethod model_json_schema(by_alias: bool = True, ref_template: str = '#/$defs/{model}', schema_generator: type[GenerateJsonSchema] = <class 'pydantic.json_schema.GenerateJsonSchema'>, mode: Literal['validation', 'serialization']='validation', *, union_format: Literal['any_of', 'primitive_type_array']='any_of') dict[str, Any]
Generates a JSON schema for a model class.
- Parameters:
by_alias – Whether to use attribute aliases or not.
ref_template – The reference template.
union_format –
The format to use when combining schemas from unions together. Can be one of:
’any_of’: Use the [anyOf](https://json-schema.org/understanding-json-schema/reference/combining#anyOf)
keyword to combine schemas (the default). - ‘primitive_type_array’: Use the [type](https://json-schema.org/understanding-json-schema/reference/type) keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive type (string, boolean, null, integer or number) or contains constraints/metadata, falls back to any_of.
schema_generator – To override the logic used to generate the JSON schema, as a subclass of GenerateJsonSchema with your desired modifications
mode – The mode in which to generate the schema.
- Returns:
The JSON schema for the given model class.
- classmethod model_parametrized_name(params: tuple[type[Any], ...]) str
Compute the class name for parametrizations of generic classes.
This method can be overridden to achieve a custom naming scheme for generic BaseModels.
- Parameters:
params – Tuple of types of the class. Given a generic class Model with 2 type variables and a concrete model Model[str, int], the value (str, int) would be passed to params.
- Returns:
String representing the new class where params are passed to cls as type variables.
- Raises:
TypeError – Raised when trying to generate concrete names for non-generic models.
- classmethod model_rebuild(*, force: bool = False, raise_errors: bool = True, _parent_namespace_depth: int = 2, _types_namespace: MappingNamespace | None = None) bool | None
Try to rebuild the pydantic-core schema for the model.
This may be necessary when one of the annotations is a ForwardRef which could not be resolved during the initial attempt to build the schema, and automatic rebuilding fails.
- Parameters:
force – Whether to force the rebuilding of the model schema, defaults to False.
raise_errors – Whether to raise errors, defaults to True.
_parent_namespace_depth – The depth level of the parent namespace, defaults to 2.
_types_namespace – The types namespace, defaults to None.
- Returns:
Returns None if the schema is already “complete” and rebuilding was not required. If rebuilding _was_ required, returns True if rebuilding was successful, otherwise False.
- classmethod model_validate(obj: Any, *, strict: bool | None = None, extra: Literal['allow', 'ignore', 'forbid'] | None = None, from_attributes: bool | None = None, context: Any | None = None, by_alias: bool | None = None, by_name: bool | None = None) Self
Validate a pydantic model instance.
- Parameters:
obj – The object to validate.
strict – Whether to enforce types strictly.
extra – Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.
from_attributes – Whether to extract data from object attributes.
context – Additional context to pass to the validator.
by_alias – Whether to use the field’s alias when validating against the provided input data.
by_name – Whether to use the field’s name when validating against the provided input data.
- Raises:
ValidationError – If the object could not be validated.
- Returns:
The validated model instance.
- classmethod model_validate_json(json_data: str | bytes | bytearray, *, strict: bool | None = None, extra: Literal['allow', 'ignore', 'forbid'] | None = None, context: Any | None = None, by_alias: bool | None = None, by_name: bool | None = None) Self
- !!! abstract “Usage Documentation”
[JSON Parsing](../concepts/json.md#json-parsing)
Validate the given JSON data against the Pydantic model.
- Parameters:
json_data – The JSON data to validate.
strict – Whether to enforce types strictly.
extra – Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.
context – Extra variables to pass to the validator.
by_alias – Whether to use the field’s alias when validating against the provided input data.
by_name – Whether to use the field’s name when validating against the provided input data.
- Returns:
The validated Pydantic model.
- Raises:
ValidationError – If json_data is not a JSON string or the object could not be validated.
- classmethod model_validate_strings(obj: Any, *, strict: bool | None = None, extra: Literal['allow', 'ignore', 'forbid'] | None = None, context: Any | None = None, by_alias: bool | None = None, by_name: bool | None = None) Self
Validate the given object with string data against the Pydantic model.
- Parameters:
obj – The object containing string data to validate.
strict – Whether to enforce types strictly.
extra – Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.
context – Extra variables to pass to the validator.
by_alias – Whether to use the field’s alias when validating against the provided input data.
by_name – Whether to use the field’s name when validating against the provided input data.
- Returns:
The validated Pydantic model.
- classmethod validate_plot_height_mode(v: PlotHeightMode | str) PlotHeightMode | str[source]
Validate that plot_height_mode is a valid PlotHeightMode value.
- classmethod warn_on_unrecognized_fields(data: dict[str, Any]) dict[str, Any]
Warn users about unrecognized fields that don’t match model fields or aliases.
This validator checks incoming data against the model’s defined fields and their aliases, issuing warnings for any keys that don’t match. This helps catch typos and misunderstandings about the API without breaking initialization.
- copy(*, include: AbstractSetIntStr | MappingIntStrAny | None = None, exclude: AbstractSetIntStr | MappingIntStrAny | None = None, update: Dict[str, Any] | None = None, deep: bool = False) Self
Returns a copy of the model.
- !!! warning “Deprecated”
This method is now deprecated; use model_copy instead.
If you need include or exclude, use:
`python {test="skip" lint="skip"} data = self.model_dump(include=include, exclude=exclude, round_trip=True) data = {**data, **(update or {})} copied = self.model_validate(data) `- Parameters:
include – Optional set or mapping specifying which fields to include in the copied model.
exclude – Optional set or mapping specifying which fields to exclude in the copied model.
update – Optional dictionary of field-value pairs to override field values in the copied model.
deep – If True, the values of fields that are Pydantic models will be deep-copied.
- Returns:
A copy of the model with included, excluded and updated fields as specified.
- create(access_token: str | None = None, folder_id: int | None = None) BaseChart
Create a new chart via the Datawrapper API.
- Parameters:
access_token – Optional Datawrapper API access token. If not provided, will use DATAWRAPPER_ACCESS_TOKEN environment variable.
folder_id – Optional folder ID to create the chart in.
- Returns:
Self, to enable method chaining. The chart ID is stored in self.chart_id.
- Raises:
ValueError – If no access token is available or API returns invalid response.
Exception – If the API request fails.
- delete(access_token: str | None = None) bool
Delete the chart via the Datawrapper API.
- Parameters:
access_token – Optional Datawrapper API access token. If not provided, will use DATAWRAPPER_ACCESS_TOKEN environment variable.
- Returns:
True if the chart was deleted successfully.
- Raises:
ValueError – If no chart_id is set or no access token is available.
Exception – If the API request fails.
- display(access_token: str | None = None) IFrame
Display the chart as an IFrame in a Jupyter notebook.
- Parameters:
access_token – Optional Datawrapper API access token. If not provided, will use DATAWRAPPER_ACCESS_TOKEN environment variable.
- Returns:
An IPython.display.IFrame object displaying the chart.
- Raises:
ValueError – If no chart_id is set or no access token is available.
Exception – If the API request fails.
- duplicate(access_token: str | None = None) BaseChart
Duplicate the chart and create a new editable copy via the Datawrapper API.
- Parameters:
access_token – Optional Datawrapper API access token. If not provided, will use DATAWRAPPER_ACCESS_TOKEN environment variable.
- Returns:
A new BaseChart instance representing the duplicated chart.
- Raises:
ValueError – If no chart_id is set or no access token is available.
Exception – If the API request fails.
- export_pdf(*, width: int | None = None, height: int | None = None, plain: bool = False, unit: Literal['px', 'mm', 'inch'] = 'px', mode: Literal['rgb', 'cmyk'] = 'rgb', scale: int = 1, zoom: int = 2, transparent: bool = False, border_width: int = 0, border_color: str | None = None, logo: Literal['auto', 'on', 'off'] = 'auto', logo_id: str | None = None, dark: bool = False, ligatures: bool = True, full_vector: bool = False, download: bool = False, access_token: str | None = None, timeout: int = 30) bytes
Export chart as PDF and return the raw bytes.
- Parameters:
width – Width of visualization. If not specified, uses chart width.
height – Height of visualization. If not specified, uses chart height.
plain – If True, exports only the visualization without header/footer.
unit – Unit for measurements: “px”, “mm”, or “inch”.
mode – Color mode: “rgb” or “cmyk”.
scale – Size multiplier that changes actual dimensions (e.g., 2 = 2x size).
zoom – Resolution multiplier for sharper output at same visual size (e.g., 2 = 2x DPI).
transparent – If True, exports with transparent background.
border_width – Margin around visualization.
border_color – Color of the border (e.g., “#FFFFFF”). If not specified, uses chart background color.
logo – Logo display mode: “auto”, “on”, or “off”.
logo_id – Custom logo ID (pattern: ^[a-zA-Z0-9-]+$).
dark – If True, exports in dark mode.
ligatures – If True (default), enables typography ligatures.
full_vector – If True, exports as full vector output.
download – If True, includes download headers in response.
access_token – Optional Datawrapper API access token.
timeout – Timeout for the API request in seconds.
- Returns:
Raw PDF document data as bytes.
- Raises:
ValueError – If no chart_id is set or invalid parameters provided.
Exception – If the API request fails.
Example
>>> chart = BarChart.get(chart_id="abc123") >>> pdf_data = chart.export_pdf(unit="mm", mode="cmyk") >>> Path("chart.pdf").write_bytes(pdf_data)
- export_png(*, width: int | None = None, height: int | None = None, plain: bool = False, scale: int = 1, zoom: int = 2, transparent: bool = False, border_width: int = 0, border_color: str | None = None, logo: Literal['auto', 'on', 'off'] = 'auto', logo_id: str | None = None, dark: bool = False, ligatures: bool = True, full_vector: bool = False, download: bool = False, access_token: str | None = None, timeout: int = 30) bytes
Export chart as PNG and return the raw bytes.
- Parameters:
width – Width of visualization in pixels. If not specified, uses chart width.
height – Height of visualization in pixels. If not specified, uses chart height.
plain – If True, exports only the visualization without header/footer.
scale – Size multiplier that changes actual dimensions (e.g., 2 = 2x size).
zoom – Resolution multiplier for sharper output at same visual size (e.g., 2 = 2x DPI).
transparent – If True, exports with transparent background.
border_width – Margin around visualization in pixels.
border_color – Color of the border (e.g., “#FFFFFF”). If not specified, uses chart background color.
logo – Logo display mode: “auto”, “on”, or “off”.
logo_id – Custom logo ID (pattern: ^[a-zA-Z0-9-]+$).
dark – If True, exports in dark mode.
ligatures – If True (default), enables typography ligatures.
full_vector – If True, exports as full vector output.
download – If True, includes download headers in response.
access_token – Optional Datawrapper API access token.
timeout – Timeout for the API request in seconds.
- Returns:
Raw PNG image data as bytes.
- Raises:
ValueError – If no chart_id is set.
Exception – If the API request fails.
Example
>>> chart = LineChart.get(chart_id="abc123") >>> png_data = chart.export_png(zoom=3, transparent=True) >>> Path("chart.png").write_bytes(png_data)
- export_svg(*, width: int | None = None, height: int | None = None, plain: bool = False, scale: int = 1, zoom: int = 2, transparent: bool = False, border_width: int = 0, border_color: str | None = None, logo: Literal['auto', 'on', 'off'] = 'auto', logo_id: str | None = None, dark: bool = False, ligatures: bool = True, full_vector: bool = False, download: bool = False, access_token: str | None = None, timeout: int = 30) bytes
Export chart as SVG and return the raw bytes.
- Parameters:
width – Width of visualization. If not specified, uses chart width.
height – Height of visualization. If not specified, uses chart height.
plain – If True, exports only the visualization without header/footer.
scale – Size multiplier that changes actual dimensions (e.g., 2 = 2x size).
zoom – Resolution multiplier for sharper output at same visual size (e.g., 2 = 2x DPI).
transparent – If True, exports with transparent background.
border_width – Margin around visualization in pixels.
border_color – Color of the border (e.g., “#FFFFFF”). If not specified, uses chart background color.
logo – Logo display mode: “auto”, “on”, or “off”.
logo_id – Custom logo ID (pattern: ^[a-zA-Z0-9-]+$).
dark – If True, exports in dark mode.
ligatures – If True (default), enables typography ligatures.
full_vector – If True, exports as full vector output.
download – If True, includes download headers in response.
access_token – Optional Datawrapper API access token.
timeout – Timeout for the API request in seconds.
- Returns:
Raw SVG document data as bytes.
- Raises:
ValueError – If no chart_id is set.
Exception – If the API request fails.
Example
>>> chart = ColumnChart.get(chart_id="abc123") >>> svg_data = chart.export_svg(plain=True) >>> Path("chart.svg").write_bytes(svg_data)
- fork(access_token: str | None = None) BaseChart
Fork the chart and create an editable copy via the Datawrapper API.
- Parameters:
access_token – Optional Datawrapper API access token. If not provided, will use DATAWRAPPER_ACCESS_TOKEN environment variable.
- Returns:
A new BaseChart instance representing the forked chart.
- Raises:
ValueError – If no chart_id is set or no access token is available.
Exception – If the API request fails.
- get_display_urls(access_token: str | None = None) list[dict]
Get the URLs for the published chart, table or map.
- Parameters:
access_token – Optional Datawrapper API access token. If not provided, will use DATAWRAPPER_ACCESS_TOKEN environment variable.
- Returns:
A list of dictionaries containing the display URLs for the chart.
- Raises:
ValueError – If no chart_id is set or no access token is available.
Exception – If the API request fails.
- get_editor_url() str
Get the Datawrapper editor URL for this chart.
- Returns:
The Datawrapper editor URL as a string.
- Raises:
ValueError – If no chart_id is set.
- get_iframe_code(responsive: bool = False, access_token: str | None = None) str
Get the iframe embed code for the chart, table, or map.
- Parameters:
responsive – Whether to return responsive iframe code, by default False
access_token – Optional Datawrapper API access token. If not provided, will use DATAWRAPPER_ACCESS_TOKEN environment variable.
- Returns:
The iframe embed code as a string.
- Raises:
ValueError – If no chart_id is set or no access token is available.
Exception – If the API request fails.
- get_png_url() str
Get the fallback PNG image URL for noscript tags.
- Returns:
//datawrapper.dwcdn.net/{chart_id}/full.png
- Return type:
The PNG image URL in the format https
- Raises:
ValueError – If no chart_id is set.
- get_public_url() str
Get the public URL for the published chart.
- Returns:
//datawrapper.dwcdn.net/{chart_id}/
- Return type:
The public URL in the format https
- Raises:
ValueError – If no chart_id is set.
Note
This method returns the URL regardless of whether the chart is actually published. If the chart is not published, the URL will not be accessible. Use publish() to publish the chart before accessing this URL.
- model_copy(*, update: Mapping[str, Any] | None = None, deep: bool = False) Self
- !!! abstract “Usage Documentation”
[model_copy](../concepts/models.md#model-copy)
Returns a copy of the model.
- !!! note
The underlying instance’s [__dict__][object.__dict__] attribute is copied. This might have unexpected side effects if you store anything in it, on top of the model fields (e.g. the value of [cached properties][functools.cached_property]).
- Parameters:
update – Values to change/add in the new model. Note: the data is not validated before creating the new model. You should trust this data.
deep – Set to True to make a deep copy of the model.
- Returns:
New model instance.
- model_dump(*, mode: Literal['json', 'python'] | str = 'python', include: set[int] | set[str] | Mapping[int, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | Mapping[str, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | None = None, exclude: set[int] | set[str] | Mapping[int, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | Mapping[str, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | None = None, context: Any | None = None, by_alias: bool | None = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, exclude_computed_fields: bool = False, round_trip: bool = False, warnings: bool | Literal['none', 'warn', 'error'] = True, fallback: Callable[[Any], Any] | None = None, serialize_as_any: bool = False, polymorphic_serialization: bool | None = None) dict[str, Any]
- !!! abstract “Usage Documentation”
[model_dump](../concepts/serialization.md#python-mode)
Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
- Parameters:
mode – The mode in which to_python should run. If mode is ‘json’, the output will only contain JSON serializable types. If mode is ‘python’, the output may contain non-JSON-serializable Python objects.
include – A set of fields to include in the output.
exclude – A set of fields to exclude from the output.
context – Additional context to pass to the serializer.
by_alias – Whether to use the field’s alias in the dictionary key if defined.
exclude_unset – Whether to exclude fields that have not been explicitly set.
exclude_defaults – Whether to exclude fields that are set to their default value.
exclude_none – Whether to exclude fields that have a value of None.
exclude_computed_fields – Whether to exclude computed fields. While this can be useful for round-tripping, it is usually recommended to use the dedicated round_trip parameter instead.
round_trip – If True, dumped values should be valid as input for non-idempotent types such as Json[T].
warnings – How to handle serialization errors. False/”none” ignores them, True/”warn” logs errors, “error” raises a [PydanticSerializationError][pydantic_core.PydanticSerializationError].
fallback – A function to call when an unknown value is encountered. If not provided, a [PydanticSerializationError][pydantic_core.PydanticSerializationError] error is raised.
serialize_as_any – Whether to serialize fields with duck-typing serialization behavior.
polymorphic_serialization – Whether to use model and dataclass polymorphic serialization for this call.
- Returns:
A dictionary representation of the model.
- model_dump_json(*, indent: int | None = None, ensure_ascii: bool = False, include: set[int] | set[str] | Mapping[int, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | Mapping[str, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | None = None, exclude: set[int] | set[str] | Mapping[int, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | Mapping[str, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | None = None, context: Any | None = None, by_alias: bool | None = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, exclude_computed_fields: bool = False, round_trip: bool = False, warnings: bool | Literal['none', 'warn', 'error'] = True, fallback: Callable[[Any], Any] | None = None, serialize_as_any: bool = False, polymorphic_serialization: bool | None = None) str
- !!! abstract “Usage Documentation”
[model_dump_json](../concepts/serialization.md#json-mode)
Generates a JSON representation of the model using Pydantic’s to_json method.
- Parameters:
indent – Indentation to use in the JSON output. If None is passed, the output will be compact.
ensure_ascii – If True, the output is guaranteed to have all incoming non-ASCII characters escaped. If False (the default), these characters will be output as-is.
include – Field(s) to include in the JSON output.
exclude – Field(s) to exclude from the JSON output.
context – Additional context to pass to the serializer.
by_alias – Whether to serialize using field aliases.
exclude_unset – Whether to exclude fields that have not been explicitly set.
exclude_defaults – Whether to exclude fields that are set to their default value.
exclude_none – Whether to exclude fields that have a value of None.
exclude_computed_fields – Whether to exclude computed fields. While this can be useful for round-tripping, it is usually recommended to use the dedicated round_trip parameter instead.
round_trip – If True, dumped values should be valid as input for non-idempotent types such as Json[T].
warnings – How to handle serialization errors. False/”none” ignores them, True/”warn” logs errors, “error” raises a [PydanticSerializationError][pydantic_core.PydanticSerializationError].
fallback – A function to call when an unknown value is encountered. If not provided, a [PydanticSerializationError][pydantic_core.PydanticSerializationError] error is raised.
serialize_as_any – Whether to serialize fields with duck-typing serialization behavior.
polymorphic_serialization – Whether to use model and dataclass polymorphic serialization for this call.
- Returns:
A JSON string representation of the model.
- model_post_init(context: Any, /) None
Override this method to perform additional initialization after __init__ and model_construct. This is useful if you want to do some validation that requires the entire model to be initialized.
- publish(access_token: str | None = None) BaseChart
Publish the chart via the Datawrapper API.
- Parameters:
access_token – Optional Datawrapper API access token. If not provided, will use DATAWRAPPER_ACCESS_TOKEN environment variable.
- Returns:
Self, to enable method chaining.
- Raises:
ValueError – If no chart_id is set or no access token is available.
Exception – If the API request fails or publishing fails.
- serialize_data() str | None
Convert data to CSV string for API upload.
- Returns:
CSV string representation of the data, or None if data is empty.
- update(access_token: str | None = None) BaseChart
Update an existing chart via the Datawrapper API.
- Parameters:
access_token – Optional Datawrapper API access token. If not provided, will use DATAWRAPPER_ACCESS_TOKEN environment variable.
- Returns:
Self, to enable method chaining.
- Raises:
ValueError – If no chart_id is set or no access token is available.
Exception – If the API request fails.
- aria_description
The alternative text for screen readers
- auto_dark_mode
Whether the chart should automatically flip to dark mode when the user’s system is in dark mode
- bar_padding: int
The padding between bars as a percentage of the bar width
- base_color: str | int
The base color for the chart (palette index or hex string)
- byline
The byline that appears below the chart
- category_labels: dict[str, str]
Dictionary mapping category names to their display labels in the color legend
- category_order: list[str]
List defining the order in which categories appear in the chart and legend
- chart_id
The chart ID after creation (populated by create() method)
- chart_type: Literal['column-chart']
The type of datawrapper chart to create
- color_category: dict[str, str]
A mapping of layer names to colors
- custom
A dictionary of custom tags to attach to the chart
- dark_mode_invert
Whether to invert colors in dark mode
- data
The data to use for the chart
- download_image
Whether to allow PNG download
- download_pdf
Whether to allow PDF download
- download_svg
Whether to allow SVG download
- embed
Whether to allow embedding
- exclude_from_color_key: list[str]
A list of columns to exclude from the color key
- force_attribution
Whether to attribute the chart to datawrapper
- forkable
Whether to allow other users to fork this visualization
- get_the_data
Whether to allow data downloads
- hide_title
Whether or not to hide the title
- highlighted_series: list[str]
A list of the highlighted series
- intro
The intro text that appears above the chart
- language
The locale of the chart, which defines decimal and thousand separators as well as translations of month and weekday names.
- logo
Whether to show a logo
- logo_id
The id of the logo to show
- model_config = {'arbitrary_types_allowed': True, 'json_schema_extra': {'examples': [{'chart-type': 'column-chart', 'data': date Value 0 2020/01 4.0 1 2020/02 3.8 2 2020/03 4.5, 'source_name': 'Bureau of Labor Statistics', 'title': 'Unemployment Rate Over Time', 'value_labels': 'always', 'y_grid': True}]}, 'populate_by_name': True, 'strict': True, 'use_enum_values': True, 'validate_assignment': True, 'validate_by_alias': True, 'validate_by_name': True, 'validate_default': True}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- property model_extra: dict[str, Any] | None
Get extra fields set during validation.
- Returns:
A dictionary of extra fields, or None if config.extra is not set to “allow”.
- property model_fields_set: set[str]
Returns the set of fields that have been explicitly set on this model instance.
- Returns:
- A set of strings representing the fields that have been set,
i.e. that were not filled from defaults.
- negative_color: str | None
The negative color to use, if you want one
- notes
The footnotes that appear below the chart
- plot_height_fixed: int | float
The fixed height of the plot
- plot_height_mode: PlotHeightMode | str
How to set the plot height
- plot_height_ratio: float
The ratio of the plot height
Whether to show social media share buttons
What URL to share
- show_color_key: bool
Whether or not to show the color key above the chart
- show_value_labels: ValueLabelDisplay | str
Whether or not to show value labels
- source_name
The source name that appears below the chart
- source_url
The source URL that appears below the chart
- theme
The theme of the chart
- title
The headline that appears above the chart
- transformations
The metadata options for the data columns in the “Check and Describe” tab
- value_labels_format: DateFormat | NumberFormat | str
How to format the value labels (use DateFormat or NumberFormat enum or custom format strings)
- value_labels_placement: ValueLabelPlacement | str
Where to place the value labels
- y_grid_label_align: GridLabelAlign | str
Which side to put the y-axis labels on
- y_grid_labels: GridLabelPosition | str
The labeling of the y grid labels
Line Chart
- class datawrapper.charts.LineChart(*, chart_type: Literal['d3-lines'] = 'd3-lines', data: DataFrame | list[dict] = <factory>, transformations: Transform | dict[str, ~typing.Any]=<factory>, title: str = '', intro: str = '', notes: str = '', source_name: str = '', source_url: str = '', byline: str = '', aria_description: str = '', hide_title: bool = False, language: str = 'en-US', theme: str = 'datawrapper', autoDarkMode: bool = False, dark_mode_invert: bool = True, get_the_data: bool = False, download_image: bool = False, download_pdf: bool = False, download_svg: bool = False, embed: bool = False, force_attribution: bool = False, share_buttons: bool = False, share_url: str = '', logo: bool = False, logo_id: str = '', custom: dict[str, ~typing.Any]=<factory>, forkable: bool = True, chart_id: str | None = None, custom_ticks_x: list[Any] | None = None, custom_ticks_y: list[Any] | None = None, custom_range_x: list[~typing.Any] | tuple[~typing.Any, ~typing.Any] | None=None, custom_range_y: list[~typing.Any] | tuple[~typing.Any, ~typing.Any] | None=None, x_grid_format: DateFormat | NumberFormat | str | None = None, y_grid_format: NumberFormat | str | None = None, x_grid: GridDisplay | str | bool | None = 'off', y_grid: GridDisplay | str | bool | None = 'on', text_annotations: Any, ~typing.Any]]=<factory>, range_annotations: Any, ~typing.Any]]=<factory>, x_column: str | None = None, y_grid_labels: GridLabelPosition | str = 'auto', y_grid_label_align: GridLabelAlign | str = 'left', scale_y: Literal['linear', 'log']='linear', y_grid_subdivide: bool = True, base_color: str | int = 0, interpolation: LineInterpolation | str = 'linear', connector_lines: bool = False, color_category: dict[str, str]=<factory>, lines: list[~datawrapper.charts.line.Line | dict[str, ~typing.Any]]=<factory>, area_fills: list[~datawrapper.charts.line.AreaFill | dict[str, ~typing.Any]]=<factory>, stack_color_legend: bool = False, label_colors: bool = False, label_margin: int = 0, value_labels_format: DateFormat | NumberFormat | str = '', value_label_colors: bool = False, show_tooltips: bool = True, tooltip_x_format: DateFormat | NumberFormat | str = '', tooltip_number_format: DateFormat | NumberFormat | str = '', plot_height_mode: PlotHeightMode | str = 'fixed', plot_height_fixed: int | float = 300, plot_height_ratio: float = 0.5)[source]
Bases:
AnnotationsMixin,GridDisplayMixin,GridFormatMixin,CustomRangeMixin,CustomTicksMixin,BaseChartA base class for the Datawrapper API’s line chart.
- classmethod convert_column_format_dicts(data: dict[str, Any]) dict[str, Any]
Convert dictionary items in transformation to Transform objects.
- classmethod deserialize_data(csv_data: str | DataFrame) DataFrame
Parse CSV string from Datawrapper API into DataFrame.
- Parameters:
csv_data – The CSV data from the chart data endpoint
- Returns:
DataFrame containing the parsed CSV data
- classmethod deserialize_model(api_response: dict[str, Any]) dict[str, Any][source]
Parse Datawrapper API response including line chart specific fields.
- Parameters:
api_response – The JSON response from the chart metadata endpoint
chart_data – The CSV data from the chart data endpoint
- Returns:
Dictionary that can be used to initialize the LineChart model
- classmethod get(chart_id: str, access_token: str | None = None) BaseChart
Fetch an existing chart from the Datawrapper API.
- Parameters:
chart_id – The ID of the chart to fetch
access_token – Optional Datawrapper API access token. If not provided, will use DATAWRAPPER_ACCESS_TOKEN environment variable.
- Returns:
An instance of the chart class with data populated from the API.
- Raises:
ValueError – If no access token is available or chart type doesn’t match.
Exception – If the API request fails.
- classmethod model_construct(_fields_set: set[str] | None = None, **values: Any) Self
Creates a new instance of the Model class with validated data.
Creates a new model setting __dict__ and __pydantic_fields_set__ from trusted or pre-validated data. Default values are respected, but no other validation is performed.
- !!! note
model_construct() generally respects the model_config.extra setting on the provided model. That is, if model_config.extra == ‘allow’, then all extra passed values are added to the model instance’s __dict__ and __pydantic_extra__ fields. If model_config.extra == ‘ignore’ (the default), then all extra passed values are ignored. Because no validation is performed with a call to model_construct(), having model_config.extra == ‘forbid’ does not result in an error if extra values are passed, but they will be ignored.
- Parameters:
_fields_set – A set of field names that were originally explicitly set during instantiation. If provided, this is directly used for the [model_fields_set][pydantic.BaseModel.model_fields_set] attribute. Otherwise, the field names from the values argument will be used.
values – Trusted or pre-validated data dictionary.
- Returns:
A new instance of the Model class with validated data.
- classmethod model_json_schema(by_alias: bool = True, ref_template: str = '#/$defs/{model}', schema_generator: type[GenerateJsonSchema] = <class 'pydantic.json_schema.GenerateJsonSchema'>, mode: Literal['validation', 'serialization']='validation', *, union_format: Literal['any_of', 'primitive_type_array']='any_of') dict[str, Any]
Generates a JSON schema for a model class.
- Parameters:
by_alias – Whether to use attribute aliases or not.
ref_template – The reference template.
union_format –
The format to use when combining schemas from unions together. Can be one of:
’any_of’: Use the [anyOf](https://json-schema.org/understanding-json-schema/reference/combining#anyOf)
keyword to combine schemas (the default). - ‘primitive_type_array’: Use the [type](https://json-schema.org/understanding-json-schema/reference/type) keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive type (string, boolean, null, integer or number) or contains constraints/metadata, falls back to any_of.
schema_generator – To override the logic used to generate the JSON schema, as a subclass of GenerateJsonSchema with your desired modifications
mode – The mode in which to generate the schema.
- Returns:
The JSON schema for the given model class.
- classmethod model_parametrized_name(params: tuple[type[Any], ...]) str
Compute the class name for parametrizations of generic classes.
This method can be overridden to achieve a custom naming scheme for generic BaseModels.
- Parameters:
params – Tuple of types of the class. Given a generic class Model with 2 type variables and a concrete model Model[str, int], the value (str, int) would be passed to params.
- Returns:
String representing the new class where params are passed to cls as type variables.
- Raises:
TypeError – Raised when trying to generate concrete names for non-generic models.
- classmethod model_rebuild(*, force: bool = False, raise_errors: bool = True, _parent_namespace_depth: int = 2, _types_namespace: MappingNamespace | None = None) bool | None
Try to rebuild the pydantic-core schema for the model.
This may be necessary when one of the annotations is a ForwardRef which could not be resolved during the initial attempt to build the schema, and automatic rebuilding fails.
- Parameters:
force – Whether to force the rebuilding of the model schema, defaults to False.
raise_errors – Whether to raise errors, defaults to True.
_parent_namespace_depth – The depth level of the parent namespace, defaults to 2.
_types_namespace – The types namespace, defaults to None.
- Returns:
Returns None if the schema is already “complete” and rebuilding was not required. If rebuilding _was_ required, returns True if rebuilding was successful, otherwise False.
- classmethod model_validate(obj: Any, *, strict: bool | None = None, extra: Literal['allow', 'ignore', 'forbid'] | None = None, from_attributes: bool | None = None, context: Any | None = None, by_alias: bool | None = None, by_name: bool | None = None) Self
Validate a pydantic model instance.
- Parameters:
obj – The object to validate.
strict – Whether to enforce types strictly.
extra – Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.
from_attributes – Whether to extract data from object attributes.
context – Additional context to pass to the validator.
by_alias – Whether to use the field’s alias when validating against the provided input data.
by_name – Whether to use the field’s name when validating against the provided input data.
- Raises:
ValidationError – If the object could not be validated.
- Returns:
The validated model instance.
- classmethod model_validate_json(json_data: str | bytes | bytearray, *, strict: bool | None = None, extra: Literal['allow', 'ignore', 'forbid'] | None = None, context: Any | None = None, by_alias: bool | None = None, by_name: bool | None = None) Self
- !!! abstract “Usage Documentation”
[JSON Parsing](../concepts/json.md#json-parsing)
Validate the given JSON data against the Pydantic model.
- Parameters:
json_data – The JSON data to validate.
strict – Whether to enforce types strictly.
extra – Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.
context – Extra variables to pass to the validator.
by_alias – Whether to use the field’s alias when validating against the provided input data.
by_name – Whether to use the field’s name when validating against the provided input data.
- Returns:
The validated Pydantic model.
- Raises:
ValidationError – If json_data is not a JSON string or the object could not be validated.
- classmethod model_validate_strings(obj: Any, *, strict: bool | None = None, extra: Literal['allow', 'ignore', 'forbid'] | None = None, context: Any | None = None, by_alias: bool | None = None, by_name: bool | None = None) Self
Validate the given object with string data against the Pydantic model.
- Parameters:
obj – The object containing string data to validate.
strict – Whether to enforce types strictly.
extra – Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.
context – Extra variables to pass to the validator.
by_alias – Whether to use the field’s alias when validating against the provided input data.
by_name – Whether to use the field’s name when validating against the provided input data.
- Returns:
The validated Pydantic model.
- classmethod validate_interpolation(v: LineInterpolation | str) LineInterpolation | str[source]
Validate that interpolation is a valid LineInterpolation value.
- classmethod validate_plot_height_mode(v: PlotHeightMode | str) PlotHeightMode | str[source]
Validate that plot_height_mode is a valid PlotHeightMode value.
- classmethod warn_on_unrecognized_fields(data: dict[str, Any]) dict[str, Any]
Warn users about unrecognized fields that don’t match model fields or aliases.
This validator checks incoming data against the model’s defined fields and their aliases, issuing warnings for any keys that don’t match. This helps catch typos and misunderstandings about the API without breaking initialization.
- copy(*, include: AbstractSetIntStr | MappingIntStrAny | None = None, exclude: AbstractSetIntStr | MappingIntStrAny | None = None, update: Dict[str, Any] | None = None, deep: bool = False) Self
Returns a copy of the model.
- !!! warning “Deprecated”
This method is now deprecated; use model_copy instead.
If you need include or exclude, use:
`python {test="skip" lint="skip"} data = self.model_dump(include=include, exclude=exclude, round_trip=True) data = {**data, **(update or {})} copied = self.model_validate(data) `- Parameters:
include – Optional set or mapping specifying which fields to include in the copied model.
exclude – Optional set or mapping specifying which fields to exclude in the copied model.
update – Optional dictionary of field-value pairs to override field values in the copied model.
deep – If True, the values of fields that are Pydantic models will be deep-copied.
- Returns:
A copy of the model with included, excluded and updated fields as specified.
- create(access_token: str | None = None, folder_id: int | None = None) BaseChart
Create a new chart via the Datawrapper API.
- Parameters:
access_token – Optional Datawrapper API access token. If not provided, will use DATAWRAPPER_ACCESS_TOKEN environment variable.
folder_id – Optional folder ID to create the chart in.
- Returns:
Self, to enable method chaining. The chart ID is stored in self.chart_id.
- Raises:
ValueError – If no access token is available or API returns invalid response.
Exception – If the API request fails.
- delete(access_token: str | None = None) bool
Delete the chart via the Datawrapper API.
- Parameters:
access_token – Optional Datawrapper API access token. If not provided, will use DATAWRAPPER_ACCESS_TOKEN environment variable.
- Returns:
True if the chart was deleted successfully.
- Raises:
ValueError – If no chart_id is set or no access token is available.
Exception – If the API request fails.
- display(access_token: str | None = None) IFrame
Display the chart as an IFrame in a Jupyter notebook.
- Parameters:
access_token – Optional Datawrapper API access token. If not provided, will use DATAWRAPPER_ACCESS_TOKEN environment variable.
- Returns:
An IPython.display.IFrame object displaying the chart.
- Raises:
ValueError – If no chart_id is set or no access token is available.
Exception – If the API request fails.
- duplicate(access_token: str | None = None) BaseChart
Duplicate the chart and create a new editable copy via the Datawrapper API.
- Parameters:
access_token – Optional Datawrapper API access token. If not provided, will use DATAWRAPPER_ACCESS_TOKEN environment variable.
- Returns:
A new BaseChart instance representing the duplicated chart.
- Raises:
ValueError – If no chart_id is set or no access token is available.
Exception – If the API request fails.
- export_pdf(*, width: int | None = None, height: int | None = None, plain: bool = False, unit: Literal['px', 'mm', 'inch'] = 'px', mode: Literal['rgb', 'cmyk'] = 'rgb', scale: int = 1, zoom: int = 2, transparent: bool = False, border_width: int = 0, border_color: str | None = None, logo: Literal['auto', 'on', 'off'] = 'auto', logo_id: str | None = None, dark: bool = False, ligatures: bool = True, full_vector: bool = False, download: bool = False, access_token: str | None = None, timeout: int = 30) bytes
Export chart as PDF and return the raw bytes.
- Parameters:
width – Width of visualization. If not specified, uses chart width.
height – Height of visualization. If not specified, uses chart height.
plain – If True, exports only the visualization without header/footer.
unit – Unit for measurements: “px”, “mm”, or “inch”.
mode – Color mode: “rgb” or “cmyk”.
scale – Size multiplier that changes actual dimensions (e.g., 2 = 2x size).
zoom – Resolution multiplier for sharper output at same visual size (e.g., 2 = 2x DPI).
transparent – If True, exports with transparent background.
border_width – Margin around visualization.
border_color – Color of the border (e.g., “#FFFFFF”). If not specified, uses chart background color.
logo – Logo display mode: “auto”, “on”, or “off”.
logo_id – Custom logo ID (pattern: ^[a-zA-Z0-9-]+$).
dark – If True, exports in dark mode.
ligatures – If True (default), enables typography ligatures.
full_vector – If True, exports as full vector output.
download – If True, includes download headers in response.
access_token – Optional Datawrapper API access token.
timeout – Timeout for the API request in seconds.
- Returns:
Raw PDF document data as bytes.
- Raises:
ValueError – If no chart_id is set or invalid parameters provided.
Exception – If the API request fails.
Example
>>> chart = BarChart.get(chart_id="abc123") >>> pdf_data = chart.export_pdf(unit="mm", mode="cmyk") >>> Path("chart.pdf").write_bytes(pdf_data)
- export_png(*, width: int | None = None, height: int | None = None, plain: bool = False, scale: int = 1, zoom: int = 2, transparent: bool = False, border_width: int = 0, border_color: str | None = None, logo: Literal['auto', 'on', 'off'] = 'auto', logo_id: str | None = None, dark: bool = False, ligatures: bool = True, full_vector: bool = False, download: bool = False, access_token: str | None = None, timeout: int = 30) bytes
Export chart as PNG and return the raw bytes.
- Parameters:
width – Width of visualization in pixels. If not specified, uses chart width.
height – Height of visualization in pixels. If not specified, uses chart height.
plain – If True, exports only the visualization without header/footer.
scale – Size multiplier that changes actual dimensions (e.g., 2 = 2x size).
zoom – Resolution multiplier for sharper output at same visual size (e.g., 2 = 2x DPI).
transparent – If True, exports with transparent background.
border_width – Margin around visualization in pixels.
border_color – Color of the border (e.g., “#FFFFFF”). If not specified, uses chart background color.
logo – Logo display mode: “auto”, “on”, or “off”.
logo_id – Custom logo ID (pattern: ^[a-zA-Z0-9-]+$).
dark – If True, exports in dark mode.
ligatures – If True (default), enables typography ligatures.
full_vector – If True, exports as full vector output.
download – If True, includes download headers in response.
access_token – Optional Datawrapper API access token.
timeout – Timeout for the API request in seconds.
- Returns:
Raw PNG image data as bytes.
- Raises:
ValueError – If no chart_id is set.
Exception – If the API request fails.
Example
>>> chart = LineChart.get(chart_id="abc123") >>> png_data = chart.export_png(zoom=3, transparent=True) >>> Path("chart.png").write_bytes(png_data)
- export_svg(*, width: int | None = None, height: int | None = None, plain: bool = False, scale: int = 1, zoom: int = 2, transparent: bool = False, border_width: int = 0, border_color: str | None = None, logo: Literal['auto', 'on', 'off'] = 'auto', logo_id: str | None = None, dark: bool = False, ligatures: bool = True, full_vector: bool = False, download: bool = False, access_token: str | None = None, timeout: int = 30) bytes
Export chart as SVG and return the raw bytes.
- Parameters:
width – Width of visualization. If not specified, uses chart width.
height – Height of visualization. If not specified, uses chart height.
plain – If True, exports only the visualization without header/footer.
scale – Size multiplier that changes actual dimensions (e.g., 2 = 2x size).
zoom – Resolution multiplier for sharper output at same visual size (e.g., 2 = 2x DPI).
transparent – If True, exports with transparent background.
border_width – Margin around visualization in pixels.
border_color – Color of the border (e.g., “#FFFFFF”). If not specified, uses chart background color.
logo – Logo display mode: “auto”, “on”, or “off”.
logo_id – Custom logo ID (pattern: ^[a-zA-Z0-9-]+$).
dark – If True, exports in dark mode.
ligatures – If True (default), enables typography ligatures.
full_vector – If True, exports as full vector output.
download – If True, includes download headers in response.
access_token – Optional Datawrapper API access token.
timeout – Timeout for the API request in seconds.
- Returns:
Raw SVG document data as bytes.
- Raises:
ValueError – If no chart_id is set.
Exception – If the API request fails.
Example
>>> chart = ColumnChart.get(chart_id="abc123") >>> svg_data = chart.export_svg(plain=True) >>> Path("chart.svg").write_bytes(svg_data)
- fork(access_token: str | None = None) BaseChart
Fork the chart and create an editable copy via the Datawrapper API.
- Parameters:
access_token – Optional Datawrapper API access token. If not provided, will use DATAWRAPPER_ACCESS_TOKEN environment variable.
- Returns:
A new BaseChart instance representing the forked chart.
- Raises:
ValueError – If no chart_id is set or no access token is available.
Exception – If the API request fails.
- get_display_urls(access_token: str | None = None) list[dict]
Get the URLs for the published chart, table or map.
- Parameters:
access_token – Optional Datawrapper API access token. If not provided, will use DATAWRAPPER_ACCESS_TOKEN environment variable.
- Returns:
A list of dictionaries containing the display URLs for the chart.
- Raises:
ValueError – If no chart_id is set or no access token is available.
Exception – If the API request fails.
- get_editor_url() str
Get the Datawrapper editor URL for this chart.
- Returns:
The Datawrapper editor URL as a string.
- Raises:
ValueError – If no chart_id is set.
- get_iframe_code(responsive: bool = False, access_token: str | None = None) str
Get the iframe embed code for the chart, table, or map.
- Parameters:
responsive – Whether to return responsive iframe code, by default False
access_token – Optional Datawrapper API access token. If not provided, will use DATAWRAPPER_ACCESS_TOKEN environment variable.
- Returns:
The iframe embed code as a string.
- Raises:
ValueError – If no chart_id is set or no access token is available.
Exception – If the API request fails.
- get_png_url() str
Get the fallback PNG image URL for noscript tags.
- Returns:
//datawrapper.dwcdn.net/{chart_id}/full.png
- Return type:
The PNG image URL in the format https
- Raises:
ValueError – If no chart_id is set.
- get_public_url() str
Get the public URL for the published chart.
- Returns:
//datawrapper.dwcdn.net/{chart_id}/
- Return type:
The public URL in the format https
- Raises:
ValueError – If no chart_id is set.
Note
This method returns the URL regardless of whether the chart is actually published. If the chart is not published, the URL will not be accessible. Use publish() to publish the chart before accessing this URL.
- model_copy(*, update: Mapping[str, Any] | None = None, deep: bool = False) Self
- !!! abstract “Usage Documentation”
[model_copy](../concepts/models.md#model-copy)
Returns a copy of the model.
- !!! note
The underlying instance’s [__dict__][object.__dict__] attribute is copied. This might have unexpected side effects if you store anything in it, on top of the model fields (e.g. the value of [cached properties][functools.cached_property]).
- Parameters:
update – Values to change/add in the new model. Note: the data is not validated before creating the new model. You should trust this data.
deep – Set to True to make a deep copy of the model.
- Returns:
New model instance.
- model_dump(*, mode: Literal['json', 'python'] | str = 'python', include: set[int] | set[str] | Mapping[int, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | Mapping[str, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | None = None, exclude: set[int] | set[str] | Mapping[int, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | Mapping[str, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | None = None, context: Any | None = None, by_alias: bool | None = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, exclude_computed_fields: bool = False, round_trip: bool = False, warnings: bool | Literal['none', 'warn', 'error'] = True, fallback: Callable[[Any], Any] | None = None, serialize_as_any: bool = False, polymorphic_serialization: bool | None = None) dict[str, Any]
- !!! abstract “Usage Documentation”
[model_dump](../concepts/serialization.md#python-mode)
Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
- Parameters:
mode – The mode in which to_python should run. If mode is ‘json’, the output will only contain JSON serializable types. If mode is ‘python’, the output may contain non-JSON-serializable Python objects.
include – A set of fields to include in the output.
exclude – A set of fields to exclude from the output.
context – Additional context to pass to the serializer.
by_alias – Whether to use the field’s alias in the dictionary key if defined.
exclude_unset – Whether to exclude fields that have not been explicitly set.
exclude_defaults – Whether to exclude fields that are set to their default value.
exclude_none – Whether to exclude fields that have a value of None.
exclude_computed_fields – Whether to exclude computed fields. While this can be useful for round-tripping, it is usually recommended to use the dedicated round_trip parameter instead.
round_trip – If True, dumped values should be valid as input for non-idempotent types such as Json[T].
warnings – How to handle serialization errors. False/”none” ignores them, True/”warn” logs errors, “error” raises a [PydanticSerializationError][pydantic_core.PydanticSerializationError].
fallback – A function to call when an unknown value is encountered. If not provided, a [PydanticSerializationError][pydantic_core.PydanticSerializationError] error is raised.
serialize_as_any – Whether to serialize fields with duck-typing serialization behavior.
polymorphic_serialization – Whether to use model and dataclass polymorphic serialization for this call.
- Returns:
A dictionary representation of the model.
- model_dump_json(*, indent: int | None = None, ensure_ascii: bool = False, include: set[int] | set[str] | Mapping[int, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | Mapping[str, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | None = None, exclude: set[int] | set[str] | Mapping[int, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | Mapping[str, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | None = None, context: Any | None = None, by_alias: bool | None = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, exclude_computed_fields: bool = False, round_trip: bool = False, warnings: bool | Literal['none', 'warn', 'error'] = True, fallback: Callable[[Any], Any] | None = None, serialize_as_any: bool = False, polymorphic_serialization: bool | None = None) str
- !!! abstract “Usage Documentation”
[model_dump_json](../concepts/serialization.md#json-mode)
Generates a JSON representation of the model using Pydantic’s to_json method.
- Parameters:
indent – Indentation to use in the JSON output. If None is passed, the output will be compact.
ensure_ascii – If True, the output is guaranteed to have all incoming non-ASCII characters escaped. If False (the default), these characters will be output as-is.
include – Field(s) to include in the JSON output.
exclude – Field(s) to exclude from the JSON output.
context – Additional context to pass to the serializer.
by_alias – Whether to serialize using field aliases.
exclude_unset – Whether to exclude fields that have not been explicitly set.
exclude_defaults – Whether to exclude fields that are set to their default value.
exclude_none – Whether to exclude fields that have a value of None.
exclude_computed_fields – Whether to exclude computed fields. While this can be useful for round-tripping, it is usually recommended to use the dedicated round_trip parameter instead.
round_trip – If True, dumped values should be valid as input for non-idempotent types such as Json[T].
warnings – How to handle serialization errors. False/”none” ignores them, True/”warn” logs errors, “error” raises a [PydanticSerializationError][pydantic_core.PydanticSerializationError].
fallback – A function to call when an unknown value is encountered. If not provided, a [PydanticSerializationError][pydantic_core.PydanticSerializationError] error is raised.
serialize_as_any – Whether to serialize fields with duck-typing serialization behavior.
polymorphic_serialization – Whether to use model and dataclass polymorphic serialization for this call.
- Returns:
A JSON string representation of the model.
- model_post_init(context: Any, /) None
Override this method to perform additional initialization after __init__ and model_construct. This is useful if you want to do some validation that requires the entire model to be initialized.
- publish(access_token: str | None = None) BaseChart
Publish the chart via the Datawrapper API.
- Parameters:
access_token – Optional Datawrapper API access token. If not provided, will use DATAWRAPPER_ACCESS_TOKEN environment variable.
- Returns:
Self, to enable method chaining.
- Raises:
ValueError – If no chart_id is set or no access token is available.
Exception – If the API request fails or publishing fails.
- serialize_data() str | None
Convert data to CSV string for API upload.
- Returns:
CSV string representation of the data, or None if data is empty.
- update(access_token: str | None = None) BaseChart
Update an existing chart via the Datawrapper API.
- Parameters:
access_token – Optional Datawrapper API access token. If not provided, will use DATAWRAPPER_ACCESS_TOKEN environment variable.
- Returns:
Self, to enable method chaining.
- Raises:
ValueError – If no chart_id is set or no access token is available.
Exception – If the API request fails.
- area_fills: list[AreaFill | dict[str, Any]]
Custom area fills
- aria_description
The alternative text for screen readers
- auto_dark_mode
Whether the chart should automatically flip to dark mode when the user’s system is in dark mode
- base_color: str | int
The base color for lines (palette index or hex string)
- byline
The byline that appears below the chart
- chart_id
The chart ID after creation (populated by create() method)
- chart_type: Literal['d3-lines']
The type of datawrapper chart to create
- color_category: dict[str, str]
A mapping of layer names to colors
- connector_lines: bool
Whether or not to draw a connector line between lines and labels
- custom
A dictionary of custom tags to attach to the chart
- dark_mode_invert
Whether to invert colors in dark mode
- data
The data to use for the chart
- download_image
Whether to allow PNG download
- download_pdf
Whether to allow PDF download
- download_svg
Whether to allow SVG download
- embed
Whether to allow embedding
- force_attribution
Whether to attribute the chart to datawrapper
- forkable
Whether to allow other users to fork this visualization
- get_the_data
Whether to allow data downloads
- hide_title
Whether or not to hide the title
- interpolation: LineInterpolation | str
The interpolation method to use when drawing lines
- intro
The intro text that appears above the chart
- label_colors: bool
Whether or not to color line category labels the same as the line
- label_margin: int
The amount of margin to leave for the right hand side for labels
- language
The locale of the chart, which defines decimal and thousand separators as well as translations of month and weekday names.
- logo
Whether to show a logo
- logo_id
The id of the logo to show
- model_config = {'arbitrary_types_allowed': True, 'json_schema_extra': {'examples': [{'chart-type': 'd3-lines', 'data': date Temperature 0 2020/01 15.0 1 2020/02 18.0 2 2020/03 22.0, 'interpolation': 'monotone-x', 'source_name': 'Weather Station', 'title': 'Temperature Over Time', 'y_grid': 'on'}]}, 'populate_by_name': True, 'strict': True, 'use_enum_values': True, 'validate_assignment': True, 'validate_by_alias': True, 'validate_by_name': True, 'validate_default': True}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- property model_extra: dict[str, Any] | None
Get extra fields set during validation.
- Returns:
A dictionary of extra fields, or None if config.extra is not set to “allow”.
- property model_fields_set: set[str]
Returns the set of fields that have been explicitly set on this model instance.
- Returns:
- A set of strings representing the fields that have been set,
i.e. that were not filled from defaults.
- notes
The footnotes that appear below the chart
- plot_height_fixed: int | float
The fixed height of the plot
- plot_height_mode: PlotHeightMode | str
How to set the plot height (managed by PlotHeight serializer, not directly serialized)
- plot_height_ratio: float
The ratio of the plot height
- scale_y: Literal['linear', 'log']
How to scale the y-axis
Whether to show social media share buttons
What URL to share
- show_tooltips: bool
Whether or not to show tooltips on hover
- source_name
The source name that appears below the chart
- source_url
The source URL that appears below the chart
- stack_color_legend: bool
Whether or not to stack the color legend
- theme
The theme of the chart
- title
The headline that appears above the chart
- tooltip_number_format: DateFormat | NumberFormat | str
The format of the number tooltip (use DateFormat or NumberFormat enum or custom format strings)
- tooltip_x_format: DateFormat | NumberFormat | str
The format for the x-axis tooltips (use DateFormat or NumberFormat enum or custom format strings)
- transformations
The metadata options for the data columns in the “Check and Describe” tab
- value_label_colors: bool
Whether to color number values labels the same as the line
- value_labels_format: DateFormat | NumberFormat | str
The number format for value labels (use DateFormat or NumberFormat enum or custom format strings)
- x_column: str | None
The column to use for the x-axis
- y_grid_label_align: GridLabelAlign | str
Which side to put the y-axis labels on
- y_grid_labels: GridLabelPosition | str
The labeling of the y grid labels
- y_grid_subdivide: bool
Whether or not to subdivide a log scale
Multiple Column Chart
- class datawrapper.charts.MultipleColumnChart(*, chart_type: Literal['multiple-columns'] = 'multiple-columns', data: DataFrame | list[dict] = <factory>, transformations: Transform | dict[str, ~typing.Any]=<factory>, title: str = '', intro: str = '', notes: str = '', source_name: str = '', source_url: str = '', byline: str = '', aria_description: str = '', hide_title: bool = False, language: str = 'en-US', theme: str = 'datawrapper', autoDarkMode: bool = False, dark_mode_invert: bool = True, get_the_data: bool = False, download_image: bool = False, download_pdf: bool = False, download_svg: bool = False, embed: bool = False, force_attribution: bool = False, share_buttons: bool = False, share_url: str = '', logo: bool = False, logo_id: str = '', custom: dict[str, ~typing.Any]=<factory>, forkable: bool = True, chart_id: str | None = None, text_annotations: Any, ~typing.Any]]=<factory>, range_annotations: Any, ~typing.Any]]=<factory>, custom_ticks_x: list[Any] | None = None, custom_ticks_y: list[Any] | None = None, custom_range_x: list[~typing.Any] | tuple[~typing.Any, ~typing.Any] | None=None, custom_range_y: list[~typing.Any] | tuple[~typing.Any, ~typing.Any] | None=None, x_grid_format: DateFormat | NumberFormat | str | None = None, y_grid_format: NumberFormat | str | None = None, x_grid: GridDisplay | str | bool | None = 'off', y_grid: GridDisplay | str | bool | None = 'on', panels: list[dict[str, ~typing.Any]]=<factory>, grid_layout: Literal['fixedCount', 'minimumWidth']='fixedCount', grid_column: int = 2, grid_column_mobile: int = 2, grid_column_width: int = 200, grid_row_height: int = 140, sort: bool = False, sort_reverse: bool = False, sort_by: Literal['start', 'end', 'range', 'diff', 'change', 'title']='end', x_grid_labels: Literal['on', 'off']='on', x_grid_all: GridDisplay | str = 'off', y_grid_labels: GridLabelPosition | str = 'outside', y_grid_label_align: GridLabelAlign | str = 'left', base_color: str | int = 0, negative_color: str | None = None, color_category: dict[str, str]=<factory>, bar_padding: int = 30, plot_height_mode: PlotHeightMode | str = 'fixed', plot_height_fixed: int = 300, plot_height_ratio: float = 0.5, show_tooltips: bool = True, syncMultipleTooltips: bool = False, tooltip_number_format: DateFormat | NumberFormat | str = '', label_colors: bool = False, show_color_key: bool = False, show_value_labels: ValueLabelDisplay | str = 'off', value_labels_format: DateFormat | NumberFormat | str = '', value_labels_placement: ValueLabelPlacement | str = 'outside', label_margin: int = 0, x_grid_label_all: bool = False)[source]
Bases:
GridDisplayMixin,GridFormatMixin,CustomRangeMixin,CustomTicksMixin,AnnotationsMixin,BaseChartA base class for the Datawrapper API’s multiple column chart.
Note: This chart uses MultipleColumnTextAnnotation and MultipleColumnRangeAnnotation for annotations, which extend the base annotation classes with plot-specific fields. The parent AnnotationsMixin fields accept these subclasses automatically.
- classmethod convert_column_format_dicts(data: dict[str, Any]) dict[str, Any]
Convert dictionary items in transformation to Transform objects.
- classmethod convert_range_annotations(v: Sequence[MultipleColumnRangeAnnotation | dict[Any, Any]]) list[MultipleColumnRangeAnnotation][source]
Convert dict annotations to MultipleColumnRangeAnnotation instances.
This ensures that when annotations are passed as dicts, they are converted to the proper annotation class so that serialize_model() includes the plot field.
- classmethod convert_text_annotations(v: Sequence[MultipleColumnTextAnnotation | dict[Any, Any]]) list[MultipleColumnTextAnnotation][source]
Convert dict annotations to MultipleColumnTextAnnotation instances.
This ensures that when annotations are passed as dicts, they are converted to the proper annotation class so that serialize_model() includes the plot field.
- classmethod deserialize_data(csv_data: str | DataFrame) DataFrame
Parse CSV string from Datawrapper API into DataFrame.
- Parameters:
csv_data – The CSV data from the chart data endpoint
- Returns:
DataFrame containing the parsed CSV data
- classmethod deserialize_model(api_response: dict[str, Any]) dict[str, Any][source]
Parse Datawrapper API response including multiple column chart specific fields.
- Parameters:
api_response – The JSON response from the chart metadata endpoint
chart_data – The CSV data from the chart data endpoint
- Returns:
Dictionary that can be used to initialize the MultipleColumnChart model
- classmethod get(chart_id: str, access_token: str | None = None) BaseChart
Fetch an existing chart from the Datawrapper API.
- Parameters:
chart_id – The ID of the chart to fetch
access_token – Optional Datawrapper API access token. If not provided, will use DATAWRAPPER_ACCESS_TOKEN environment variable.
- Returns:
An instance of the chart class with data populated from the API.
- Raises:
ValueError – If no access token is available or chart type doesn’t match.
Exception – If the API request fails.
- classmethod model_construct(_fields_set: set[str] | None = None, **values: Any) Self
Creates a new instance of the Model class with validated data.
Creates a new model setting __dict__ and __pydantic_fields_set__ from trusted or pre-validated data. Default values are respected, but no other validation is performed.
- !!! note
model_construct() generally respects the model_config.extra setting on the provided model. That is, if model_config.extra == ‘allow’, then all extra passed values are added to the model instance’s __dict__ and __pydantic_extra__ fields. If model_config.extra == ‘ignore’ (the default), then all extra passed values are ignored. Because no validation is performed with a call to model_construct(), having model_config.extra == ‘forbid’ does not result in an error if extra values are passed, but they will be ignored.
- Parameters:
_fields_set – A set of field names that were originally explicitly set during instantiation. If provided, this is directly used for the [model_fields_set][pydantic.BaseModel.model_fields_set] attribute. Otherwise, the field names from the values argument will be used.
values – Trusted or pre-validated data dictionary.
- Returns:
A new instance of the Model class with validated data.
- classmethod model_json_schema(by_alias: bool = True, ref_template: str = '#/$defs/{model}', schema_generator: type[GenerateJsonSchema] = <class 'pydantic.json_schema.GenerateJsonSchema'>, mode: Literal['validation', 'serialization']='validation', *, union_format: Literal['any_of', 'primitive_type_array']='any_of') dict[str, Any]
Generates a JSON schema for a model class.
- Parameters:
by_alias – Whether to use attribute aliases or not.
ref_template – The reference template.
union_format –
The format to use when combining schemas from unions together. Can be one of:
’any_of’: Use the [anyOf](https://json-schema.org/understanding-json-schema/reference/combining#anyOf)
keyword to combine schemas (the default). - ‘primitive_type_array’: Use the [type](https://json-schema.org/understanding-json-schema/reference/type) keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive type (string, boolean, null, integer or number) or contains constraints/metadata, falls back to any_of.
schema_generator – To override the logic used to generate the JSON schema, as a subclass of GenerateJsonSchema with your desired modifications
mode – The mode in which to generate the schema.
- Returns:
The JSON schema for the given model class.
- classmethod model_parametrized_name(params: tuple[type[Any], ...]) str
Compute the class name for parametrizations of generic classes.
This method can be overridden to achieve a custom naming scheme for generic BaseModels.
- Parameters:
params – Tuple of types of the class. Given a generic class Model with 2 type variables and a concrete model Model[str, int], the value (str, int) would be passed to params.
- Returns:
String representing the new class where params are passed to cls as type variables.
- Raises:
TypeError – Raised when trying to generate concrete names for non-generic models.
- classmethod model_rebuild(*, force: bool = False, raise_errors: bool = True, _parent_namespace_depth: int = 2, _types_namespace: MappingNamespace | None = None) bool | None
Try to rebuild the pydantic-core schema for the model.
This may be necessary when one of the annotations is a ForwardRef which could not be resolved during the initial attempt to build the schema, and automatic rebuilding fails.
- Parameters:
force – Whether to force the rebuilding of the model schema, defaults to False.
raise_errors – Whether to raise errors, defaults to True.
_parent_namespace_depth – The depth level of the parent namespace, defaults to 2.
_types_namespace – The types namespace, defaults to None.
- Returns:
Returns None if the schema is already “complete” and rebuilding was not required. If rebuilding _was_ required, returns True if rebuilding was successful, otherwise False.
- classmethod model_validate(obj: Any, *, strict: bool | None = None, extra: Literal['allow', 'ignore', 'forbid'] | None = None, from_attributes: bool | None = None, context: Any | None = None, by_alias: bool | None = None, by_name: bool | None = None) Self
Validate a pydantic model instance.
- Parameters:
obj – The object to validate.
strict – Whether to enforce types strictly.
extra – Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.
from_attributes – Whether to extract data from object attributes.
context – Additional context to pass to the validator.
by_alias – Whether to use the field’s alias when validating against the provided input data.
by_name – Whether to use the field’s name when validating against the provided input data.
- Raises:
ValidationError – If the object could not be validated.
- Returns:
The validated model instance.
- classmethod model_validate_json(json_data: str | bytes | bytearray, *, strict: bool | None = None, extra: Literal['allow', 'ignore', 'forbid'] | None = None, context: Any | None = None, by_alias: bool | None = None, by_name: bool | None = None) Self
- !!! abstract “Usage Documentation”
[JSON Parsing](../concepts/json.md#json-parsing)
Validate the given JSON data against the Pydantic model.
- Parameters:
json_data – The JSON data to validate.
strict – Whether to enforce types strictly.
extra – Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.
context – Extra variables to pass to the validator.
by_alias – Whether to use the field’s alias when validating against the provided input data.
by_name – Whether to use the field’s name when validating against the provided input data.
- Returns:
The validated Pydantic model.
- Raises:
ValidationError – If json_data is not a JSON string or the object could not be validated.
- classmethod model_validate_strings(obj: Any, *, strict: bool | None = None, extra: Literal['allow', 'ignore', 'forbid'] | None = None, context: Any | None = None, by_alias: bool | None = None, by_name: bool | None = None) Self
Validate the given object with string data against the Pydantic model.
- Parameters:
obj – The object containing string data to validate.
strict – Whether to enforce types strictly.
extra – Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.
context – Extra variables to pass to the validator.
by_alias – Whether to use the field’s alias when validating against the provided input data.
by_name – Whether to use the field’s name when validating against the provided input data.
- Returns:
The validated Pydantic model.
- classmethod validate_plot_height_mode(v: PlotHeightMode | str) PlotHeightMode | str[source]
Validate that plot_height_mode is a valid PlotHeightMode value.
- classmethod warn_on_unrecognized_fields(data: dict[str, Any]) dict[str, Any]
Warn users about unrecognized fields that don’t match model fields or aliases.
This validator checks incoming data against the model’s defined fields and their aliases, issuing warnings for any keys that don’t match. This helps catch typos and misunderstandings about the API without breaking initialization.
- copy(*, include: AbstractSetIntStr | MappingIntStrAny | None = None, exclude: AbstractSetIntStr | MappingIntStrAny | None = None, update: Dict[str, Any] | None = None, deep: bool = False) Self
Returns a copy of the model.
- !!! warning “Deprecated”
This method is now deprecated; use model_copy instead.
If you need include or exclude, use:
`python {test="skip" lint="skip"} data = self.model_dump(include=include, exclude=exclude, round_trip=True) data = {**data, **(update or {})} copied = self.model_validate(data) `- Parameters:
include – Optional set or mapping specifying which fields to include in the copied model.
exclude – Optional set or mapping specifying which fields to exclude in the copied model.
update – Optional dictionary of field-value pairs to override field values in the copied model.
deep – If True, the values of fields that are Pydantic models will be deep-copied.
- Returns:
A copy of the model with included, excluded and updated fields as specified.
- create(access_token: str | None = None, folder_id: int | None = None) BaseChart
Create a new chart via the Datawrapper API.
- Parameters:
access_token – Optional Datawrapper API access token. If not provided, will use DATAWRAPPER_ACCESS_TOKEN environment variable.
folder_id – Optional folder ID to create the chart in.
- Returns:
Self, to enable method chaining. The chart ID is stored in self.chart_id.
- Raises:
ValueError – If no access token is available or API returns invalid response.
Exception – If the API request fails.
- delete(access_token: str | None = None) bool
Delete the chart via the Datawrapper API.
- Parameters:
access_token – Optional Datawrapper API access token. If not provided, will use DATAWRAPPER_ACCESS_TOKEN environment variable.
- Returns:
True if the chart was deleted successfully.
- Raises:
ValueError – If no chart_id is set or no access token is available.
Exception – If the API request fails.
- display(access_token: str | None = None) IFrame
Display the chart as an IFrame in a Jupyter notebook.
- Parameters:
access_token – Optional Datawrapper API access token. If not provided, will use DATAWRAPPER_ACCESS_TOKEN environment variable.
- Returns:
An IPython.display.IFrame object displaying the chart.
- Raises:
ValueError – If no chart_id is set or no access token is available.
Exception – If the API request fails.
- duplicate(access_token: str | None = None) BaseChart
Duplicate the chart and create a new editable copy via the Datawrapper API.
- Parameters:
access_token – Optional Datawrapper API access token. If not provided, will use DATAWRAPPER_ACCESS_TOKEN environment variable.
- Returns:
A new BaseChart instance representing the duplicated chart.
- Raises:
ValueError – If no chart_id is set or no access token is available.
Exception – If the API request fails.
- export_pdf(*, width: int | None = None, height: int | None = None, plain: bool = False, unit: Literal['px', 'mm', 'inch'] = 'px', mode: Literal['rgb', 'cmyk'] = 'rgb', scale: int = 1, zoom: int = 2, transparent: bool = False, border_width: int = 0, border_color: str | None = None, logo: Literal['auto', 'on', 'off'] = 'auto', logo_id: str | None = None, dark: bool = False, ligatures: bool = True, full_vector: bool = False, download: bool = False, access_token: str | None = None, timeout: int = 30) bytes
Export chart as PDF and return the raw bytes.
- Parameters:
width – Width of visualization. If not specified, uses chart width.
height – Height of visualization. If not specified, uses chart height.
plain – If True, exports only the visualization without header/footer.
unit – Unit for measurements: “px”, “mm”, or “inch”.
mode – Color mode: “rgb” or “cmyk”.
scale – Size multiplier that changes actual dimensions (e.g., 2 = 2x size).
zoom – Resolution multiplier for sharper output at same visual size (e.g., 2 = 2x DPI).
transparent – If True, exports with transparent background.
border_width – Margin around visualization.
border_color – Color of the border (e.g., “#FFFFFF”). If not specified, uses chart background color.
logo – Logo display mode: “auto”, “on”, or “off”.
logo_id – Custom logo ID (pattern: ^[a-zA-Z0-9-]+$).
dark – If True, exports in dark mode.
ligatures – If True (default), enables typography ligatures.
full_vector – If True, exports as full vector output.
download – If True, includes download headers in response.
access_token – Optional Datawrapper API access token.
timeout – Timeout for the API request in seconds.
- Returns:
Raw PDF document data as bytes.
- Raises:
ValueError – If no chart_id is set or invalid parameters provided.
Exception – If the API request fails.
Example
>>> chart = BarChart.get(chart_id="abc123") >>> pdf_data = chart.export_pdf(unit="mm", mode="cmyk") >>> Path("chart.pdf").write_bytes(pdf_data)
- export_png(*, width: int | None = None, height: int | None = None, plain: bool = False, scale: int = 1, zoom: int = 2, transparent: bool = False, border_width: int = 0, border_color: str | None = None, logo: Literal['auto', 'on', 'off'] = 'auto', logo_id: str | None = None, dark: bool = False, ligatures: bool = True, full_vector: bool = False, download: bool = False, access_token: str | None = None, timeout: int = 30) bytes
Export chart as PNG and return the raw bytes.
- Parameters:
width – Width of visualization in pixels. If not specified, uses chart width.
height – Height of visualization in pixels. If not specified, uses chart height.
plain – If True, exports only the visualization without header/footer.
scale – Size multiplier that changes actual dimensions (e.g., 2 = 2x size).
zoom – Resolution multiplier for sharper output at same visual size (e.g., 2 = 2x DPI).
transparent – If True, exports with transparent background.
border_width – Margin around visualization in pixels.
border_color – Color of the border (e.g., “#FFFFFF”). If not specified, uses chart background color.
logo – Logo display mode: “auto”, “on”, or “off”.
logo_id – Custom logo ID (pattern: ^[a-zA-Z0-9-]+$).
dark – If True, exports in dark mode.
ligatures – If True (default), enables typography ligatures.
full_vector – If True, exports as full vector output.
download – If True, includes download headers in response.
access_token – Optional Datawrapper API access token.
timeout – Timeout for the API request in seconds.
- Returns:
Raw PNG image data as bytes.
- Raises:
ValueError – If no chart_id is set.
Exception – If the API request fails.
Example
>>> chart = LineChart.get(chart_id="abc123") >>> png_data = chart.export_png(zoom=3, transparent=True) >>> Path("chart.png").write_bytes(png_data)
- export_svg(*, width: int | None = None, height: int | None = None, plain: bool = False, scale: int = 1, zoom: int = 2, transparent: bool = False, border_width: int = 0, border_color: str | None = None, logo: Literal['auto', 'on', 'off'] = 'auto', logo_id: str | None = None, dark: bool = False, ligatures: bool = True, full_vector: bool = False, download: bool = False, access_token: str | None = None, timeout: int = 30) bytes
Export chart as SVG and return the raw bytes.
- Parameters:
width – Width of visualization. If not specified, uses chart width.
height – Height of visualization. If not specified, uses chart height.
plain – If True, exports only the visualization without header/footer.
scale – Size multiplier that changes actual dimensions (e.g., 2 = 2x size).
zoom – Resolution multiplier for sharper output at same visual size (e.g., 2 = 2x DPI).
transparent – If True, exports with transparent background.
border_width – Margin around visualization in pixels.
border_color – Color of the border (e.g., “#FFFFFF”). If not specified, uses chart background color.
logo – Logo display mode: “auto”, “on”, or “off”.
logo_id – Custom logo ID (pattern: ^[a-zA-Z0-9-]+$).
dark – If True, exports in dark mode.
ligatures – If True (default), enables typography ligatures.
full_vector – If True, exports as full vector output.
download – If True, includes download headers in response.
access_token – Optional Datawrapper API access token.
timeout – Timeout for the API request in seconds.
- Returns:
Raw SVG document data as bytes.
- Raises:
ValueError – If no chart_id is set.
Exception – If the API request fails.
Example
>>> chart = ColumnChart.get(chart_id="abc123") >>> svg_data = chart.export_svg(plain=True) >>> Path("chart.svg").write_bytes(svg_data)
- fork(access_token: str | None = None) BaseChart
Fork the chart and create an editable copy via the Datawrapper API.
- Parameters:
access_token – Optional Datawrapper API access token. If not provided, will use DATAWRAPPER_ACCESS_TOKEN environment variable.
- Returns:
A new BaseChart instance representing the forked chart.
- Raises:
ValueError – If no chart_id is set or no access token is available.
Exception – If the API request fails.
- get_display_urls(access_token: str | None = None) list[dict]
Get the URLs for the published chart, table or map.
- Parameters:
access_token – Optional Datawrapper API access token. If not provided, will use DATAWRAPPER_ACCESS_TOKEN environment variable.
- Returns:
A list of dictionaries containing the display URLs for the chart.
- Raises:
ValueError – If no chart_id is set or no access token is available.
Exception – If the API request fails.
- get_editor_url() str
Get the Datawrapper editor URL for this chart.
- Returns:
The Datawrapper editor URL as a string.
- Raises:
ValueError – If no chart_id is set.
- get_iframe_code(responsive: bool = False, access_token: str | None = None) str
Get the iframe embed code for the chart, table, or map.
- Parameters:
responsive – Whether to return responsive iframe code, by default False
access_token – Optional Datawrapper API access token. If not provided, will use DATAWRAPPER_ACCESS_TOKEN environment variable.
- Returns:
The iframe embed code as a string.
- Raises:
ValueError – If no chart_id is set or no access token is available.
Exception – If the API request fails.
- get_png_url() str
Get the fallback PNG image URL for noscript tags.
- Returns:
//datawrapper.dwcdn.net/{chart_id}/full.png
- Return type:
The PNG image URL in the format https
- Raises:
ValueError – If no chart_id is set.
- get_public_url() str
Get the public URL for the published chart.
- Returns:
//datawrapper.dwcdn.net/{chart_id}/
- Return type:
The public URL in the format https
- Raises:
ValueError – If no chart_id is set.
Note
This method returns the URL regardless of whether the chart is actually published. If the chart is not published, the URL will not be accessible. Use publish() to publish the chart before accessing this URL.
- model_copy(*, update: Mapping[str, Any] | None = None, deep: bool = False) Self
- !!! abstract “Usage Documentation”
[model_copy](../concepts/models.md#model-copy)
Returns a copy of the model.
- !!! note
The underlying instance’s [__dict__][object.__dict__] attribute is copied. This might have unexpected side effects if you store anything in it, on top of the model fields (e.g. the value of [cached properties][functools.cached_property]).
- Parameters:
update – Values to change/add in the new model. Note: the data is not validated before creating the new model. You should trust this data.
deep – Set to True to make a deep copy of the model.
- Returns:
New model instance.
- model_dump(*, mode: Literal['json', 'python'] | str = 'python', include: set[int] | set[str] | Mapping[int, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | Mapping[str, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | None = None, exclude: set[int] | set[str] | Mapping[int, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | Mapping[str, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | None = None, context: Any | None = None, by_alias: bool | None = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, exclude_computed_fields: bool = False, round_trip: bool = False, warnings: bool | Literal['none', 'warn', 'error'] = True, fallback: Callable[[Any], Any] | None = None, serialize_as_any: bool = False, polymorphic_serialization: bool | None = None) dict[str, Any]
- !!! abstract “Usage Documentation”
[model_dump](../concepts/serialization.md#python-mode)
Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
- Parameters:
mode – The mode in which to_python should run. If mode is ‘json’, the output will only contain JSON serializable types. If mode is ‘python’, the output may contain non-JSON-serializable Python objects.
include – A set of fields to include in the output.
exclude – A set of fields to exclude from the output.
context – Additional context to pass to the serializer.
by_alias – Whether to use the field’s alias in the dictionary key if defined.
exclude_unset – Whether to exclude fields that have not been explicitly set.
exclude_defaults – Whether to exclude fields that are set to their default value.
exclude_none – Whether to exclude fields that have a value of None.
exclude_computed_fields – Whether to exclude computed fields. While this can be useful for round-tripping, it is usually recommended to use the dedicated round_trip parameter instead.
round_trip – If True, dumped values should be valid as input for non-idempotent types such as Json[T].
warnings – How to handle serialization errors. False/”none” ignores them, True/”warn” logs errors, “error” raises a [PydanticSerializationError][pydantic_core.PydanticSerializationError].
fallback – A function to call when an unknown value is encountered. If not provided, a [PydanticSerializationError][pydantic_core.PydanticSerializationError] error is raised.
serialize_as_any – Whether to serialize fields with duck-typing serialization behavior.
polymorphic_serialization – Whether to use model and dataclass polymorphic serialization for this call.
- Returns:
A dictionary representation of the model.
- model_dump_json(*, indent: int | None = None, ensure_ascii: bool = False, include: set[int] | set[str] | Mapping[int, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | Mapping[str, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | None = None, exclude: set[int] | set[str] | Mapping[int, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | Mapping[str, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | None = None, context: Any | None = None, by_alias: bool | None = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, exclude_computed_fields: bool = False, round_trip: bool = False, warnings: bool | Literal['none', 'warn', 'error'] = True, fallback: Callable[[Any], Any] | None = None, serialize_as_any: bool = False, polymorphic_serialization: bool | None = None) str
- !!! abstract “Usage Documentation”
[model_dump_json](../concepts/serialization.md#json-mode)
Generates a JSON representation of the model using Pydantic’s to_json method.
- Parameters:
indent – Indentation to use in the JSON output. If None is passed, the output will be compact.
ensure_ascii – If True, the output is guaranteed to have all incoming non-ASCII characters escaped. If False (the default), these characters will be output as-is.
include – Field(s) to include in the JSON output.
exclude – Field(s) to exclude from the JSON output.
context – Additional context to pass to the serializer.
by_alias – Whether to serialize using field aliases.
exclude_unset – Whether to exclude fields that have not been explicitly set.
exclude_defaults – Whether to exclude fields that are set to their default value.
exclude_none – Whether to exclude fields that have a value of None.
exclude_computed_fields – Whether to exclude computed fields. While this can be useful for round-tripping, it is usually recommended to use the dedicated round_trip parameter instead.
round_trip – If True, dumped values should be valid as input for non-idempotent types such as Json[T].
warnings – How to handle serialization errors. False/”none” ignores them, True/”warn” logs errors, “error” raises a [PydanticSerializationError][pydantic_core.PydanticSerializationError].
fallback – A function to call when an unknown value is encountered. If not provided, a [PydanticSerializationError][pydantic_core.PydanticSerializationError] error is raised.
serialize_as_any – Whether to serialize fields with duck-typing serialization behavior.
polymorphic_serialization – Whether to use model and dataclass polymorphic serialization for this call.
- Returns:
A JSON string representation of the model.
- model_post_init(context: Any, /) None
Override this method to perform additional initialization after __init__ and model_construct. This is useful if you want to do some validation that requires the entire model to be initialized.
- publish(access_token: str | None = None) BaseChart
Publish the chart via the Datawrapper API.
- Parameters:
access_token – Optional Datawrapper API access token. If not provided, will use DATAWRAPPER_ACCESS_TOKEN environment variable.
- Returns:
Self, to enable method chaining.
- Raises:
ValueError – If no chart_id is set or no access token is available.
Exception – If the API request fails or publishing fails.
- serialize_data() str | None
Convert data to CSV string for API upload.
- Returns:
CSV string representation of the data, or None if data is empty.
- update(access_token: str | None = None) BaseChart
Update an existing chart via the Datawrapper API.
- Parameters:
access_token – Optional Datawrapper API access token. If not provided, will use DATAWRAPPER_ACCESS_TOKEN environment variable.
- Returns:
Self, to enable method chaining.
- Raises:
ValueError – If no chart_id is set or no access token is available.
Exception – If the API request fails.
- aria_description
The alternative text for screen readers
- auto_dark_mode
Whether the chart should automatically flip to dark mode when the user’s system is in dark mode
- bar_padding: int
The padding between bars as a percentage of the bar width
- base_color: str | int
The base color for the chart (palette index or hex string)
- byline
The byline that appears below the chart
- chart_id
The chart ID after creation (populated by create() method)
- chart_type: Literal['multiple-columns']
The type of datawrapper chart to create
- color_category: dict[str, str]
A mapping of layer names to colors
- custom
A dictionary of custom tags to attach to the chart
- dark_mode_invert
Whether to invert colors in dark mode
- data
The data to use for the chart
- download_image
Whether to allow PNG download
- download_pdf
Whether to allow PDF download
- download_svg
Whether to allow SVG download
- embed
Whether to allow embedding
- force_attribution
Whether to attribute the chart to datawrapper
- forkable
Whether to allow other users to fork this visualization
- get_the_data
Whether to allow data downloads
- grid_column: int
How the panels are laid out on desktop
- grid_column_mobile: int
How the panels are laid out on mobile
- grid_column_width: int
How the panels are laid out - only changed if layout is not fixedCount
- grid_layout: Literal['fixedCount', 'minimumWidth']
Fixed vs auto layout. If minimumWidth is selected it’s auto layout
- grid_row_height: int
Height of rows
- hide_title
Whether or not to hide the title
- intro
The intro text that appears above the chart
- label_colors: bool
Whether or not to column labels the same as the column
- label_margin: int
The amount of margin to leave for the right hand side for labels
- language
The locale of the chart, which defines decimal and thousand separators as well as translations of month and weekday names.
- logo
Whether to show a logo
- logo_id
The id of the logo to show
- model_config = {'arbitrary_types_allowed': True, 'json_schema_extra': {'examples': [{'chart-type': 'multiple-columns', 'data': Year North South East 0 2020 100 90 80 1 2021 110 95 85 2 2022 120 100 90 3 2023 130 105 95, 'grid_column': 3, 'grid_row_height': 140, 'title': 'Regional Sales Comparison'}]}, 'populate_by_name': True, 'strict': True, 'use_enum_values': True, 'validate_assignment': True, 'validate_by_alias': True, 'validate_by_name': True, 'validate_default': True}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- property model_extra: dict[str, Any] | None
Get extra fields set during validation.
- Returns:
A dictionary of extra fields, or None if config.extra is not set to “allow”.
- property model_fields_set: set[str]
Returns the set of fields that have been explicitly set on this model instance.
- Returns:
- A set of strings representing the fields that have been set,
i.e. that were not filled from defaults.
- negative_color: str | None
The negative color to use, if you want one
- notes
The footnotes that appear below the chart
- panels: list[dict[str, Any]]
Panels configuration
- plot_height_fixed: int
The fixed height of the plot
- plot_height_mode: PlotHeightMode | str
How to set the plot height
- plot_height_ratio: float
The ratio of the plot height
Whether to show social media share buttons
What URL to share
- show_color_key: bool
Whether or not to show the color key above the chart
- show_tooltips: bool
Whether or not to show tooltips on hover
- show_value_labels: ValueLabelDisplay | str
Whether or not to show value labels
- sort: bool
Sort of the panels
- sort_by: Literal['start', 'end', 'range', 'diff', 'change', 'title']
How to sort the panels
- sort_reverse: bool
Whether to sort the panels in reverse order
- source_name
The source name that appears below the chart
- source_url
The source URL that appears below the chart
- sync_multiple_tooltips: bool
Whether to show tooltips synchronously across all panels
- theme
The theme of the chart
- title
The headline that appears above the chart
- tooltip_number_format: DateFormat | NumberFormat | str
The format for the y-axis values in tooltips (use DateFormat or NumberFormat enum or custom format strings)
- transformations
The metadata options for the data columns in the “Check and Describe” tab
- value_labels_format: DateFormat | NumberFormat | str
How to format the value labels (use DateFormat or NumberFormat enum or custom format strings)
- value_labels_placement: ValueLabelPlacement | str
Where to place the value labels
- x_grid_all: GridDisplay | str
x_grid for panels
- x_grid_label_all: bool
Show label for all panels
- x_grid_labels: Literal['on', 'off']
The labeling of the x axis
- y_grid_label_align: GridLabelAlign | str
Which side to put the y-axis labels on
- y_grid_labels: GridLabelPosition | str
The labeling of the y grid labels
Scatter Plot
- class datawrapper.charts.ScatterPlot(*, chart_type: Literal['d3-scatter-plot'] = 'd3-scatter-plot', data: DataFrame | list[dict] = <factory>, transformations: Transform | dict[str, ~typing.Any]=<factory>, title: str = '', intro: str = '', notes: str = '', source_name: str = '', source_url: str = '', byline: str = '', aria_description: str = '', hide_title: bool = False, language: str = 'en-US', theme: str = 'datawrapper', autoDarkMode: bool = False, dark_mode_invert: bool = True, get_the_data: bool = False, download_image: bool = False, download_pdf: bool = False, download_svg: bool = False, embed: bool = False, force_attribution: bool = False, share_buttons: bool = False, share_url: str = '', logo: bool = False, logo_id: str = '', custom: dict[str, ~typing.Any]=<factory>, forkable: bool = True, chart_id: str | None = None, text_annotations: Any, ~typing.Any]]=<factory>, range_annotations: Any, ~typing.Any]]=<factory>, x_column: str | None = None, x_range: tuple[~typing.Any, ~typing.Any] | list[~typing.Any]=('', ''), x_ticks: list[Any] = <factory>, x_log: bool = False, x_format: DateFormat | NumberFormat | str = '', x_position: ScatterAxisPosition | str = 'bottom', x_grid_lines: ScatterGridLines | str = 'on', y_column: str | None = None, y_range: tuple[~typing.Any, ~typing.Any] | list[~typing.Any]=('', ''), y_ticks: list[Any] = <factory>, y_log: bool = False, y_format: DateFormat | NumberFormat | str = '', y_position: ScatterAxisPosition | str = 'bottom', y_grid_lines: ScatterGridLines | str = 'on', base_color: str | int = 0, opacity: float = 1.0, outlines: bool = False, color_outline: str = '#000000', show_color_key: bool = False, color_column: str = '', color_category: dict[str, str]=<factory>, category_labels: dict[str, str]=<factory>, category_order: list[str] = <factory>, exclude_from_color_key: list[str] = <factory>, size: ScatterSize | str = 'fixed', fixed_size: int | float = 5, size_column: str | None = None, max_size: int | float = 25, responsive_symbol_size: bool = False, show_size_legend: bool = False, size_legend_position: Literal['above', 'below', 'inside-left-top', 'inside-center-top', 'inside-right-top', 'inside-left-bottom', 'inside-center-bottom', 'inside-right-bottom']='above', legend_offset_x: int = 0, legend_offset_y: int = 0, size_legend_values_format: Literal['auto', 'custom']='auto', size_legend_values: list[int | float] = <factory>, size_legend_label_position: Literal['below', 'right']='below', size_legend_label_format: DateFormat | NumberFormat | str = '', size_legend_title_enabled: bool = False, size_legend_title: str = '', size_legend_title_position: Literal['left', 'right', 'above', 'below']='left', size_legend_title_width: int | float = 200, shape: ScatterShape | str = 'fixed', fixed_shape: ScatterShape | str = 'symbolCircle', shape_column: str | None = None, regression: bool = False, regression_method: RegressionMethod | str = 'linear', plot_height_mode: PlotHeightMode | str = 'fixed', plot_height_fixed: int | float = 300, plot_height_ratio: float = 0.5, custom_lines: str = '', label_column: str | None = None, auto_labels: bool = True, add_labels: list[Any] = <factory>, highlight_labeled: bool = True, tooltip_enabled: bool = True, tooltip_title: str = '', tooltip_body: str = '', tooltip_sticky: bool = False)[source]
Bases:
AnnotationsMixin,BaseChartA base class for the Datawrapper API’s scatter plot chart.
- classmethod convert_column_format_dicts(data: dict[str, Any]) dict[str, Any]
Convert dictionary items in transformation to Transform objects.
- classmethod deserialize_data(csv_data: str | DataFrame) DataFrame
Parse CSV string from Datawrapper API into DataFrame.
- Parameters:
csv_data – The CSV data from the chart data endpoint
- Returns:
DataFrame containing the parsed CSV data
- classmethod deserialize_model(api_response: dict[str, Any]) dict[str, Any][source]
Parse Datawrapper API response including scatter plot specific fields.
- Parameters:
api_response – The JSON response from the chart metadata endpoint
chart_data – The CSV data from the chart data endpoint
- Returns:
Dictionary that can be used to initialize the ScatterPlot model
- classmethod get(chart_id: str, access_token: str | None = None) BaseChart
Fetch an existing chart from the Datawrapper API.
- Parameters:
chart_id – The ID of the chart to fetch
access_token – Optional Datawrapper API access token. If not provided, will use DATAWRAPPER_ACCESS_TOKEN environment variable.
- Returns:
An instance of the chart class with data populated from the API.
- Raises:
ValueError – If no access token is available or chart type doesn’t match.
Exception – If the API request fails.
- classmethod model_construct(_fields_set: set[str] | None = None, **values: Any) Self
Creates a new instance of the Model class with validated data.
Creates a new model setting __dict__ and __pydantic_fields_set__ from trusted or pre-validated data. Default values are respected, but no other validation is performed.
- !!! note
model_construct() generally respects the model_config.extra setting on the provided model. That is, if model_config.extra == ‘allow’, then all extra passed values are added to the model instance’s __dict__ and __pydantic_extra__ fields. If model_config.extra == ‘ignore’ (the default), then all extra passed values are ignored. Because no validation is performed with a call to model_construct(), having model_config.extra == ‘forbid’ does not result in an error if extra values are passed, but they will be ignored.
- Parameters:
_fields_set – A set of field names that were originally explicitly set during instantiation. If provided, this is directly used for the [model_fields_set][pydantic.BaseModel.model_fields_set] attribute. Otherwise, the field names from the values argument will be used.
values – Trusted or pre-validated data dictionary.
- Returns:
A new instance of the Model class with validated data.
- classmethod model_json_schema(by_alias: bool = True, ref_template: str = '#/$defs/{model}', schema_generator: type[GenerateJsonSchema] = <class 'pydantic.json_schema.GenerateJsonSchema'>, mode: Literal['validation', 'serialization']='validation', *, union_format: Literal['any_of', 'primitive_type_array']='any_of') dict[str, Any]
Generates a JSON schema for a model class.
- Parameters:
by_alias – Whether to use attribute aliases or not.
ref_template – The reference template.
union_format –
The format to use when combining schemas from unions together. Can be one of:
’any_of’: Use the [anyOf](https://json-schema.org/understanding-json-schema/reference/combining#anyOf)
keyword to combine schemas (the default). - ‘primitive_type_array’: Use the [type](https://json-schema.org/understanding-json-schema/reference/type) keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive type (string, boolean, null, integer or number) or contains constraints/metadata, falls back to any_of.
schema_generator – To override the logic used to generate the JSON schema, as a subclass of GenerateJsonSchema with your desired modifications
mode – The mode in which to generate the schema.
- Returns:
The JSON schema for the given model class.
- classmethod model_parametrized_name(params: tuple[type[Any], ...]) str
Compute the class name for parametrizations of generic classes.
This method can be overridden to achieve a custom naming scheme for generic BaseModels.
- Parameters:
params – Tuple of types of the class. Given a generic class Model with 2 type variables and a concrete model Model[str, int], the value (str, int) would be passed to params.
- Returns:
String representing the new class where params are passed to cls as type variables.
- Raises:
TypeError – Raised when trying to generate concrete names for non-generic models.
- classmethod model_rebuild(*, force: bool = False, raise_errors: bool = True, _parent_namespace_depth: int = 2, _types_namespace: MappingNamespace | None = None) bool | None
Try to rebuild the pydantic-core schema for the model.
This may be necessary when one of the annotations is a ForwardRef which could not be resolved during the initial attempt to build the schema, and automatic rebuilding fails.
- Parameters:
force – Whether to force the rebuilding of the model schema, defaults to False.
raise_errors – Whether to raise errors, defaults to True.
_parent_namespace_depth – The depth level of the parent namespace, defaults to 2.
_types_namespace – The types namespace, defaults to None.
- Returns:
Returns None if the schema is already “complete” and rebuilding was not required. If rebuilding _was_ required, returns True if rebuilding was successful, otherwise False.
- classmethod model_validate(obj: Any, *, strict: bool | None = None, extra: Literal['allow', 'ignore', 'forbid'] | None = None, from_attributes: bool | None = None, context: Any | None = None, by_alias: bool | None = None, by_name: bool | None = None) Self
Validate a pydantic model instance.
- Parameters:
obj – The object to validate.
strict – Whether to enforce types strictly.
extra – Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.
from_attributes – Whether to extract data from object attributes.
context – Additional context to pass to the validator.
by_alias – Whether to use the field’s alias when validating against the provided input data.
by_name – Whether to use the field’s name when validating against the provided input data.
- Raises:
ValidationError – If the object could not be validated.
- Returns:
The validated model instance.
- classmethod model_validate_json(json_data: str | bytes | bytearray, *, strict: bool | None = None, extra: Literal['allow', 'ignore', 'forbid'] | None = None, context: Any | None = None, by_alias: bool | None = None, by_name: bool | None = None) Self
- !!! abstract “Usage Documentation”
[JSON Parsing](../concepts/json.md#json-parsing)
Validate the given JSON data against the Pydantic model.
- Parameters:
json_data – The JSON data to validate.
strict – Whether to enforce types strictly.
extra – Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.
context – Extra variables to pass to the validator.
by_alias – Whether to use the field’s alias when validating against the provided input data.
by_name – Whether to use the field’s name when validating against the provided input data.
- Returns:
The validated Pydantic model.
- Raises:
ValidationError – If json_data is not a JSON string or the object could not be validated.
- classmethod model_validate_strings(obj: Any, *, strict: bool | None = None, extra: Literal['allow', 'ignore', 'forbid'] | None = None, context: Any | None = None, by_alias: bool | None = None, by_name: bool | None = None) Self
Validate the given object with string data against the Pydantic model.
- Parameters:
obj – The object containing string data to validate.
strict – Whether to enforce types strictly.
extra – Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.
context – Extra variables to pass to the validator.
by_alias – Whether to use the field’s alias when validating against the provided input data.
by_name – Whether to use the field’s name when validating against the provided input data.
- Returns:
The validated Pydantic model.
- classmethod validate_plot_height_mode(v: PlotHeightMode | str) PlotHeightMode | str[source]
Validate that plot_height_mode is a valid PlotHeightMode value.
- classmethod warn_on_unrecognized_fields(data: dict[str, Any]) dict[str, Any]
Warn users about unrecognized fields that don’t match model fields or aliases.
This validator checks incoming data against the model’s defined fields and their aliases, issuing warnings for any keys that don’t match. This helps catch typos and misunderstandings about the API without breaking initialization.
- copy(*, include: AbstractSetIntStr | MappingIntStrAny | None = None, exclude: AbstractSetIntStr | MappingIntStrAny | None = None, update: Dict[str, Any] | None = None, deep: bool = False) Self
Returns a copy of the model.
- !!! warning “Deprecated”
This method is now deprecated; use model_copy instead.
If you need include or exclude, use:
`python {test="skip" lint="skip"} data = self.model_dump(include=include, exclude=exclude, round_trip=True) data = {**data, **(update or {})} copied = self.model_validate(data) `- Parameters:
include – Optional set or mapping specifying which fields to include in the copied model.
exclude – Optional set or mapping specifying which fields to exclude in the copied model.
update – Optional dictionary of field-value pairs to override field values in the copied model.
deep – If True, the values of fields that are Pydantic models will be deep-copied.
- Returns:
A copy of the model with included, excluded and updated fields as specified.
- create(access_token: str | None = None, folder_id: int | None = None) BaseChart
Create a new chart via the Datawrapper API.
- Parameters:
access_token – Optional Datawrapper API access token. If not provided, will use DATAWRAPPER_ACCESS_TOKEN environment variable.
folder_id – Optional folder ID to create the chart in.
- Returns:
Self, to enable method chaining. The chart ID is stored in self.chart_id.
- Raises:
ValueError – If no access token is available or API returns invalid response.
Exception – If the API request fails.
- delete(access_token: str | None = None) bool
Delete the chart via the Datawrapper API.
- Parameters:
access_token – Optional Datawrapper API access token. If not provided, will use DATAWRAPPER_ACCESS_TOKEN environment variable.
- Returns:
True if the chart was deleted successfully.
- Raises:
ValueError – If no chart_id is set or no access token is available.
Exception – If the API request fails.
- display(access_token: str | None = None) IFrame
Display the chart as an IFrame in a Jupyter notebook.
- Parameters:
access_token – Optional Datawrapper API access token. If not provided, will use DATAWRAPPER_ACCESS_TOKEN environment variable.
- Returns:
An IPython.display.IFrame object displaying the chart.
- Raises:
ValueError – If no chart_id is set or no access token is available.
Exception – If the API request fails.
- duplicate(access_token: str | None = None) BaseChart
Duplicate the chart and create a new editable copy via the Datawrapper API.
- Parameters:
access_token – Optional Datawrapper API access token. If not provided, will use DATAWRAPPER_ACCESS_TOKEN environment variable.
- Returns:
A new BaseChart instance representing the duplicated chart.
- Raises:
ValueError – If no chart_id is set or no access token is available.
Exception – If the API request fails.
- export_pdf(*, width: int | None = None, height: int | None = None, plain: bool = False, unit: Literal['px', 'mm', 'inch'] = 'px', mode: Literal['rgb', 'cmyk'] = 'rgb', scale: int = 1, zoom: int = 2, transparent: bool = False, border_width: int = 0, border_color: str | None = None, logo: Literal['auto', 'on', 'off'] = 'auto', logo_id: str | None = None, dark: bool = False, ligatures: bool = True, full_vector: bool = False, download: bool = False, access_token: str | None = None, timeout: int = 30) bytes
Export chart as PDF and return the raw bytes.
- Parameters:
width – Width of visualization. If not specified, uses chart width.
height – Height of visualization. If not specified, uses chart height.
plain – If True, exports only the visualization without header/footer.
unit – Unit for measurements: “px”, “mm”, or “inch”.
mode – Color mode: “rgb” or “cmyk”.
scale – Size multiplier that changes actual dimensions (e.g., 2 = 2x size).
zoom – Resolution multiplier for sharper output at same visual size (e.g., 2 = 2x DPI).
transparent – If True, exports with transparent background.
border_width – Margin around visualization.
border_color – Color of the border (e.g., “#FFFFFF”). If not specified, uses chart background color.
logo – Logo display mode: “auto”, “on”, or “off”.
logo_id – Custom logo ID (pattern: ^[a-zA-Z0-9-]+$).
dark – If True, exports in dark mode.
ligatures – If True (default), enables typography ligatures.
full_vector – If True, exports as full vector output.
download – If True, includes download headers in response.
access_token – Optional Datawrapper API access token.
timeout – Timeout for the API request in seconds.
- Returns:
Raw PDF document data as bytes.
- Raises:
ValueError – If no chart_id is set or invalid parameters provided.
Exception – If the API request fails.
Example
>>> chart = BarChart.get(chart_id="abc123") >>> pdf_data = chart.export_pdf(unit="mm", mode="cmyk") >>> Path("chart.pdf").write_bytes(pdf_data)
- export_png(*, width: int | None = None, height: int | None = None, plain: bool = False, scale: int = 1, zoom: int = 2, transparent: bool = False, border_width: int = 0, border_color: str | None = None, logo: Literal['auto', 'on', 'off'] = 'auto', logo_id: str | None = None, dark: bool = False, ligatures: bool = True, full_vector: bool = False, download: bool = False, access_token: str | None = None, timeout: int = 30) bytes
Export chart as PNG and return the raw bytes.
- Parameters:
width – Width of visualization in pixels. If not specified, uses chart width.
height – Height of visualization in pixels. If not specified, uses chart height.
plain – If True, exports only the visualization without header/footer.
scale – Size multiplier that changes actual dimensions (e.g., 2 = 2x size).
zoom – Resolution multiplier for sharper output at same visual size (e.g., 2 = 2x DPI).
transparent – If True, exports with transparent background.
border_width – Margin around visualization in pixels.
border_color – Color of the border (e.g., “#FFFFFF”). If not specified, uses chart background color.
logo – Logo display mode: “auto”, “on”, or “off”.
logo_id – Custom logo ID (pattern: ^[a-zA-Z0-9-]+$).
dark – If True, exports in dark mode.
ligatures – If True (default), enables typography ligatures.
full_vector – If True, exports as full vector output.
download – If True, includes download headers in response.
access_token – Optional Datawrapper API access token.
timeout – Timeout for the API request in seconds.
- Returns:
Raw PNG image data as bytes.
- Raises:
ValueError – If no chart_id is set.
Exception – If the API request fails.
Example
>>> chart = LineChart.get(chart_id="abc123") >>> png_data = chart.export_png(zoom=3, transparent=True) >>> Path("chart.png").write_bytes(png_data)
- export_svg(*, width: int | None = None, height: int | None = None, plain: bool = False, scale: int = 1, zoom: int = 2, transparent: bool = False, border_width: int = 0, border_color: str | None = None, logo: Literal['auto', 'on', 'off'] = 'auto', logo_id: str | None = None, dark: bool = False, ligatures: bool = True, full_vector: bool = False, download: bool = False, access_token: str | None = None, timeout: int = 30) bytes
Export chart as SVG and return the raw bytes.
- Parameters:
width – Width of visualization. If not specified, uses chart width.
height – Height of visualization. If not specified, uses chart height.
plain – If True, exports only the visualization without header/footer.
scale – Size multiplier that changes actual dimensions (e.g., 2 = 2x size).
zoom – Resolution multiplier for sharper output at same visual size (e.g., 2 = 2x DPI).
transparent – If True, exports with transparent background.
border_width – Margin around visualization in pixels.
border_color – Color of the border (e.g., “#FFFFFF”). If not specified, uses chart background color.
logo – Logo display mode: “auto”, “on”, or “off”.
logo_id – Custom logo ID (pattern: ^[a-zA-Z0-9-]+$).
dark – If True, exports in dark mode.
ligatures – If True (default), enables typography ligatures.
full_vector – If True, exports as full vector output.
download – If True, includes download headers in response.
access_token – Optional Datawrapper API access token.
timeout – Timeout for the API request in seconds.
- Returns:
Raw SVG document data as bytes.
- Raises:
ValueError – If no chart_id is set.
Exception – If the API request fails.
Example
>>> chart = ColumnChart.get(chart_id="abc123") >>> svg_data = chart.export_svg(plain=True) >>> Path("chart.svg").write_bytes(svg_data)
- fork(access_token: str | None = None) BaseChart
Fork the chart and create an editable copy via the Datawrapper API.
- Parameters:
access_token – Optional Datawrapper API access token. If not provided, will use DATAWRAPPER_ACCESS_TOKEN environment variable.
- Returns:
A new BaseChart instance representing the forked chart.
- Raises:
ValueError – If no chart_id is set or no access token is available.
Exception – If the API request fails.
- get_display_urls(access_token: str | None = None) list[dict]
Get the URLs for the published chart, table or map.
- Parameters:
access_token – Optional Datawrapper API access token. If not provided, will use DATAWRAPPER_ACCESS_TOKEN environment variable.
- Returns:
A list of dictionaries containing the display URLs for the chart.
- Raises:
ValueError – If no chart_id is set or no access token is available.
Exception – If the API request fails.
- get_editor_url() str
Get the Datawrapper editor URL for this chart.
- Returns:
The Datawrapper editor URL as a string.
- Raises:
ValueError – If no chart_id is set.
- get_iframe_code(responsive: bool = False, access_token: str | None = None) str
Get the iframe embed code for the chart, table, or map.
- Parameters:
responsive – Whether to return responsive iframe code, by default False
access_token – Optional Datawrapper API access token. If not provided, will use DATAWRAPPER_ACCESS_TOKEN environment variable.
- Returns:
The iframe embed code as a string.
- Raises:
ValueError – If no chart_id is set or no access token is available.
Exception – If the API request fails.
- get_png_url() str
Get the fallback PNG image URL for noscript tags.
- Returns:
//datawrapper.dwcdn.net/{chart_id}/full.png
- Return type:
The PNG image URL in the format https
- Raises:
ValueError – If no chart_id is set.
- get_public_url() str
Get the public URL for the published chart.
- Returns:
//datawrapper.dwcdn.net/{chart_id}/
- Return type:
The public URL in the format https
- Raises:
ValueError – If no chart_id is set.
Note
This method returns the URL regardless of whether the chart is actually published. If the chart is not published, the URL will not be accessible. Use publish() to publish the chart before accessing this URL.
- model_copy(*, update: Mapping[str, Any] | None = None, deep: bool = False) Self
- !!! abstract “Usage Documentation”
[model_copy](../concepts/models.md#model-copy)
Returns a copy of the model.
- !!! note
The underlying instance’s [__dict__][object.__dict__] attribute is copied. This might have unexpected side effects if you store anything in it, on top of the model fields (e.g. the value of [cached properties][functools.cached_property]).
- Parameters:
update – Values to change/add in the new model. Note: the data is not validated before creating the new model. You should trust this data.
deep – Set to True to make a deep copy of the model.
- Returns:
New model instance.
- model_dump(*, mode: Literal['json', 'python'] | str = 'python', include: set[int] | set[str] | Mapping[int, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | Mapping[str, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | None = None, exclude: set[int] | set[str] | Mapping[int, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | Mapping[str, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | None = None, context: Any | None = None, by_alias: bool | None = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, exclude_computed_fields: bool = False, round_trip: bool = False, warnings: bool | Literal['none', 'warn', 'error'] = True, fallback: Callable[[Any], Any] | None = None, serialize_as_any: bool = False, polymorphic_serialization: bool | None = None) dict[str, Any]
- !!! abstract “Usage Documentation”
[model_dump](../concepts/serialization.md#python-mode)
Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
- Parameters:
mode – The mode in which to_python should run. If mode is ‘json’, the output will only contain JSON serializable types. If mode is ‘python’, the output may contain non-JSON-serializable Python objects.
include – A set of fields to include in the output.
exclude – A set of fields to exclude from the output.
context – Additional context to pass to the serializer.
by_alias – Whether to use the field’s alias in the dictionary key if defined.
exclude_unset – Whether to exclude fields that have not been explicitly set.
exclude_defaults – Whether to exclude fields that are set to their default value.
exclude_none – Whether to exclude fields that have a value of None.
exclude_computed_fields – Whether to exclude computed fields. While this can be useful for round-tripping, it is usually recommended to use the dedicated round_trip parameter instead.
round_trip – If True, dumped values should be valid as input for non-idempotent types such as Json[T].
warnings – How to handle serialization errors. False/”none” ignores them, True/”warn” logs errors, “error” raises a [PydanticSerializationError][pydantic_core.PydanticSerializationError].
fallback – A function to call when an unknown value is encountered. If not provided, a [PydanticSerializationError][pydantic_core.PydanticSerializationError] error is raised.
serialize_as_any – Whether to serialize fields with duck-typing serialization behavior.
polymorphic_serialization – Whether to use model and dataclass polymorphic serialization for this call.
- Returns:
A dictionary representation of the model.
- model_dump_json(*, indent: int | None = None, ensure_ascii: bool = False, include: set[int] | set[str] | Mapping[int, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | Mapping[str, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | None = None, exclude: set[int] | set[str] | Mapping[int, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | Mapping[str, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | None = None, context: Any | None = None, by_alias: bool | None = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, exclude_computed_fields: bool = False, round_trip: bool = False, warnings: bool | Literal['none', 'warn', 'error'] = True, fallback: Callable[[Any], Any] | None = None, serialize_as_any: bool = False, polymorphic_serialization: bool | None = None) str
- !!! abstract “Usage Documentation”
[model_dump_json](../concepts/serialization.md#json-mode)
Generates a JSON representation of the model using Pydantic’s to_json method.
- Parameters:
indent – Indentation to use in the JSON output. If None is passed, the output will be compact.
ensure_ascii – If True, the output is guaranteed to have all incoming non-ASCII characters escaped. If False (the default), these characters will be output as-is.
include – Field(s) to include in the JSON output.
exclude – Field(s) to exclude from the JSON output.
context – Additional context to pass to the serializer.
by_alias – Whether to serialize using field aliases.
exclude_unset – Whether to exclude fields that have not been explicitly set.
exclude_defaults – Whether to exclude fields that are set to their default value.
exclude_none – Whether to exclude fields that have a value of None.
exclude_computed_fields – Whether to exclude computed fields. While this can be useful for round-tripping, it is usually recommended to use the dedicated round_trip parameter instead.
round_trip – If True, dumped values should be valid as input for non-idempotent types such as Json[T].
warnings – How to handle serialization errors. False/”none” ignores them, True/”warn” logs errors, “error” raises a [PydanticSerializationError][pydantic_core.PydanticSerializationError].
fallback – A function to call when an unknown value is encountered. If not provided, a [PydanticSerializationError][pydantic_core.PydanticSerializationError] error is raised.
serialize_as_any – Whether to serialize fields with duck-typing serialization behavior.
polymorphic_serialization – Whether to use model and dataclass polymorphic serialization for this call.
- Returns:
A JSON string representation of the model.
- model_post_init(context: Any, /) None
Override this method to perform additional initialization after __init__ and model_construct. This is useful if you want to do some validation that requires the entire model to be initialized.
- publish(access_token: str | None = None) BaseChart
Publish the chart via the Datawrapper API.
- Parameters:
access_token – Optional Datawrapper API access token. If not provided, will use DATAWRAPPER_ACCESS_TOKEN environment variable.
- Returns:
Self, to enable method chaining.
- Raises:
ValueError – If no chart_id is set or no access token is available.
Exception – If the API request fails or publishing fails.
- serialize_data() str | None
Convert data to CSV string for API upload.
- Returns:
CSV string representation of the data, or None if data is empty.
- update(access_token: str | None = None) BaseChart
Update an existing chart via the Datawrapper API.
- Parameters:
access_token – Optional Datawrapper API access token. If not provided, will use DATAWRAPPER_ACCESS_TOKEN environment variable.
- Returns:
Self, to enable method chaining.
- Raises:
ValueError – If no chart_id is set or no access token is available.
Exception – If the API request fails.
- add_labels: list[Any]
Values to add labels for
- aria_description
The alternative text for screen readers
- auto_dark_mode
Whether the chart should automatically flip to dark mode when the user’s system is in dark mode
- auto_labels: bool
Whether to automatically label symbols
- base_color: str | int
The default color (palette index or hex string)
- byline
The byline that appears below the chart
- category_labels: dict[str, str]
Dictionary mapping category names to their display labels in the color legend
- category_order: list[str]
List defining the order in which categories appear in the chart and legend
- chart_id
The chart ID after creation (populated by create() method)
- chart_type: Literal['d3-scatter-plot']
The type of datawrapper chart to create
- color_category: dict[str, str]
A mapping of layer names to colors
- color_column: str
The column with the color for the points
- color_outline: str
The color of the outline stroke
- custom
A dictionary of custom tags to attach to the chart
- custom_lines: str
Add custom lines on the chart
- dark_mode_invert
Whether to invert colors in dark mode
- data
The data to use for the chart
- download_image
Whether to allow PNG download
- download_pdf
Whether to allow PDF download
- download_svg
Whether to allow SVG download
- embed
Whether to allow embedding
- exclude_from_color_key: list[str]
A list of columns to exclude from the color key
- fixed_shape: ScatterShape | str
Options for the shape
- fixed_size: int | float
The fixed size, if it’s set that way
- force_attribution
Whether to attribute the chart to datawrapper
- forkable
Whether to allow other users to fork this visualization
- get_the_data
Whether to allow data downloads
- hide_title
Whether or not to hide the title
- highlight_labeled: bool
Whether to highlight labeled symbols
- intro
The intro text that appears above the chart
- label_column: str | None
The column to use for the labels
- language
The locale of the chart, which defines decimal and thousand separators as well as translations of month and weekday names.
- legend_offset_x: int
The percentage offset of the size legend on the x-axis
- legend_offset_y: int
The percentage offset of the size legend on the y-axis
- logo
Whether to show a logo
- logo_id
The id of the logo to show
- max_size: int | float
The maximum size of a dynamic setting
- model_config = {'arbitrary_types_allowed': True, 'json_schema_extra': {'examples': [{'chart-type': 'd3-scatter-plot', 'data': Country GDP Life Expectancy Population 0 USA 60000 79 330 1 China 15000 76 1400 2 India 7000 69 1380, 'size_column': 'Population', 'title': 'GDP vs Life Expectancy', 'x_column': 'GDP', 'y_column': 'Life Expectancy'}]}, 'populate_by_name': True, 'strict': True, 'use_enum_values': True, 'validate_assignment': True, 'validate_by_alias': True, 'validate_by_name': True, 'validate_default': True}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- property model_extra: dict[str, Any] | None
Get extra fields set during validation.
- Returns:
A dictionary of extra fields, or None if config.extra is not set to “allow”.
- property model_fields_set: set[str]
Returns the set of fields that have been explicitly set on this model instance.
- Returns:
- A set of strings representing the fields that have been set,
i.e. that were not filled from defaults.
- notes
The footnotes that appear below the chart
- opacity: float
The opacity of the points
- outlines: bool
Whether to show an outline stroke on points
- plot_height_fixed: int | float
The fixed height of the plot
- plot_height_mode: PlotHeightMode | str
How to set the plot height
- plot_height_ratio: float
The ratio of the plot height
- regression: bool
Whether or not to show a regression line
- regression_method: RegressionMethod | str
The regression method to use
- responsive_symbol_size: bool
Whether to reduce the size on mobile phones
- shape: ScatterShape | str
How to set the shape
- shape_column: str | None
The columns to get the variable shapes for
Whether to show social media share buttons
What URL to share
- show_color_key: bool
Whether to show the color key
- show_size_legend: bool
Whether to show the size legend
- size: ScatterSize | str
How the size is set
- size_column: str | None
The dynamic column to size with
- size_legend_label_format: DateFormat | NumberFormat | str
How to format the size legend label values (use DateFormat or NumberFormat enum or custom format strings)
- size_legend_label_position: Literal['below', 'right']
Where to put the value labels on the size legend
- size_legend_position: Literal['above', 'below', 'inside-left-top', 'inside-center-top', 'inside-right-top', 'inside-left-bottom', 'inside-center-bottom', 'inside-right-bottom']
Where to show the size legend
- size_legend_title: str
What to put in the size legend title
- size_legend_title_enabled: bool
Whether to show a size legend title
- size_legend_title_position: Literal['left', 'right', 'above', 'below']
Where to put the size legend title
- size_legend_title_width: int | float
The maximum width of the size legend title in pixels
- size_legend_values: list[int | float]
The list of values to include in the size legend
- size_legend_values_format: Literal['auto', 'custom']
How to format the values of the size legend
- source_name
The source name that appears below the chart
- source_url
The source URL that appears below the chart
- theme
The theme of the chart
- title
The headline that appears above the chart
- tooltip_body: str
Tooltip body format
- tooltip_enabled: bool
Whether to show tooltips
- tooltip_sticky: bool
Whether the tooltip is sticky on click
- tooltip_title: str
Tooltip title format
- transformations
The metadata options for the data columns in the “Check and Describe” tab
- x_column: str | None
The column to use for the x-axis
- x_format: DateFormat | NumberFormat | str
Format of the x-axis ticks (use DateFormat or NumberFormat enum or custom format strings)
- x_grid_lines: ScatterGridLines | str
How to display x-axis grid lines
- x_log: bool
Set the x-axis on a Logarithmic scale
- x_position: ScatterAxisPosition | str
The position of the x-axis ticks and labels
- x_range: tuple[Any, Any] | list[Any]
The range for the x-axis
- x_ticks: list[Any]
Custom ticks for the x-axis
- y_column: str | None
The column to use for the y-axis
- y_format: DateFormat | NumberFormat | str
Format of the y-axis ticks (use DateFormat or NumberFormat enum or custom format strings)
- y_grid_lines: ScatterGridLines | str
How to display y-axis grid lines
- y_log: bool
Set the y-axis on a Logarithmic scale
- y_position: ScatterAxisPosition | str
The position of the y-axis ticks and labels
- y_range: tuple[Any, Any] | list[Any]
The range for the y-axis
- y_ticks: list[Any]
Custom ticks for the y-axis
Stacked Bar Chart
- class datawrapper.charts.StackedBarChart(*, chart_type: Literal['d3-bars-stacked'] = 'd3-bars-stacked', data: DataFrame | list[dict] = <factory>, transformations: Transform | dict[str, ~typing.Any]=<factory>, title: str = '', intro: str = '', notes: str = '', source_name: str = '', source_url: str = '', byline: str = '', aria_description: str = '', hide_title: bool = False, language: str = 'en-US', theme: str = 'datawrapper', autoDarkMode: bool = False, dark_mode_invert: bool = True, get_the_data: bool = False, download_image: bool = False, download_pdf: bool = False, download_svg: bool = False, embed: bool = False, force_attribution: bool = False, share_buttons: bool = False, share_url: str = '', logo: bool = False, logo_id: str = '', custom: dict[str, ~typing.Any]=<factory>, forkable: bool = True, chart_id: str | None = None, color_category: dict[str, str]=<factory>, replace_flags: ReplaceFlagsType | str = 'off', sort_ranges: bool = False, thick_bars: bool = False, reverse_order: bool = False, value_label_format: DateFormat | NumberFormat | str = '', date_label_format: DateFormat | str = '', range_value_labels: str = '', show_color_key: bool = False, value_label_mode: ValueLabelMode | str = 'left', stack_percentages: bool = False, sort_bars: bool = False, sort_by: str = '', base_color: str | int = 0, block_labels: bool = False, negative_color: str | None = None, groups_column: str | None = None)[source]
Bases:
BaseChartA Pydantic model for the Datawrapper API’s stacked bar chart.
- classmethod convert_column_format_dicts(data: dict[str, Any]) dict[str, Any]
Convert dictionary items in transformation to Transform objects.
- classmethod deserialize_data(csv_data: str | DataFrame) DataFrame
Parse CSV string from Datawrapper API into DataFrame.
- Parameters:
csv_data – The CSV data from the chart data endpoint
- Returns:
DataFrame containing the parsed CSV data
- classmethod deserialize_model(api_response: dict[str, Any]) dict[str, Any][source]
Parse Datawrapper API response including stacked bar specific fields.
- Parameters:
api_response – The JSON response from the chart metadata endpoint
chart_data – The CSV data from the chart data endpoint
- Returns:
Dictionary that can be used to initialize the StackedBarChart model
- classmethod get(chart_id: str, access_token: str | None = None) BaseChart
Fetch an existing chart from the Datawrapper API.
- Parameters:
chart_id – The ID of the chart to fetch
access_token – Optional Datawrapper API access token. If not provided, will use DATAWRAPPER_ACCESS_TOKEN environment variable.
- Returns:
An instance of the chart class with data populated from the API.
- Raises:
ValueError – If no access token is available or chart type doesn’t match.
Exception – If the API request fails.
- classmethod model_construct(_fields_set: set[str] | None = None, **values: Any) Self
Creates a new instance of the Model class with validated data.
Creates a new model setting __dict__ and __pydantic_fields_set__ from trusted or pre-validated data. Default values are respected, but no other validation is performed.
- !!! note
model_construct() generally respects the model_config.extra setting on the provided model. That is, if model_config.extra == ‘allow’, then all extra passed values are added to the model instance’s __dict__ and __pydantic_extra__ fields. If model_config.extra == ‘ignore’ (the default), then all extra passed values are ignored. Because no validation is performed with a call to model_construct(), having model_config.extra == ‘forbid’ does not result in an error if extra values are passed, but they will be ignored.
- Parameters:
_fields_set – A set of field names that were originally explicitly set during instantiation. If provided, this is directly used for the [model_fields_set][pydantic.BaseModel.model_fields_set] attribute. Otherwise, the field names from the values argument will be used.
values – Trusted or pre-validated data dictionary.
- Returns:
A new instance of the Model class with validated data.
- classmethod model_json_schema(by_alias: bool = True, ref_template: str = '#/$defs/{model}', schema_generator: type[GenerateJsonSchema] = <class 'pydantic.json_schema.GenerateJsonSchema'>, mode: Literal['validation', 'serialization']='validation', *, union_format: Literal['any_of', 'primitive_type_array']='any_of') dict[str, Any]
Generates a JSON schema for a model class.
- Parameters:
by_alias – Whether to use attribute aliases or not.
ref_template – The reference template.
union_format –
The format to use when combining schemas from unions together. Can be one of:
’any_of’: Use the [anyOf](https://json-schema.org/understanding-json-schema/reference/combining#anyOf)
keyword to combine schemas (the default). - ‘primitive_type_array’: Use the [type](https://json-schema.org/understanding-json-schema/reference/type) keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive type (string, boolean, null, integer or number) or contains constraints/metadata, falls back to any_of.
schema_generator – To override the logic used to generate the JSON schema, as a subclass of GenerateJsonSchema with your desired modifications
mode – The mode in which to generate the schema.
- Returns:
The JSON schema for the given model class.
- classmethod model_parametrized_name(params: tuple[type[Any], ...]) str
Compute the class name for parametrizations of generic classes.
This method can be overridden to achieve a custom naming scheme for generic BaseModels.
- Parameters:
params – Tuple of types of the class. Given a generic class Model with 2 type variables and a concrete model Model[str, int], the value (str, int) would be passed to params.
- Returns:
String representing the new class where params are passed to cls as type variables.
- Raises:
TypeError – Raised when trying to generate concrete names for non-generic models.
- classmethod model_rebuild(*, force: bool = False, raise_errors: bool = True, _parent_namespace_depth: int = 2, _types_namespace: MappingNamespace | None = None) bool | None
Try to rebuild the pydantic-core schema for the model.
This may be necessary when one of the annotations is a ForwardRef which could not be resolved during the initial attempt to build the schema, and automatic rebuilding fails.
- Parameters:
force – Whether to force the rebuilding of the model schema, defaults to False.
raise_errors – Whether to raise errors, defaults to True.
_parent_namespace_depth – The depth level of the parent namespace, defaults to 2.
_types_namespace – The types namespace, defaults to None.
- Returns:
Returns None if the schema is already “complete” and rebuilding was not required. If rebuilding _was_ required, returns True if rebuilding was successful, otherwise False.
- classmethod model_validate(obj: Any, *, strict: bool | None = None, extra: Literal['allow', 'ignore', 'forbid'] | None = None, from_attributes: bool | None = None, context: Any | None = None, by_alias: bool | None = None, by_name: bool | None = None) Self
Validate a pydantic model instance.
- Parameters:
obj – The object to validate.
strict – Whether to enforce types strictly.
extra – Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.
from_attributes – Whether to extract data from object attributes.
context – Additional context to pass to the validator.
by_alias – Whether to use the field’s alias when validating against the provided input data.
by_name – Whether to use the field’s name when validating against the provided input data.
- Raises:
ValidationError – If the object could not be validated.
- Returns:
The validated model instance.
- classmethod model_validate_json(json_data: str | bytes | bytearray, *, strict: bool | None = None, extra: Literal['allow', 'ignore', 'forbid'] | None = None, context: Any | None = None, by_alias: bool | None = None, by_name: bool | None = None) Self
- !!! abstract “Usage Documentation”
[JSON Parsing](../concepts/json.md#json-parsing)
Validate the given JSON data against the Pydantic model.
- Parameters:
json_data – The JSON data to validate.
strict – Whether to enforce types strictly.
extra – Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.
context – Extra variables to pass to the validator.
by_alias – Whether to use the field’s alias when validating against the provided input data.
by_name – Whether to use the field’s name when validating against the provided input data.
- Returns:
The validated Pydantic model.
- Raises:
ValidationError – If json_data is not a JSON string or the object could not be validated.
- classmethod model_validate_strings(obj: Any, *, strict: bool | None = None, extra: Literal['allow', 'ignore', 'forbid'] | None = None, context: Any | None = None, by_alias: bool | None = None, by_name: bool | None = None) Self
Validate the given object with string data against the Pydantic model.
- Parameters:
obj – The object containing string data to validate.
strict – Whether to enforce types strictly.
extra – Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.
context – Extra variables to pass to the validator.
by_alias – Whether to use the field’s alias when validating against the provided input data.
by_name – Whether to use the field’s name when validating against the provided input data.
- Returns:
The validated Pydantic model.
- classmethod validate_replace_flags(v: ReplaceFlagsType | str) ReplaceFlagsType | str[source]
Validate that replace_flags is a valid ReplaceFlagsType value.
- classmethod validate_value_label_mode(v: ValueLabelMode | str) ValueLabelMode | str[source]
Validate that value_label_mode is a valid ValueLabelMode value.
- classmethod warn_on_unrecognized_fields(data: dict[str, Any]) dict[str, Any]
Warn users about unrecognized fields that don’t match model fields or aliases.
This validator checks incoming data against the model’s defined fields and their aliases, issuing warnings for any keys that don’t match. This helps catch typos and misunderstandings about the API without breaking initialization.
- copy(*, include: AbstractSetIntStr | MappingIntStrAny | None = None, exclude: AbstractSetIntStr | MappingIntStrAny | None = None, update: Dict[str, Any] | None = None, deep: bool = False) Self
Returns a copy of the model.
- !!! warning “Deprecated”
This method is now deprecated; use model_copy instead.
If you need include or exclude, use:
`python {test="skip" lint="skip"} data = self.model_dump(include=include, exclude=exclude, round_trip=True) data = {**data, **(update or {})} copied = self.model_validate(data) `- Parameters:
include – Optional set or mapping specifying which fields to include in the copied model.
exclude – Optional set or mapping specifying which fields to exclude in the copied model.
update – Optional dictionary of field-value pairs to override field values in the copied model.
deep – If True, the values of fields that are Pydantic models will be deep-copied.
- Returns:
A copy of the model with included, excluded and updated fields as specified.
- create(access_token: str | None = None, folder_id: int | None = None) BaseChart
Create a new chart via the Datawrapper API.
- Parameters:
access_token – Optional Datawrapper API access token. If not provided, will use DATAWRAPPER_ACCESS_TOKEN environment variable.
folder_id – Optional folder ID to create the chart in.
- Returns:
Self, to enable method chaining. The chart ID is stored in self.chart_id.
- Raises:
ValueError – If no access token is available or API returns invalid response.
Exception – If the API request fails.
- delete(access_token: str | None = None) bool
Delete the chart via the Datawrapper API.
- Parameters:
access_token – Optional Datawrapper API access token. If not provided, will use DATAWRAPPER_ACCESS_TOKEN environment variable.
- Returns:
True if the chart was deleted successfully.
- Raises:
ValueError – If no chart_id is set or no access token is available.
Exception – If the API request fails.
- display(access_token: str | None = None) IFrame
Display the chart as an IFrame in a Jupyter notebook.
- Parameters:
access_token – Optional Datawrapper API access token. If not provided, will use DATAWRAPPER_ACCESS_TOKEN environment variable.
- Returns:
An IPython.display.IFrame object displaying the chart.
- Raises:
ValueError – If no chart_id is set or no access token is available.
Exception – If the API request fails.
- duplicate(access_token: str | None = None) BaseChart
Duplicate the chart and create a new editable copy via the Datawrapper API.
- Parameters:
access_token – Optional Datawrapper API access token. If not provided, will use DATAWRAPPER_ACCESS_TOKEN environment variable.
- Returns:
A new BaseChart instance representing the duplicated chart.
- Raises:
ValueError – If no chart_id is set or no access token is available.
Exception – If the API request fails.
- export_pdf(*, width: int | None = None, height: int | None = None, plain: bool = False, unit: Literal['px', 'mm', 'inch'] = 'px', mode: Literal['rgb', 'cmyk'] = 'rgb', scale: int = 1, zoom: int = 2, transparent: bool = False, border_width: int = 0, border_color: str | None = None, logo: Literal['auto', 'on', 'off'] = 'auto', logo_id: str | None = None, dark: bool = False, ligatures: bool = True, full_vector: bool = False, download: bool = False, access_token: str | None = None, timeout: int = 30) bytes
Export chart as PDF and return the raw bytes.
- Parameters:
width – Width of visualization. If not specified, uses chart width.
height – Height of visualization. If not specified, uses chart height.
plain – If True, exports only the visualization without header/footer.
unit – Unit for measurements: “px”, “mm”, or “inch”.
mode – Color mode: “rgb” or “cmyk”.
scale – Size multiplier that changes actual dimensions (e.g., 2 = 2x size).
zoom – Resolution multiplier for sharper output at same visual size (e.g., 2 = 2x DPI).
transparent – If True, exports with transparent background.
border_width – Margin around visualization.
border_color – Color of the border (e.g., “#FFFFFF”). If not specified, uses chart background color.
logo – Logo display mode: “auto”, “on”, or “off”.
logo_id – Custom logo ID (pattern: ^[a-zA-Z0-9-]+$).
dark – If True, exports in dark mode.
ligatures – If True (default), enables typography ligatures.
full_vector – If True, exports as full vector output.
download – If True, includes download headers in response.
access_token – Optional Datawrapper API access token.
timeout – Timeout for the API request in seconds.
- Returns:
Raw PDF document data as bytes.
- Raises:
ValueError – If no chart_id is set or invalid parameters provided.
Exception – If the API request fails.
Example
>>> chart = BarChart.get(chart_id="abc123") >>> pdf_data = chart.export_pdf(unit="mm", mode="cmyk") >>> Path("chart.pdf").write_bytes(pdf_data)
- export_png(*, width: int | None = None, height: int | None = None, plain: bool = False, scale: int = 1, zoom: int = 2, transparent: bool = False, border_width: int = 0, border_color: str | None = None, logo: Literal['auto', 'on', 'off'] = 'auto', logo_id: str | None = None, dark: bool = False, ligatures: bool = True, full_vector: bool = False, download: bool = False, access_token: str | None = None, timeout: int = 30) bytes
Export chart as PNG and return the raw bytes.
- Parameters:
width – Width of visualization in pixels. If not specified, uses chart width.
height – Height of visualization in pixels. If not specified, uses chart height.
plain – If True, exports only the visualization without header/footer.
scale – Size multiplier that changes actual dimensions (e.g., 2 = 2x size).
zoom – Resolution multiplier for sharper output at same visual size (e.g., 2 = 2x DPI).
transparent – If True, exports with transparent background.
border_width – Margin around visualization in pixels.
border_color – Color of the border (e.g., “#FFFFFF”). If not specified, uses chart background color.
logo – Logo display mode: “auto”, “on”, or “off”.
logo_id – Custom logo ID (pattern: ^[a-zA-Z0-9-]+$).
dark – If True, exports in dark mode.
ligatures – If True (default), enables typography ligatures.
full_vector – If True, exports as full vector output.
download – If True, includes download headers in response.
access_token – Optional Datawrapper API access token.
timeout – Timeout for the API request in seconds.
- Returns:
Raw PNG image data as bytes.
- Raises:
ValueError – If no chart_id is set.
Exception – If the API request fails.
Example
>>> chart = LineChart.get(chart_id="abc123") >>> png_data = chart.export_png(zoom=3, transparent=True) >>> Path("chart.png").write_bytes(png_data)
- export_svg(*, width: int | None = None, height: int | None = None, plain: bool = False, scale: int = 1, zoom: int = 2, transparent: bool = False, border_width: int = 0, border_color: str | None = None, logo: Literal['auto', 'on', 'off'] = 'auto', logo_id: str | None = None, dark: bool = False, ligatures: bool = True, full_vector: bool = False, download: bool = False, access_token: str | None = None, timeout: int = 30) bytes
Export chart as SVG and return the raw bytes.
- Parameters:
width – Width of visualization. If not specified, uses chart width.
height – Height of visualization. If not specified, uses chart height.
plain – If True, exports only the visualization without header/footer.
scale – Size multiplier that changes actual dimensions (e.g., 2 = 2x size).
zoom – Resolution multiplier for sharper output at same visual size (e.g., 2 = 2x DPI).
transparent – If True, exports with transparent background.
border_width – Margin around visualization in pixels.
border_color – Color of the border (e.g., “#FFFFFF”). If not specified, uses chart background color.
logo – Logo display mode: “auto”, “on”, or “off”.
logo_id – Custom logo ID (pattern: ^[a-zA-Z0-9-]+$).
dark – If True, exports in dark mode.
ligatures – If True (default), enables typography ligatures.
full_vector – If True, exports as full vector output.
download – If True, includes download headers in response.
access_token – Optional Datawrapper API access token.
timeout – Timeout for the API request in seconds.
- Returns:
Raw SVG document data as bytes.
- Raises:
ValueError – If no chart_id is set.
Exception – If the API request fails.
Example
>>> chart = ColumnChart.get(chart_id="abc123") >>> svg_data = chart.export_svg(plain=True) >>> Path("chart.svg").write_bytes(svg_data)
- fork(access_token: str | None = None) BaseChart
Fork the chart and create an editable copy via the Datawrapper API.
- Parameters:
access_token – Optional Datawrapper API access token. If not provided, will use DATAWRAPPER_ACCESS_TOKEN environment variable.
- Returns:
A new BaseChart instance representing the forked chart.
- Raises:
ValueError – If no chart_id is set or no access token is available.
Exception – If the API request fails.
- get_display_urls(access_token: str | None = None) list[dict]
Get the URLs for the published chart, table or map.
- Parameters:
access_token – Optional Datawrapper API access token. If not provided, will use DATAWRAPPER_ACCESS_TOKEN environment variable.
- Returns:
A list of dictionaries containing the display URLs for the chart.
- Raises:
ValueError – If no chart_id is set or no access token is available.
Exception – If the API request fails.
- get_editor_url() str
Get the Datawrapper editor URL for this chart.
- Returns:
The Datawrapper editor URL as a string.
- Raises:
ValueError – If no chart_id is set.
- get_iframe_code(responsive: bool = False, access_token: str | None = None) str
Get the iframe embed code for the chart, table, or map.
- Parameters:
responsive – Whether to return responsive iframe code, by default False
access_token – Optional Datawrapper API access token. If not provided, will use DATAWRAPPER_ACCESS_TOKEN environment variable.
- Returns:
The iframe embed code as a string.
- Raises:
ValueError – If no chart_id is set or no access token is available.
Exception – If the API request fails.
- get_png_url() str
Get the fallback PNG image URL for noscript tags.
- Returns:
//datawrapper.dwcdn.net/{chart_id}/full.png
- Return type:
The PNG image URL in the format https
- Raises:
ValueError – If no chart_id is set.
- get_public_url() str
Get the public URL for the published chart.
- Returns:
//datawrapper.dwcdn.net/{chart_id}/
- Return type:
The public URL in the format https
- Raises:
ValueError – If no chart_id is set.
Note
This method returns the URL regardless of whether the chart is actually published. If the chart is not published, the URL will not be accessible. Use publish() to publish the chart before accessing this URL.
- model_copy(*, update: Mapping[str, Any] | None = None, deep: bool = False) Self
- !!! abstract “Usage Documentation”
[model_copy](../concepts/models.md#model-copy)
Returns a copy of the model.
- !!! note
The underlying instance’s [__dict__][object.__dict__] attribute is copied. This might have unexpected side effects if you store anything in it, on top of the model fields (e.g. the value of [cached properties][functools.cached_property]).
- Parameters:
update – Values to change/add in the new model. Note: the data is not validated before creating the new model. You should trust this data.
deep – Set to True to make a deep copy of the model.
- Returns:
New model instance.
- model_dump(*, mode: Literal['json', 'python'] | str = 'python', include: set[int] | set[str] | Mapping[int, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | Mapping[str, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | None = None, exclude: set[int] | set[str] | Mapping[int, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | Mapping[str, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | None = None, context: Any | None = None, by_alias: bool | None = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, exclude_computed_fields: bool = False, round_trip: bool = False, warnings: bool | Literal['none', 'warn', 'error'] = True, fallback: Callable[[Any], Any] | None = None, serialize_as_any: bool = False, polymorphic_serialization: bool | None = None) dict[str, Any]
- !!! abstract “Usage Documentation”
[model_dump](../concepts/serialization.md#python-mode)
Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
- Parameters:
mode – The mode in which to_python should run. If mode is ‘json’, the output will only contain JSON serializable types. If mode is ‘python’, the output may contain non-JSON-serializable Python objects.
include – A set of fields to include in the output.
exclude – A set of fields to exclude from the output.
context – Additional context to pass to the serializer.
by_alias – Whether to use the field’s alias in the dictionary key if defined.
exclude_unset – Whether to exclude fields that have not been explicitly set.
exclude_defaults – Whether to exclude fields that are set to their default value.
exclude_none – Whether to exclude fields that have a value of None.
exclude_computed_fields – Whether to exclude computed fields. While this can be useful for round-tripping, it is usually recommended to use the dedicated round_trip parameter instead.
round_trip – If True, dumped values should be valid as input for non-idempotent types such as Json[T].
warnings – How to handle serialization errors. False/”none” ignores them, True/”warn” logs errors, “error” raises a [PydanticSerializationError][pydantic_core.PydanticSerializationError].
fallback – A function to call when an unknown value is encountered. If not provided, a [PydanticSerializationError][pydantic_core.PydanticSerializationError] error is raised.
serialize_as_any – Whether to serialize fields with duck-typing serialization behavior.
polymorphic_serialization – Whether to use model and dataclass polymorphic serialization for this call.
- Returns:
A dictionary representation of the model.
- model_dump_json(*, indent: int | None = None, ensure_ascii: bool = False, include: set[int] | set[str] | Mapping[int, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | Mapping[str, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | None = None, exclude: set[int] | set[str] | Mapping[int, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | Mapping[str, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | None = None, context: Any | None = None, by_alias: bool | None = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, exclude_computed_fields: bool = False, round_trip: bool = False, warnings: bool | Literal['none', 'warn', 'error'] = True, fallback: Callable[[Any], Any] | None = None, serialize_as_any: bool = False, polymorphic_serialization: bool | None = None) str
- !!! abstract “Usage Documentation”
[model_dump_json](../concepts/serialization.md#json-mode)
Generates a JSON representation of the model using Pydantic’s to_json method.
- Parameters:
indent – Indentation to use in the JSON output. If None is passed, the output will be compact.
ensure_ascii – If True, the output is guaranteed to have all incoming non-ASCII characters escaped. If False (the default), these characters will be output as-is.
include – Field(s) to include in the JSON output.
exclude – Field(s) to exclude from the JSON output.
context – Additional context to pass to the serializer.
by_alias – Whether to serialize using field aliases.
exclude_unset – Whether to exclude fields that have not been explicitly set.
exclude_defaults – Whether to exclude fields that are set to their default value.
exclude_none – Whether to exclude fields that have a value of None.
exclude_computed_fields – Whether to exclude computed fields. While this can be useful for round-tripping, it is usually recommended to use the dedicated round_trip parameter instead.
round_trip – If True, dumped values should be valid as input for non-idempotent types such as Json[T].
warnings – How to handle serialization errors. False/”none” ignores them, True/”warn” logs errors, “error” raises a [PydanticSerializationError][pydantic_core.PydanticSerializationError].
fallback – A function to call when an unknown value is encountered. If not provided, a [PydanticSerializationError][pydantic_core.PydanticSerializationError] error is raised.
serialize_as_any – Whether to serialize fields with duck-typing serialization behavior.
polymorphic_serialization – Whether to use model and dataclass polymorphic serialization for this call.
- Returns:
A JSON string representation of the model.
- model_post_init(context: Any, /) None
Override this method to perform additional initialization after __init__ and model_construct. This is useful if you want to do some validation that requires the entire model to be initialized.
- publish(access_token: str | None = None) BaseChart
Publish the chart via the Datawrapper API.
- Parameters:
access_token – Optional Datawrapper API access token. If not provided, will use DATAWRAPPER_ACCESS_TOKEN environment variable.
- Returns:
Self, to enable method chaining.
- Raises:
ValueError – If no chart_id is set or no access token is available.
Exception – If the API request fails or publishing fails.
- serialize_data() str | None
Convert data to CSV string for API upload.
- Returns:
CSV string representation of the data, or None if data is empty.
- update(access_token: str | None = None) BaseChart
Update an existing chart via the Datawrapper API.
- Parameters:
access_token – Optional Datawrapper API access token. If not provided, will use DATAWRAPPER_ACCESS_TOKEN environment variable.
- Returns:
Self, to enable method chaining.
- Raises:
ValueError – If no chart_id is set or no access token is available.
Exception – If the API request fails.
- aria_description
The alternative text for screen readers
- auto_dark_mode
Whether the chart should automatically flip to dark mode when the user’s system is in dark mode
- base_color: str | int
The base color (can be hex string or palette index)
- block_labels: bool
Whether to use block labels
- byline
The byline that appears below the chart
- chart_id
The chart ID after creation (populated by create() method)
- chart_type: Literal['d3-bars-stacked']
The type of datawrapper chart to create
- color_category: dict[str, str]
A mapping of layer names to colors
- custom
A dictionary of custom tags to attach to the chart
- dark_mode_invert
Whether to invert colors in dark mode
- data
The data to use for the chart
- date_label_format: DateFormat | str
The date format (use DateFormat enum or custom format strings)
- download_image
Whether to allow PNG download
- download_pdf
Whether to allow PDF download
- download_svg
Whether to allow SVG download
- embed
Whether to allow embedding
- force_attribution
Whether to attribute the chart to datawrapper
- forkable
Whether to allow other users to fork this visualization
- get_the_data
Whether to allow data downloads
- groups_column: str | None
The column to use for grouping
- hide_title
Whether or not to hide the title
- intro
The intro text that appears above the chart
- language
The locale of the chart, which defines decimal and thousand separators as well as translations of month and weekday names.
- logo
Whether to show a logo
- logo_id
The id of the logo to show
- model_config = {'arbitrary_types_allowed': True, 'json_schema_extra': {'examples': [{'chart_type': 'd3-lines', 'language': 'en-US', 'source_name': 'Reuters', 'title': 'Sample Chart Title'}, {'chart_type': 'd3-lines', 'language': 'en-US', 'source_name': 'Reuters', 'title': 'Sample Chart Title', 'transformations': {'column-format': [{'column': 'sales', 'number-prepend': '$', 'type': 'number'}], 'column-order': [0, 1, 2], 'external-data': '', 'horizontal-header': True, 'transpose': False, 'upload-method': 'copy', 'use-datawrapper-cdn': True, 'vertical-header': True}}, {'chart_type': 'd3-lines', 'language': 'en-US', 'source_name': 'Reuters', 'title': 'Sample Chart Title', 'transformations': {'column-format': [{'column': 'sales', 'number-prepend': '$', 'type': 'number'}], 'column-order': [0, 1, 2], 'external-data': '', 'horizontal-header': True, 'transpose': False, 'upload-method': 'copy', 'use-datawrapper-cdn': True, 'vertical-header': True}}]}, 'populate_by_name': True, 'strict': True, 'use_enum_values': True, 'validate_assignment': True, 'validate_by_alias': True, 'validate_by_name': True, 'validate_default': True}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- property model_extra: dict[str, Any] | None
Get extra fields set during validation.
- Returns:
A dictionary of extra fields, or None if config.extra is not set to “allow”.
- property model_fields_set: set[str]
Returns the set of fields that have been explicitly set on this model instance.
- Returns:
- A set of strings representing the fields that have been set,
i.e. that were not filled from defaults.
- negative_color: str | None
The negative color to use, if you want one
- notes
The footnotes that appear below the chart
- range_value_labels: str
The field you want to use for the value labels
- replace_flags: ReplaceFlagsType | str
Whether to replace country codes with flags (use ReplaceFlagsType enum or raw string)
- reverse_order: bool
Reverse the order of the ranges
Whether to show social media share buttons
What URL to share
- show_color_key: bool
Enables the legend
- sort_bars: bool
Whether to sort bars
- sort_by: str
Which column to sort by
- sort_ranges: bool
Whether to sort the ranges
- source_name
The source name that appears below the chart
- source_url
The source URL that appears below the chart
- stack_percentages: bool
Whether to display values as percentages
- theme
The theme of the chart
- thick_bars: bool
Whether to use thick bars
- title
The headline that appears above the chart
- transformations
The metadata options for the data columns in the “Check and Describe” tab
- value_label_format: DateFormat | NumberFormat | str
The number format for value labels (use DateFormat or NumberFormat enum or custom format strings)
- value_label_mode: ValueLabelMode | str
How to place the over-bar labels (use ValueLabelMode enum or raw string)