Chart Widgets#
Altair Charts#
- class AltairChart(*args, **kwargs)[source]#
Bases:
Widget,JSONDataViewA widget for rendering Altair charts in Django applications.
This class provides a wrapper around Altair charts, making them easy to integrate into Django templates. It supports both synchronous and asynchronous loading of chart data, and allows for customization of the chart’s appearance.
The chart content is rendered using a Django template, and the chart data is loaded via a JSON endpoint when in asynchronous mode.
Example
import altair as alt from wildewidgets.widgets.charts.altair import AltairChart class MyBarChart(AltairChart): def load(self): # Create an Altair chart data = pd.DataFrame({ 'category': ['A', 'B', 'C'], 'value': [10, 20, 30] }) chart = alt.Chart(data).mark_bar().encode( x='category', y='value' ) self.set_data(chart)
- get_content(**kwargs) str[source]#
Render the chart as HTML content.
This method renders the chart using the specified template file. If the chart data has not been loaded yet, it will set the
asyncflag toTrue, which tells the template to load the data asynchronously via a JSON endpoint.- Parameters:
**kwargs – Arbitrary keyword arguments (not used)
- Returns:
The rendered HTML content for the chart
- Return type:
- get_context_data(**kwargs) dict[str, Any][source]#
Get the context data for rendering the chart.
This method loads the chart data if it hasn’t been loaded yet and adds it to the context data.
- Parameters:
**kwargs – Arbitrary keyword arguments passed to the parent method
- Returns:
The context data for rendering the chart
- Return type:
- load() None[source]#
Load the chart data.
This method should be overridden by subclasses to load the chart data. The implementation should create an Altair chart and call set_data() with it.
The default implementation does nothing.
Example
def load(self): # Load data from a source data = pd.DataFrame(...) # Create an Altair chart chart = alt.Chart(data).mark_bar().encode(...) # Set the chart data self.set_data(chart)
- set_data(spec, set_size: bool = True)[source]#
Set the chart data from an Altair chart specification.
This method converts an Altair chart specification into a dictionary representation that can be serialized to JSON. It also optionally sets the chart to use container-based sizing.
- Parameters:
spec – The Altair chart specification
set_size – Whether to set the chart to use container-based sizing When True, the chart will fill its container element. When False, the chart will use its own width and height settings.
Apex Charts#
- class ApexChartBase(*args: Any, **kwargs: Any)[source]#
Bases:
WidgetInitKwargsMixinBase class for Apex Charts in Django applications.
This class provides the foundation for creating interactive Apex charts in Django applications. It handles chart configuration, dataset management, and rendering.
- chart_options#
Dictionary containing all chart configuration options
Example
class MyLineChart(ApexChartBase): chart_type = 'line' def __init__(self, **kwargs): super().__init__(**kwargs) dataset = MyDataset() dataset.data = [10, 41, 35, 51, 49, 62, 69, 91, 148] self.add_dataset(dataset) self.add_categories(['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep'])
- add_categories(categories: list[Any]) None[source]#
Set the categories for the chart’s x-axis.
This method sets the labels for the x-axis categories. These are typically used for categorical data like months, product names, etc.
- Parameters:
categories – List of category labels
- add_dataset(dataset: ApexDatasetBase) None[source]#
Add a dataset to the chart.
This method adds a dataset to the chart’s series. Each dataset represents a data series in the chart (e.g., a line in a line chart or a set of bars in a bar chart).
- Parameters:
dataset – The dataset to add to the chart
- add_suboption(option: str, name: str, value: Any) None[source]#
Add a nested configuration option to the chart.
This method adds a configuration option to a nested section of the chart options. It’s useful for setting options in sections like ‘chart’, ‘xaxis’, ‘yaxis’, etc.
- Parameters:
option – The parent option section (e.g., ‘chart’, ‘xaxis’)
name – The name of the specific option
value – The value to set for the option
Example
# Set chart.height = 350 chart.add_suboption('chart', 'height', 350) # Set tooltip.enabled = False chart.add_suboption('tooltip', 'enabled', False)
- get_content(**kwargs: Any) str[source]#
Render the chart as HTML content.
This method renders the chart using the specified template and context data.
- Parameters:
**kwargs – Additional context data (unused)
- Returns:
The rendered HTML content for the chart
- Return type:
- get_context_data(**kwargs: Any) dict[str, Any][source]#
Get the context data for rendering the chart template.
This method prepares the data needed by the Django template to render the chart, including chart options, CSS ID, and extra data.
- Keyword Arguments:
**kwargs – Additional context data
- Returns:
The context data for the template
- Return type:
- class ApexDatasetBase(**kwargs: Any)[source]#
Bases:
WidgetBase class for Apex chart datasets.
This class provides the foundation for defining datasets that can be added to ApexCharts. It handles the transformation of Python data into the format expected by the ApexCharts JavaScript library.
- data#
The list of data points for this dataset
Example
class MyDataset(ApexDatasetBase): name = "Monthly Sales" chart_type = "line" def __init__(self, **kwargs): super().__init__(**kwargs) self.data = [10, 41, 35, 51, 49, 62, 69, 91, 148]
Or use subclassing to customize the dataset further:
class CustomDataset(ApexDatasetBase): name = "Custom Data" chart_type = "bar" def __init__(self, **kwargs): super().__init__(**kwargs) self.data = self.load_custom_data() def load_custom_data(self) -> list[int]: # Load or generate custom data here return [5, 15, 25, 35, 45]
- get_options() dict[str, Any][source]#
Get the dataset options in the format expected by ApexCharts.
This method transforms the dataset’s properties into a dictionary format that can be serialized to JSON and used by the ApexCharts JavaScript library.
- Returns:
The dataset configuration options
- Return type:
- class ApexJSONMixin[source]#
Bases:
objectA mixin class adding AJAX support to Apex Charts.
This mixin enables Apex charts to load their data asynchronously via AJAX. It handles the HTTP request/response cycle and provides methods for preparing the chart data as JSON.
Note
Classes using this mixin should implement the load method to populate the chart’s datasets.
- dispatch(request: HttpRequest, *args: Any, **kwargs: Any) JsonResponse[source]#
Dispatch the request to the appropriate handler method.
This method delegates to the appropriate HTTP method handler (e.g., get, post) based on the request method.
- Parameters:
request – The HTTP request object
*args – Additional positional arguments
- Keyword Arguments:
**kwargs – Additional keyword arguments
- Returns:
The JSON response containing chart data
- Return type:
JsonResponse
- get(_: HttpRequest, *args: Any, **kwargs: Any) JsonResponse[source]#
Handle GET requests for chart data.
This method is called when the client makes an AJAX GET request for chart data. It returns the chart’s series data as JSON.
- Parameters:
_ – The HTTP request object (unused)
*args – Additional positional arguments
**kwargs – Additional keyword arguments
- Returns:
The JSON response containing chart data
- Return type:
JsonResponse
- get_series_data(**kwargs: Any) dict[str, Any][source]#
Get the chart series data.
This method loads the chart data and adds the series to the provided keyword arguments.
- Keyword Arguments:
**kwargs – Keyword arguments to update with series data
- Returns:
The updated keyword arguments containing series data
- Return type:
- load() None[source]#
Load datasets into the chart via AJAX.
This method should be overridden by subclasses to populate the chart’s datasets. It will be called when an AJAX request is made for chart data.
Example
def load(self) -> None: dataset = MyDataset() dataset.data = [10, 41, 35, 51, 49, 62, 69, 91, 148] self.add_dataset(dataset)
- render_to_response(context: dict[str, Any], **response_kwargs: Any) JsonResponse[source]#
Render the chart data as a JSON response.
- Parameters:
context – The chart data to be serialized as JSON
- Keyword Arguments:
**response_kwargs – Additional keyword arguments (unused)
- Returns:
The JSON response containing chart data
- Return type:
JsonResponse
- class ApexSparkline(**kwargs: Any)[source]#
Bases:
ApexChartBaseA specialized Apex chart for creating sparklines.
Sparklines are small, simple, condensed charts typically shown inline with text or in a dashboard. This class configures an Apex chart with the appropriate settings for a sparkline visualization.
Example
sparkline = ApexSparkline() dataset = MyDataset() dataset.data = [10, 41, 35, 51, 49, 62, 69, 91, 148] sparkline.add_dataset(dataset)
Or use subclassing to customize the sparkline further:
… code-block:: python
- class CustomSparkline(ApexSparkline):
width = 100 stroke_width = 3
- def __init__(self, **kwargs):
super().__init__(**kwargs) self.add_suboption(“chart”, “sparkline”, {“enabled”: True}) self.add_suboption(“chart”, “width”, self.width) self.add_suboption(“stroke”, “width”, self.stroke_width) self.add_dataset(self.get_dataset())
- def get_dataset(self) -> list[Any]:
# do your custom data loading here return (
Model.objects .order_by(‘datestamp’) .values_list(‘field_name’, flat=True)
)
ChartJS Charts#
- class BarChart(*args, **kwargs)[source]#
Bases:
CategoryChartA bar chart implementation using Chart.js.
This class creates a vertical bar chart where data is displayed as rectangular bars with heights proportional to their values. Bar charts are excellent for comparing quantities across different categories.
Features:
Support for multiple datasets (grouped bars)
Optional stacking of bars
Horizontal orientation option
Money formatting option
Example
from wildewidgets import BarChart chart = BarChart(title="Monthly Sales") chart.set_categories(['Jan', 'Feb', 'Mar', 'Apr', 'May']) chart.add_dataset([10000, 15000, 12000, 18000, 20000], "2022") chart.add_dataset([12000, 18000, 15000, 21000, 25000], "2023")
- get_dataset_configs() list[dict][source]#
Get the complete configuration for all datasets in the bar chart.
This method prepares all datasets with appropriate colors and options.
- get_dataset_options(index, color: tuple[int, int, int])[source]#
Get rendering options for a dataset in the bar chart.
- Parameters:
index – The index of the dataset
color – The RGB color tuple for the dataset
- Returns:
Dataset rendering options with appropriate styling
- Return type:
- class CategoryChart(*args, **kwargs)[source]#
Bases:
Widget,WidgetInitKwargsMixin,JSONDataViewBase class for Chart.js charts that display data in categories.
This abstract class provides the foundation for creating various Chart.js visualizations that organize data into categories (like bar charts, pie charts, etc.). It handles dataset management, color assignment, and rendering.
Note
This is an abstract base class. Subclasses should implement the necessary methods to create specific chart types.
Example
from wildewidgets import CategoryChart class MyBarChart(CategoryChart): def __init__(self, **kwargs): super().__init__(chart_type="bar", **kwargs) self.set_categories(['A', 'B', 'C']) self.add_dataset([10, 20, 30], "Series 1")
- add_dataset(dataset: list[float] | list[int], label: str | None = None) None[source]#
Add a dataset to the chart.
- Parameters:
dataset – List of data values corresponding to each category
label – Optional name for the dataset (shown in legend)
- get_categories() list[str][source]#
Get the category labels for the chart.
- Returns:
List of category labels
- Return type:
- Raises:
NotImplementedError – If not implemented by a subclass
- get_color_iterator() Iterator[tuple[int, int, int]][source]#
Get an iterator over the chart’s color palette.
- Returns:
Iterator over RGB color tuples
- Return type:
iterator
- get_content(**kwargs)[source]#
Render the chart as HTML content.
- Returns:
The rendered HTML for the chart
- Return type:
- get_context_data(**kwargs)[source]#
Get the context data for rendering the chart template.
- Returns:
The context data for the template
- Return type:
- get_dataset_configs() list[dict][source]#
Get the complete configuration for all datasets.
Note
This method should be implemented by subclasses.
- get_dataset_options(index, color: tuple[int, int, int])[source]#
Get rendering options for a dataset.
- Parameters:
index – The index of the dataset
color – The RGB color tuple for the dataset
- Returns:
Dataset rendering options
- Return type:
- get_datasets() list[list[float]][source]#
Get all datasets for the chart.
- Returns:
- List of datasets, each containing values for each
category
- Return type:
- Raises:
NotImplementedError – If not implemented by a subclass
- load() None[source]#
Load data into the chart.
This method should be implemented by subclasses to load data from external sources or perform calculations before rendering.
- set_categories(categories: list[str] | list[float]) None[source]#
Set the categories for the chart’s x-axis.
- Parameters:
categories – List of category labels to display on the x-axis
- set_color(color: bool) None[source]#
Enable or disable color mode.
- Parameters:
color – If True, use the color palette; if False, use grayscale
- set_colors(colors: list[tuple[int, int, int]]) None[source]#
Set a custom color palette for the chart.
- Parameters:
colors – List of RGB color tuples to use for chart elements
- set_option(name: str, value: str | float | bool | None) None[source]#
Set a chart configuration option.
- Parameters:
name – The option name
value – The option value
- COLORS: Final[list[tuple[int, int, int]]] = [(0, 59, 76), (0, 88, 80), (100, 75, 120), (123, 48, 62), (133, 152, 148), (157, 174, 136), (159, 146, 94), (242, 211, 131), (30, 152, 138), (115, 169, 80)]#
Default colors for the chart, used if no custom colors are set
- GRAYS: Final[list[tuple[int, int, int]]] = [(200, 200, 200), (229, 229, 229), (170, 169, 159), (118, 119, 123), (97, 98, 101), (175, 175, 175), (105, 107, 115)]#
Default grayscale colors for the chart, used if no custom colors are set
- class DoughnutChart(*args, **kwargs)[source]#
Bases:
CategoryChartA doughnut chart implementation using Chart.js.
This class creates a doughnut chart (a pie chart with a hole in the center) that displays data as segments of a circle. Each segment represents a proportion of the whole, making this chart ideal for showing composition.
Example
chart = DoughnutChart(title="Browser Usage") chart.set_categories(['Chrome', 'Firefox', 'Safari', 'Edge', 'Other']) chart.add_dataset([65, 15, 10, 8, 2], "Usage Share")
- class Histogram(*args, **kwargs)[source]#
Bases:
BarChartA vertical histogram chart for visualizing data distribution.
This class creates a histogram that displays the distribution of numerical data by grouping values into bins. The height of each bar represents the frequency of values within that bin.
To use this chart, call the build method with your raw data and the desired number of bins. The class will automatically: 1. Calculate appropriate bin ranges 2. Count values in each bin 3. Configure the chart with proper categories and dataset
Examples
# Create a histogram with 10 bins for a list of data points chart = Histogram(title="Distribution of Values") chart.build([23.5, 24.1, 25.3, 26.2, 27.5, 28.1, 29.3, 30.2, 31.5], 10)
- build(data: list[float], bin_count: int) None[source]#
Process raw data and configure the histogram.
This method handles all the calculations needed to convert raw data into a histogram representation: - Determines the range of the data - Calculates appropriate bin sizes and boundaries - Counts the frequency of values in each bin - Sets up the chart categories and dataset
The method uses a robust algorithm that handles both positive and negative values, and attempts to create visually appealing bin boundaries.
- Parameters:
data – List of numerical values to be plotted in the histogram
bin_count – Number of bins to divide the data into
Note
The method will set two special options on the chart: - “max”: The upper bound of the last visible bin - “histogram_max”: The absolute upper boundary of the data range
- class HorizontalBarChart(*args, **kwargs)[source]#
Bases:
BarChartA horizontal bar chart implementation using Chart.js.
This class creates a horizontal bar chart where data is displayed as rectangular bars with lengths proportional to their values. Horizontal bar charts are excellent for comparing quantities across different categories, especially when category labels are long.
Example
from wildewidgets import HorizontalBarChart chart = HorizontalBarChart(title="Population by Country") chart.set_categories( ['United States', 'Indonesia', 'Brazil', 'Russia', 'Mexico'] ) chart.add_dataset( [331000000, 273500000, 211800000, 145500000, 130000000], "Population" )
- class HorizontalHistogram(*args, **kwargs)[source]#
Bases:
HistogramA horizontal histogram chart for visualizing data distribution.
This class extends the regular Histogram to display bars horizontally instead of vertically. This can be particularly useful when: - You have many bins that would appear too narrow in a vertical histogram - You want to display long category labels that are easier to read horizontally - You want to emphasize the comparison of frequencies across bins
All the functionality of the regular Histogram is preserved, including the automatic calculation of bin ranges and frequencies.
Examples
# Create a horizontal histogram with 8 bins chart = HorizontalHistogram(title="Age Distribution") chart.build([21, 22, 24, 25, 26, 28, 29, 31, 32, 33, 35, 37, 39, 45], 8)
- class HorizontalStackedBarChart(*args, **kwargs)[source]#
Bases:
BarChartA horizontal stacked bar chart implementation using Chart.js.
This class creates a horizontal bar chart where multiple datasets are stacked on top of each other for each category. Useful for comparing parts of a whole across different categories.
The chart is configured with both horizontal orientation and stacked mode automatically during initialization.
Examples
from wildewidgets import HorizontalStackedBarChart chart = HorizontalStackedBarChart() chart.set_categories(['A', 'B', 'C']) chart.add_dataset([10, 20, 30], "Dataset 1") chart.add_dataset([5, 15, 25], "Dataset 2")
- class PieChart(*args, **kwargs)[source]#
Bases:
DoughnutChartA pie chart implementation using Chart.js.
This class creates a pie chart that displays data as segments of a circle. Each segment represents a proportion of the whole, making this chart ideal for showing composition.
It extends DoughnutChart and has the same functionality, just with a different chart type.
Example
from wildewidgets import PieChart chart = PieChart(title="Expenditure Breakdown") chart.set_categories( ['Housing', 'Food', 'Transport', 'Entertainment', 'Other'] ) chart.add_dataset([35, 25, 15, 15, 10], "Percentage")
- class StackedBarChart(*args, **kwargs)[source]#
Bases:
BarChartA stacked bar chart implementation using Chart.js.
This class creates a vertical bar chart where multiple datasets are stacked on top of each other for each category. This is useful for comparing total values across categories while also showing the composition of each total.
Example
from wildewidgets import StackedBarChart chart = StackedBarChart(title="Revenue Breakdown") chart.set_categories(['Q1', 'Q2', 'Q3', 'Q4']) chart.add_dataset([50000, 60000, 55000, 75000], "Product A") chart.add_dataset([35000, 40000, 45000, 55000], "Product B") chart.add_dataset([15000, 20000, 25000, 30000], "Product C")
- float_range(start: float, stop: float, step: float = 1.0) Generator[float, None, None][source]#
A generator function that yields a range of floating point numbers.
This function behaves like the built-in range function, but for floating point numbers. It yields numbers starting from start, up to but not including stop, incrementing by step.
Example
>>> list(float_range(0.0, 5.0, 1.0)) [0.0, 1.0, 2.0, 3.0, 4.0]
>>> list(float_range(0.0, 5.0, 0.5)) [0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0]
Note
This function does not support negative steps or reverse ranges.
- Parameters:
start – the starting value of the range.
stop – the end value of the range (exclusive).
step – the increment between each value in the range.
- Yields:
float – the next value in the range.