Skip to content

BarChart

src.drawpyo.diagram_types.bar_chart.BarChart

A configurable bar chart built entirely from Object and Group.

This chart is mutable - you can update data, styling, and position after creation.

Source code in src/drawpyo/diagram_types/bar_chart.py
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
class BarChart:
    """A configurable bar chart built entirely from Object and Group.

    This chart is mutable - you can update data, styling, and position after creation.
    """

    # Layout constants
    DEFAULT_BAR_WIDTH = 40
    DEFAULT_BAR_SPACING = 20
    DEFAULT_MAX_BAR_HEIGHT = 200

    # Spacing constants
    TITLE_BOTTOM_MARGIN = 10
    LABEL_TOP_MARGIN = 5
    BACKGROUND_PADDING = 20

    # Axis constants
    AXIS_OFFSET = 10
    TICK_COUNT = 5
    TICK_LENGTH = 4
    TICK_LABEL_MARGIN = 4
    TICK_COLOR = "#000000"

    def __init__(self, data: dict[str, float], **kwargs):
        """
        Args:
            data (dict[str, float]): Mapping of labels to numeric values.

        Keyword Args:
            position (tuple[int, int]): Chart top-left position. Default: (0, 0)
            bar_template (Object): Optional template Object for bar styling. Default: None
            bar_width (int): Width of each bar. Default: 40
            bar_spacing (int): Space between bars. Default: 20
            max_bar_height (int): Height of the largest bar. Default: 200
            bar_colors (str | StandardColor | list[Union[str, StandardColor]]): Single color or list of colors. Default: "#66ccff"
            base_label_formatter (Callable[[str, float], str]): Custom label formatter for base (below) labels. Default: lambda l,v: l
            inside_label_formatter (Callable[[str, float], str]): Custom label formatter for inside-bar labels. Default: lambda l,v: str(v)
            title (str): Optional chart title. Default: None
            title_text_format (TextFormat): TextFormat for the title. Default: TextFormat()
            base_text_format (TextFormat): TextFormat for base labels. Default: TextFormat()
            inside_text_format (TextFormat): TextFormat for inside labels. Default: TextFormat()
            bar_fill_color (str | StandardColor): Optional fill color override for all bars. Default: None
            bar_stroke_color (str | StandardColor): Stroke color for bars. Default: "#000000"
            background_color (str | StandardColor): Optional chart background fill. Default: None
            show_axis (bool): Whether to show the axis and ticks. Default: False
            axis_tick_count (int): Number of tick intervals on the axis. Default: 5
            axis_text_format (TextFormat): TextFormat for axis tick labels. Default: TextFormat()
        """
        # Validate data
        if not isinstance(data, dict):
            raise TypeError("Data must be a dict.")
        if not data:
            raise ValueError("Data cannot be empty.")

        invalid_keys = [key for key in data if not isinstance(key, str)]
        if invalid_keys:
            raise TypeError(f"All keys must be strings. Invalid: {invalid_keys}")

        invalid_values = [
            key for key, value in data.items() if not isinstance(value, (int, float))
        ]
        if invalid_values:
            raise TypeError(f"Values must be numeric. Invalid: {invalid_values}")

        self._data: dict[str, Union[int, float]] = data.copy()

        # Position and dimensions
        self._position: Optional[tuple[int, int]] = kwargs.get("position", (0, 0))
        self._bar_width: Optional[int] = kwargs.get("bar_width", self.DEFAULT_BAR_WIDTH)
        self._bar_spacing: Optional[int] = kwargs.get(
            "bar_spacing", self.DEFAULT_BAR_SPACING
        )
        self._max_bar_height: Optional[int] = kwargs.get(
            "max_bar_height", self.DEFAULT_MAX_BAR_HEIGHT
        )

        # Text formats
        self._title_text_format: Optional[TextFormat] = deepcopy(
            kwargs.get("title_text_format", TextFormat())
        )
        self._base_text_format: Optional[TextFormat] = deepcopy(
            kwargs.get("base_text_format", TextFormat())
        )
        self._inside_text_format: Optional[TextFormat] = deepcopy(
            kwargs.get("inside_text_format", TextFormat())
        )
        self._axis_text_format: Optional[TextFormat] = deepcopy(
            kwargs.get("axis_text_format", TextFormat())
        )

        # Label formatters
        self._base_label_formatter: Optional[Callable[[str, float], str]] = kwargs.get(
            "base_label_formatter", lambda label, value: label
        )
        self._inside_label_formatter: Optional[Callable[[str, float], str]] = (
            kwargs.get("inside_label_formatter", lambda label, value: str(value))
        )

        # Title
        self._title: Optional[str] = kwargs.get("title")

        # Colors
        self._bar_fill_color: Optional[Union[str, StandardColor]] = kwargs.get(
            "bar_fill_color"
        )
        self._bar_stroke_color: Optional[Union[str, StandardColor]] = kwargs.get(
            "bar_stroke_color", "#000000"
        )
        self._background_color: Optional[Union[str, StandardColor]] = kwargs.get(
            "background_color"
        )

        # Axis settings
        self._show_axis: Optional[bool] = kwargs.get("show_axis", False)
        self._axis_tick_count: Optional[int] = kwargs.get(
            "axis_tick_count", self.TICK_COUNT
        )

        # Optional bar object template
        self._bar_template: Optional[Object] = kwargs.get("bar_template")

        # Normalize bar colors
        bar_colors: Optional[
            Union[str, StandardColor, list[Union[str, StandardColor]]]
        ] = kwargs.get("bar_colors", "#66ccff")
        self._bar_colors: list[Union[str, StandardColor]] = self._normalize_colors(
            bar_colors, len(data)
        )
        self._original_bar_colors: (
            Optional[Union[str, StandardColor]]
            | Optional[list[Union[str, StandardColor]]]
        ) = bar_colors

        # Build the chart
        self._group: Group = Group()
        self._build_chart()

    # ------------------------------------------------------------------
    # Properties
    # ------------------------------------------------------------------

    @property
    def data(self) -> dict[str, float]:
        return self._data.copy()

    @property
    def position(self) -> tuple[int, int]:
        return self._position

    @property
    def group(self) -> Group:
        return self._group

    # ------------------------------------------------------------------
    # Public methods
    # ------------------------------------------------------------------

    def update_data(self, data: dict[str, Union[float, int]]) -> None:
        # Validate data
        if not isinstance(data, dict):
            raise TypeError("Data must be a dict.")
        if not data:
            raise ValueError("Data cannot be empty.")

        invalid_keys = [key for key in data if not isinstance(key, str)]
        if invalid_keys:
            raise TypeError(f"All keys must be strings. Invalid: {invalid_keys}")

        invalid_values = [
            key for key, value in data.items() if not isinstance(value, (int, float))
        ]
        if invalid_values:
            raise TypeError(f"Values must be numeric. Invalid: {invalid_values}")

        self._data = data.copy()
        self._bar_colors = self._normalize_colors(self._original_bar_colors, len(data))
        self._rebuild()

    def update_colors(
        self, bar_colors: Union[str, StandardColor] | list[Union[str, StandardColor]]
    ) -> None:
        self._original_bar_colors = bar_colors
        self._bar_colors = self._normalize_colors(bar_colors, len(self._data))
        self._rebuild()

    def move(self, new_position: tuple[int, int]) -> None:
        if not isinstance(new_position, (tuple, list)) or len(new_position) != 2:
            raise ValueError("new_position must be a tuple of (x, y)")

        dx = new_position[0] - self._position[0]
        dy = new_position[1] - self._position[1]

        for obj in self._group.objects:
            old_x, old_y = obj.position
            obj.position = (old_x + dx, old_y + dy)

        self._position = new_position
        self._group.update_geometry()

    def add_to_page(self, page: Page) -> None:
        for obj in self._group.objects:
            page.add_object(obj)

    # ------------------------------------------------------------------
    # Private methods
    # ------------------------------------------------------------------

    def _normalize_colors(
        self,
        colors: Union[str, StandardColor, list[Union[str, StandardColor]]],
        count: int,
    ) -> list[Union[str, StandardColor]]:
        if isinstance(colors, (str, StandardColor)):
            return [colors] * count
        if not colors:
            return ["#66ccff"] * count
        if len(colors) < count:
            return colors + [colors[-1]] * (count - len(colors))
        return colors[:count]

    def _calculate_scale(self) -> float:
        values = list(self._data.values())
        max_value = max(values)
        min_value = min(values)

        if min_value < 0:
            raise ValueError("Negative values are not currently supported")
        if max_value == 0:
            return 1
        return self._max_bar_height / max_value

    def _calculate_chart_dimensions(self) -> tuple[int, int]:
        num_bars = len(self._data)
        width = num_bars * self._bar_width + (num_bars - 1) * self._bar_spacing
        height = self._max_bar_height

        # add space for base labels
        height += (self._base_text_format.fontSize or 12) + self.LABEL_TOP_MARGIN

        # add space for title
        if self._title:
            height += (
                self._title_text_format.fontSize or 16
            ) + self.TITLE_BOTTOM_MARGIN

        return width, height

    def _rebuild(self) -> None:
        self._group.objects.clear()
        self._build_chart()

    def _build_chart(self) -> None:
        x, y = self._position
        scale = self._calculate_scale()

        content_y = y
        if self._title:
            content_y += (
                self._title_text_format.fontSize or 16
            ) + self.TITLE_BOTTOM_MARGIN

        if self._background_color:
            self._add_background()
        if self._title:
            self._add_title()

        # Add ticks and axis if enabled
        if self._show_axis:
            self._add_axis_and_ticks(content_y, scale)

        for i, (key, value) in enumerate(self._data.items()):
            self._add_bar_and_label(i, key, value, content_y, scale)

        self._group.update_geometry()

    def _add_background(self) -> None:
        width, height = self._calculate_chart_dimensions()
        x, y = self._position

        bg = Object(
            value="",
            position=(x - self.BACKGROUND_PADDING, y - self.BACKGROUND_PADDING),
            width=width + 2 * self.BACKGROUND_PADDING,
            height=height + 2 * self.BACKGROUND_PADDING,
            fillColor=self._background_color,
            strokeColor=None,
        )
        self._group.add_object(bg)

    def _add_title(self) -> None:
        x, y = self._position
        chart_width, _ = self._calculate_chart_dimensions()

        title_obj = Object(
            value=self._title,
            position=(x, y),
            width=chart_width,
            height=(self._title_text_format.fontSize or 16) + 4,
            fillColor="none",
            strokeColor="none",
        )
        title_obj.text_format = deepcopy(self._title_text_format)
        title_obj.text_format.align = title_obj.text_format.align or "center"
        title_obj.text_format.verticalAlign = (
            title_obj.text_format.verticalAlign or "top"
        )
        self._group.add_object(title_obj)

    # Draw axis and tick marks
    def _add_axis_and_ticks(self, content_y: int, scale: float) -> None:
        x, _ = self._position

        axis_x = x - self._bar_spacing
        axis_y_top = content_y
        axis_y_bottom = content_y + self._max_bar_height

        axis_line = Object(
            value="",
            position=(axis_x, axis_y_top),
            width=1,
            height=self._max_bar_height,
            fillColor=None,
            strokeColor=self.TICK_COLOR,
        )
        self._group.add_object(axis_line)

        self._add_ticks(axis_x, content_y, scale)

    def _add_ticks(self, axis_x: int, content_y: int, scale: float) -> None:
        if self._axis_tick_count < 1:
            return

        max_value = max(self._data.values())
        font_size = self._axis_text_format.fontSize or 12

        for i in range(self._axis_tick_count + 1):
            t = i / self._axis_tick_count

            tick_value = max_value * (1 - t)
            tick_y = content_y + (self._max_bar_height * t)

            tick = Object(
                value="",
                position=(axis_x - self.TICK_LENGTH, tick_y),
                width=self.TICK_LENGTH,
                height=1,
                fillColor=None,
                strokeColor=self.TICK_COLOR,
            )
            self._group.add_object(tick)

            label_obj = Object(
                value=str(round(tick_value, 2)),
                position=(
                    axis_x - self.TICK_LENGTH - self.TICK_LABEL_MARGIN - 40,
                    tick_y - font_size / 2,
                ),
                width=40,
                height=font_size + 4,
                fillColor="none",
                strokeColor="none",
            )
            label_obj.text_format = deepcopy(self._axis_text_format)
            label_obj.text_format.align = "right"
            self._group.add_object(label_obj)

    def _add_bar_and_label(
        self, index: int, key: str, value: float, content_y: int, scale: float
    ) -> None:
        x, _ = self._position
        bar_height = value * scale
        color = self._bar_fill_color or self._bar_colors[index]

        bar_x = x + index * (self._bar_width + self._bar_spacing)
        bar_y = content_y + (self._max_bar_height - bar_height)
        bar_width = self._bar_width

        # Uses the template object if provided, otherwise defaults
        if self._bar_template:
            bar = Object.create_from_template_object(
                self._bar_template,
                value="",
                position=(bar_x, bar_y),
            )
            bar.width = bar_width
            bar.height = bar_height
            bar.fillColor = color
            bar.strokeColor = self._bar_stroke_color
        else:
            bar = Object(
                value="",
                position=(bar_x, bar_y),
                width=bar_width,
                height=bar_height,
                fillColor=color,
                strokeColor=self._bar_stroke_color,
            )

        self._group.add_object(bar)

        # BASE LABEL
        base_label = self._base_label_formatter(key, value)
        base_obj = Object(
            value=base_label,
            position=(bar_x, content_y + self._max_bar_height + self.LABEL_TOP_MARGIN),
            width=bar_width,
            height=(self._base_text_format.fontSize or 12) + 10,
            fillColor="none",
            strokeColor="none",
        )
        base_obj.text_format = deepcopy(self._base_text_format)
        base_obj.text_format.align = base_obj.text_format.align or "center"
        self._group.add_object(base_obj)

        # INSIDE LABEL
        inside_label = self._inside_label_formatter(key, value)
        inside_obj = Object(
            value=inside_label,
            position=(bar_x, bar_y),
            width=bar_width,
            height=bar_height,
            fillColor="none",
            strokeColor="none",
        )
        inside_obj.text_format = deepcopy(self._inside_text_format)
        inside_obj.text_format.align = inside_obj.text_format.align or "center"
        inside_obj.text_format.verticalAlign = (
            inside_obj.text_format.verticalAlign or "middle"
        )
        self._group.add_object(inside_obj)

    def __repr__(self) -> str:
        return f"BarChart(bars={len(self._data)}, position={self._position})"

    def __len__(self) -> int:
        return len(self._data)

