All Projects → matthisk → Django Jchart

matthisk / Django Jchart

Licence: bsd-3-clause
📈 A Django package for plotting charts using the excellent Chart.JS library.

Programming Languages

python
139335 projects - #7 most used programming language

Projects that are alternatives of or similar to Django Jchart

Chartkick.py
Create beautiful Javascript charts with minimal code
Stars: ✭ 695 (+504.35%)
Mutual labels:  django, chart, charting-library, chartjs
Chart
Quick & smart charting for STDIN
Stars: ✭ 521 (+353.04%)
Mutual labels:  chart, charting-library, chartjs
React Chartjs 2
React components for Chart.js, the most popular charting library
Stars: ✭ 4,667 (+3958.26%)
Mutual labels:  chart, charting-library, chartjs
Amcharts4
The most advanced amCharts charting library for JavaScript and TypeScript apps.
Stars: ✭ 907 (+688.7%)
Mutual labels:  chart, charting-library
Chartjs Chart Financial
Chart.js module for charting financial securities
Stars: ✭ 469 (+307.83%)
Mutual labels:  chart, charting-library
Flutter echarts
A Flutter widget to use Apache ECharts (incubating) in a reactive way.
Stars: ✭ 420 (+265.22%)
Mutual labels:  chart, charting-library
Laravel Chartjs
Simple package to facilitate and automate the use of charts in Laravel 5.x using Chartjs v2 library
Stars: ✭ 404 (+251.3%)
Mutual labels:  chart, chartjs
Swiftchart
Line and area chart library for iOS
Stars: ✭ 950 (+726.09%)
Mutual labels:  chart, charting-library
Timesheet.js
JavaScript library for HTML5 & CSS3 time sheets
Stars: ✭ 6,881 (+5883.48%)
Mutual labels:  chart, charting-library
React Vis
Data Visualization Components
Stars: ✭ 8,091 (+6935.65%)
Mutual labels:  chart, charting-library
Vaadin Charts
Vaadin Charts is a feature-rich interactive graph library that answers the data visualization needs of modern web applications
Stars: ✭ 47 (-59.13%)
Mutual labels:  chart, charting-library
Vue Chartjs
📊 Vue.js wrapper for Chart.js
Stars: ✭ 4,554 (+3860%)
Mutual labels:  chart, chartjs
Aachartkit
📈📊🚀🚀🚀An elegant modern declarative data visualization chart framework for iOS, iPadOS and macOS. Extremely powerful, supports line, spline, area, areaspline, column, bar, pie, scatter, angular gauges, arearange, areasplinerange, columnrange, bubble, box plot, error bars, funnel, waterfall and polar chart types. 极其精美而又强大的跨平台数据可视化图表框架,支持柱状图、条形图、折…
Stars: ✭ 4,358 (+3689.57%)
Mutual labels:  chart, charting-library
Django Rest Pandas
📊📈 Serves up Pandas dataframes via the Django REST Framework for use in client-side (i.e. d3.js) visualizations and offline analysis (e.g. Excel)
Stars: ✭ 1,030 (+795.65%)
Mutual labels:  django, chart
Asciichart
Nice-looking lightweight console ASCII line charts ╭┈╯ for NodeJS, browsers and terminal, no dependencies
Stars: ✭ 1,107 (+862.61%)
Mutual labels:  chart, charting-library
Teechart Firemonkey Samples
Sample programs showing how to use TeeChart for FireMonkey
Stars: ✭ 21 (-81.74%)
Mutual labels:  chart, charting-library
React Jsx Highcharts
Highcharts built with proper React components
Stars: ✭ 336 (+192.17%)
Mutual labels:  chart, charting-library
Chart.qml
Chart.qml like Chart.js
Stars: ✭ 100 (-13.04%)
Mutual labels:  chart, chartjs
Go Chartjs
golang library to make https://chartjs.org/ plots (this is vanilla #golang, not gopherjs)
Stars: ✭ 42 (-63.48%)
Mutual labels:  chart, chartjs
Chartjs Chart Box And Violin Plot
Chart.js Box Plot addon
Stars: ✭ 91 (-20.87%)
Mutual labels:  chart, chartjs

