|
| 1 | +--- |
| 2 | +title: Component - Chart |
| 3 | +order: 4 |
| 4 | +description: Add bar and line charts to Django with Unfold’s customizable Chart.js component and built-in design integration. |
| 5 | +--- |
| 6 | + |
| 7 | +# Chart component |
| 8 | + |
| 9 | +Unfold provides built-in components for easily rendering bar and line charts. Simply pass a properly structured data object to the chart component and it will be displayed automatically. Chart rendering is handled by Chart.js with default configurations that match the Unfold design system. Basic settings can be adjusted without modifying code. For advanced customization, use the `options` parameter to provide your own Chart.js options (except for JavaScript functions, which are not supported). |
| 10 | + |
| 11 | +## Special options |
| 12 | + |
| 13 | +- To configure the maximum number of ticks on the X-axis, add the `maxTicksXLimit` property to the dataset. |
| 14 | +- By default, Y-axis labels are hidden. To display them, add the `displayYAxis` property to the dataset. |
| 15 | +- To show a suffix on Y-axis values, add the `suffixYAxis` property to the dataset. |
| 16 | + |
| 17 | +```python |
| 18 | +# admin.py |
| 19 | + |
| 20 | +from unfold.components import BaseComponent |
| 21 | + |
| 22 | + |
| 23 | +@register_component |
| 24 | +class BarChartComponent(BaseComponent): |
| 25 | + def get_context_data(self, **kwargs): |
| 26 | + context = super().get_context_data(**kwargs) |
| 27 | + context.update({ |
| 28 | + "height": 320, |
| 29 | + "data": json.dumps({ |
| 30 | + "labels": ["Mo", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"], |
| 31 | + "datasets": [ |
| 32 | + { |
| 33 | + "label": "Dataset 1", |
| 34 | + "data": [12, 19, 3, 5, 2, 3, 9], |
| 35 | + "backgroundColor": "var(--color-primary-700)", |
| 36 | + }, |
| 37 | + { |
| 38 | + "label": "Dataset 2", |
| 39 | + "data": [3, 12, 5, 9, 2, 19, 3], |
| 40 | + "borderColor": "var(--color-primary-400)", |
| 41 | + "type": "line", # Change the type here |
| 42 | + # "displayYAxis": True, # Display the Y-axis labels |
| 43 | + # "maxTicksXLimit": 50, # Limit the number of ticks on X-axis |
| 44 | + # "suffixYAxis": "€", # Add a suffix to the Y-axis values |
| 45 | + } |
| 46 | + ] |
| 47 | + }) |
| 48 | + # Completely custom chart options |
| 49 | + # "options": json.dumps({ |
| 50 | + # "sample": "example", |
| 51 | + # }) |
| 52 | + }) |
| 53 | + |
| 54 | + return context |
| 55 | +``` |
| 56 | + |
| 57 | +```html |
| 58 | +{% load unfold %} |
| 59 | + |
| 60 | +{% component "unfold/components/card.html" with title="Chart title" %} |
| 61 | + {% component "unfold/components/chart/bar.html" with component_class="BarChartComponent" %}{% endcomponent %} |
| 62 | +{% endcomponent %} |
| 63 | +``` |
0 commit comments