__init__(data, **kwargs)

Parameters:

Name Type Description Default
data dict[str, float]

Mapping of labels to numeric values.

required

Other Parameters:

Name Type Description
position tuple[int, int]

Chart top-left position. Default: (0, 0)

bar_template Object

Optional template Object for bar styling. Default: None

bar_width int

Width of each bar. Default: 40

bar_spacing int

Space between bars. Default: 20

max_bar_height int

Height of the largest bar. Default: 200

bar_colors str | StandardColor | list[Union[str, StandardColor]]

Single color or list of colors. Default: "#66ccff"

base_label_formatter Callable[[str, float], str]

Custom label formatter for base (below) labels. Default: lambda l,v: l

inside_label_formatter Callable[[str, float], str]

Custom label formatter for inside-bar labels. Default: lambda l,v: str(v)

title str

Optional chart title. Default: None

title_text_format TextFormat

TextFormat for the title. Default: TextFormat()

base_text_format TextFormat

TextFormat for base labels. Default: TextFormat()

inside_text_format TextFormat

TextFormat for inside labels. Default: TextFormat()

bar_fill_color str | StandardColor

Optional fill color override for all bars. Default: None

bar_stroke_color str | StandardColor

Stroke color for bars. Default: "#000000"

background_color str | StandardColor