django-jchart

Build Status Coverage Status PyPI version

This Django app enables you to configure and render Chart.JS charts directly from your Django codebase. Charts can than either be rendered directly into your Django template or served asynchronously to the webbrowser.

Getting Started

install django-jchart

pip install django-jchart

Add django-jchart to your installed apps.

INSTALLED_APPS = (
    '...',
    'jchart',
)

Enable template loading from app folders by adding the following property to your TEMPLATES django configuration:

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'APP_DIRS': True,
        # ...
    }]

Frontend Dependencies

For the charts to be rendered inside the browser you will need to include the Chart.JS library. Add the following HTML before your closing </body> tag:

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.4.0/Chart.bundle.min.js"></script>

If you want to make use of asynchronous loading charts you will also need to include jQuery:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

The Chart Class

At the heart of this charting library lies the Chart class. This class describes a chart and defines which data it should display. The chart's 'class fields' map to Chart.JS options which describe how the chart should render and behave. By overriding the get_datasets method on your Chart instance you can define which data should be displayed.

To define which type of chart you want to render (e.g. a line or bar chart), your chart class should set its class field chart_type to one of "line", "bar", "radar", "polarArea", "pie", or "bubble". A chart class without this field is invalid and initialization will result in an ImproperlyConfigured exception.

from jchart import Chart

class LineChart(Chart):
    chart_type = 'line'
get_datasets

The get_datasets method should return a list of datasets this chart should display. Where a dataset is a dictionary with key/value configuration pairs (see the Chart.JS documentation).

from jchart import Chart

class LineChart(Chart):
    chart_type = 'line'

    def get_datasets(self, **kwargs):
        return [{
            'label': "My Dataset",
            'data': [69, 30, 45, 60, 55]
        }]
get_labels

This method allows you to set the Chart.JS data.labels parameter. Which allows you to configure categorical axes. For an example on how to use this feature see this pie chart.

from jchart import Chart

class PieChart(Chart):
    chart_type = 'pie'

    def get_labels(self, **kwargs):
        return ['Red', 'Blue']

Configuring Charts

A chart can be configured through the following class fields:

scales layout title legend tooltips hover animation elements responsive

All of these fields map to the same key in the Chart.JS 'options' object. For instance, if you wanted to create a chart that does not render responsively you would set the responsive class field to false:

from jchart import Chart

class UnresponsiveLineChart(Chart):
    chart_type = 'line'
    responsive = False
    # ...

Most of these class fields require either a list of dicitonaries or a dictionary. With the exception of responsive which should be a boolean value. Be sure to read the Chart.JS documentation on how to use these configuration options.

For your convenience there are some methods located in jchart.config which can be used to produce correct dictionaries to configure Chart.JS properties. Most of these methods only serve as a validation step for your input configuration but some can also transform their input. Let's take a look at an example, how would you configure the X-Axis so it is not to be displayed:

from jchart import Chart
from jchart.config import Axes

class LineChart(Chart):
    chart_type = 'line'
    scales = {
        'xAxes': [Axes(display=False)],
    }

jchart.config also contains a method to create dataset configuration dictionaries. One of the advantages of using this method is that it includes a special property color which can be used to automatically set the values for: 'backgroundColor', 'pointBackgroundColor', 'borderColor', 'pointBorderColor', and 'pointStrokeColor'.

from jchart import Chart
from jchart.config import Axes

class LineChart(Chart):
    chart_type = 'line'
    
    def get_datasets(self, **kwargs):
        return [DataSet(color=(255, 255, 255), data=[])]

The jchart.config module contains methods for the properties listed below. Keep in mind that you are in no way obligated to use these methods, you could also supply Python dictionaries in the place of these method calls.

<h5>Available configuration methods:</h5>
<code>Axes</code>, <code>ScaleLabel</code>, <code>Tick</code>, <code>DataSet</code>, <code>Tooltips</code>, <code>Legend</code>, <code>LegendLabel</code>, <code>Title</code>, <code>Hover</code>, <code>InteractionModes</code>, <code>Animation</code>, <code>Element</code>, <code>ElementArc</code>, <code>ElementLine</code>, <code>ElementPoint</code>, <code>ElementRectangle</code>

