GithubHelp home page GithubHelp logo

yasodasanjel / django-jchart Goto Github PK

View Code? Open in Web Editor NEW

This project forked from matthisk/django-jchart

0.0 1.0 0.0 112 KB

A Django package for plotting charts using the excellent Chart.JS library.

Home Page: https://django-jchart.matthisk.nl

License: BSD 3-Clause "New" or "Revised" License

Python 53.78% HTML 46.22%

django-jchart's Introduction

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',
)

(Code) Examples

The main webpage for this repository contains examples for all different chart types.

Documentation

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>

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. There is a method that should be implemented in the chart class that defines which datasets are to be plotted, this method should be called get_datasets.

To define which type of chart you want to render (e.g. a line or bar chart), your chart class should set it's 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 a ImproperlyConfigured exception.

from jchart import Chart

class LineChart(Chart):
    chart_type = 'line'

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]
        }]

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']

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 the input configuration. Lets take a look at an example, how would you configure the X-Axis so it wouldn't 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 Convenience 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>

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 }}

While 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.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>

ToDO

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

django-jchart's People

Contributors

matthisk avatar

Watchers

James Cloos avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.