Optional chart background fill. Default: None

show_axis bool

Whether to show the axis and ticks. Default: False

axis_tick_count int

Number of tick intervals on the axis. Default: 5

axis_text_format TextFormat

TextFormat for axis tick labels. Default: TextFormat()

Source code in src/drawpyo/diagram_types/bar_chart.py
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
def __init__(self, data: dict[str, float], **kwargs):
    """
    Args:
        data (dict[str, float]): Mapping of labels to numeric values.

    Keyword Args:
        position (tuple[int, int]): Chart top-left position. Default: (0, 0)
        bar_template (Object): Optional template Object for bar styling. Default: None
        bar_width (int): Width of each bar. Default: 40
        bar_spacing (int): Space between bars. Default: 20
        max_bar_height (int): Height of the largest bar. Default: 200
        bar_colors (str | StandardColor | list[Union[str, StandardColor]]): Single color or list of colors. Default: "#66ccff"
        base_label_formatter (Callable[[str, float], str]): Custom label formatter for base (below) labels. Default: lambda l,v: l
        inside_label_formatter (Callable[[str, float], str]): Custom label formatter for inside-bar labels. Default: lambda l,v: str(v)
        title (str): Optional chart title. Default: None
        title_text_format (TextFormat): TextFormat for the title. Default: TextFormat()
        base_text_format (TextFormat): TextFormat for base labels. Default: TextFormat()
        inside_text_format (TextFormat): TextFormat for inside labels. Default: TextFormat()
        bar_fill_color (str | StandardColor): Optional fill color override for all bars. Default: None
        bar_stroke_color (str | StandardColor): Stroke color for bars. Default: "#000000"
        background_color (str | StandardColor): Optional chart background fill. Default: None
        show_axis (bool): Whether to show the axis and ticks. Default: False
        axis_tick_count (int): Number of tick intervals on the axis. Default: 5
        axis_text_format (TextFormat): TextFormat for axis tick labels. Default: TextFormat()
    """
    # Validate data
    if not isinstance(data, dict):
        raise TypeError("Data must be a dict.")
    if not data:
        raise ValueError("Data cannot be empty.")

    invalid_keys = [key for key in data if not isinstance(key, str)]
    if invalid_keys:
        raise TypeError(f"All keys must be strings. Invalid: {invalid_keys}")

    invalid_values = [
        key for key, value in data.items() if not isinstance(value, (int, float))
    ]
    if invalid_values:
        raise TypeError(f"Values must be numeric. Invalid: {invalid_values}")

    self._data: dict[str, Union[int, float]] = data.copy()

    # Position and dimensions
    self._position: Optional[tuple[int, int]] = kwargs.get("position", (0, 0))
    self._bar_width: Optional[int] = kwargs.get("bar_width", self.DEFAULT_BAR_WIDTH)
    self._bar_spacing: Optional[int] = kwargs.get(
        "bar_spacing", self.DEFAULT_BAR_SPACING
    )
    self._max_bar_height: Optional[int] = kwargs.get(
        "max_bar_height", self.DEFAULT_MAX_BAR_HEIGHT
    )

    # Text formats
    self._title_text_format: Optional[TextFormat] = deepcopy(
        kwargs.get("title_text_format", TextFormat())
    )
    self._base_text_format: Optional[TextFormat] = deepcopy(
        kwargs.get("base_text_format", TextFormat())
    )
    self._inside_text_format: Optional[TextFormat] = deepcopy(
        kwargs.get("inside_text_format", TextFormat())
    )
    self._axis_text_format: Optional[TextFormat] = deepcopy(
        kwargs.get("axis_text_format", TextFormat())
    )

    # Label formatters
    self._base_label_formatter: Optional[Callable[[str, float], str]] = kwargs.get(
        "base_label_formatter", lambda label, value: label
    )
    self._inside_label_formatter: Optional[Callable[[str, float], str]] = (
        kwargs.get("inside_label_formatter", lambda label, value: str(value))
    )

    # Title
    self._title: Optional[str] = kwargs.get("title")

    # Colors
    self._bar_fill_color: Optional[Union[str, StandardColor]] = kwargs.get(
        "bar_fill_color"
    )
    self._bar_stroke_color: Optional[Union[str, StandardColor]] = kwargs.get(
        "bar_stroke_color", "#000000"
    )
    self._background_color: Optional[Union[str, StandardColor]] = kwargs.get(
        "background_color"
    )

    # Axis settings
    self._show_axis: Optional[bool] = kwargs.get("show_axis", False)
    self._axis_tick_count: Optional[int] = kwargs.get(
        "axis_tick_count", self.TICK_COUNT
    )

    # Optional bar object template
    self._bar_template: Optional[Object] = kwargs.get("bar_template")

    # Normalize bar colors
    bar_colors: Optional[
        Union[str, StandardColor, list[Union[str, StandardColor]]]
    ] = kwargs.get("bar_colors", "#66ccff")
    self._bar_colors: list[Union[str, StandardColor]] = self._normalize_colors(
        bar_colors, len(data)
    )
    self._original_bar_colors: (
        Optional[Union[str, StandardColor]]
        | Optional[list[Union[str, StandardColor]]]
    ) = bar_colors

    # Build the chart
    self._group: Group = Group()
    self._build_chart()