Custom configuration options
There is another special class field named options this has to be set to a dictionary and can be used to set any other Chart.JS configuration values that are not configurable through a predefined class field (e.g. maintainAspectRatio). The class fields have precedence over any configuration applied through the options dictionary.
from jchart import Chart

class OptionsChart(Chart):
    chart_type = 'line'
    options = {
        'maintainAspectRatio': True
    }
    # ...

Rendering Charts

Chart instances can be passed to your Django template context. Inside the template you can invoke the method `as_html` on the chart instance to render the chart.

# LineChart is a class inheriting from jchart.Chart

def some_view(request):
    render(request, 'template.html', {
        'line_chart': LineChart(),
    })

The following code is an example of how to render this line chart inside your html template:

{{ line_chart.as_html }}

Asynchronous Charts

When rendering the chart directly into your HTML template, all the data needed for the chart is transmitted on the page's HTTP request. It is also possible to load the chart (and its required data) asynchronous.

To do this we need to setup a url endpoint from which to load the chart's data. There is a classmethod available on jchart.views.ChartView to automatically create a view which exposes the chart's configuration data as JSON on a HTTP get request:

from jchart.views import ChartView

# LineChart is a class inheriting from jchart.Chart
line_chart = LineChart()

urlpatterns = [
    url(r'^charts/line_chart/$', ChartView.from_chart(line_chart), name='line_chart'),
]

You can use a custom templatetag inside your Django template to load this chart asynchronously. The custom tag behaves like the Django url templatetag and any positional or keyword arguments supplied to it are used to resolve the url for the given url name. In this example the url does not require any url parameters to be resolved:

{% load jchart %}

{% render_chart 'line_chart' %}

This tag will be expanded into the following JS/HTML code:

<canvas class="chart" id="unique-chart-id">
</canvas>

<script type="text/javascript">
window.addEventListener("DOMContentLoaded", function() {
    $.get('/charts/line_chart/', function(configuration) {
        var ctx = document.getElementById("unique-chart-id").getContext("2d");    

        new Chart(ctx, configuration);
    });
});
</script>

Chart Parameterization

It can often be useful to reuse the same chart for different datasets. This can either be done by subclassing an existing chart class and overriding its get_datasets method. But there is another way to do this. Any arguments given to the as_html method are supplied to your get_datasets method. This makes it possible to parameterize the output of get_datasets

Let's have a look at an example. Imagine we have price point data stored in a model called Price and this model has a field called currency_type. We could render the chart for different currency types by accepting the value for this field as a parameter to get_datasets.

from jchart import Chart
from core.models import Price

class PriceChart(Chart):
    chart_type = 'line'

    def get_datasets(self, currency_type):
        prices = Price.objects.filter(currency_type=currency_type)

        data = [{'x': price.date, 'y': price.point} for price in prices]

        return [DataSet(data=data)]

If we supply an instance of this chart to the context of our template, we could use this to render two different charts. This is done by using the render_chart template tag to supply additional parameters to the get_datasets method:

{% render_chart price_chart 'euro' %}

{% render_chart price_chart 'dollar' %}

For asynchronous charts any url parameters are passed to the get_datasets method.

from jchart.views import ChartView
from .charts import PriceChart

price_chart = PriceChart()

urlpatterns = [
    url(r'^currency_chart/(?P<>\w+)/$',
        ChartView.from_chart(price_chart))
]

To render this chart asynchronously we have to supply the url parameter as a second argument to the render_chart template tag, like so:

{% load jchart %}

{% render_chart 'price_chart' 'euro' %}

{% render_chart 'price_chart' 'dollar' %}

ToDO

  • Composable datasources (instead of having to rely on inheritance)
  • Compare django-jchart to other Django chartig libraries (in the readme)

Contributing

Releasing

  • To release update the version of the package in setup.py.
  • Add release to CHANGELOG.md.
  • Run commands:
python setup.py sdist bdist_wheel --universal
twine upload dist/*
  • Add git tag to commit
Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].