跳转到主要内容

一个Django应用,可以直接从模型中绘制图表和交叉表。使用HighCharts和jQuery JavaScript库在网页上渲染图表。

项目描述

Documentation Status https://travis-ci.org/chartit/django-chartit.svg?branch=master Code Health https://coveralls.io/repos/github/chartit/django-chartit/badge.svg?branch=master

Django Chartit是一个Django应用,可用于轻松从数据库中的数据创建图表。图表使用Highcharts和jQuery JavaScript库进行渲染。数据库中的数据可以绘制为简单的折线图、柱状图、面积图、散点图等多种图表类型。数据也可以绘制为交叉表,其中数据根据特定的列进行分组和/或旋转。

变更日志

  • 0.2.9 (2017年1月17日)
    • 测试期间启用pylint,但不要在失败时阻止Travis-CI。修复了#42

    • 在Python 2.7下处理饼图和散点图中的Unicode数据。PR#47

  • 0.2.8(2016年12月4日)
    • PivotChartPivotDataPool 将很快被弃用。这两个类都被标记了弃用警告。它们与 ChartDataPool 类之间有很多重复和特殊处理,这使得扩展 django-chartit 的功能集变得更加困难。下一个版本将专注于将所有功能整合到 ChartDataPool,这样用户仍然能够绘制交叉表。不过,您将需要手动构建您的交叉表!

    • DataPool 现在支持模型属性。修复了 #35。对于 PivotDataPool 不支持模型属性!警告:当使用模型属性时,chartit 不能在内部使用 ``QuerySet.values()``。这意味着结果将不会按照您提供的字段值分组。这可能会导致意外的查询结果/图表!

    • DataPool 现在支持 RawQuerySet 作为数据源。修复了 #44。对于 PivotDataPool 不支持 RawQuerySet警告:当使用 ``RawQuerySet`` 时,不要在字段名称中使用双下划线,因为这些在 chartit 内部被解释,将导致异常。例如,不要这样做 ``SELECT AVG(rating) as rating__avg``,而是写成 ``SELECT AVG(rating) as rating_avg``!

    • README 现在说明了如何执行 demoproject/

  • 0.2.7(2016年9月14日)
    • 不要使用 super(self.__class__),因为这会破坏图表类的继承。修复了 #41

  • 0.2.6(2016年8月16日)
    • chartit_tests/demoproject/ 合并

    • 加载测试数据库中的真实数据以供测试使用

    • 添加更多测试

    • 在构建文档时更新 demoproject.settings 的路径。修复了导致一些 API 文档为空的错误

    • 修复了当 QuerySet 返回空数据时 PivotChart 中的 ValueError: not enough values to unpack (expected 2, got 0)

    • 删除了对 simplejson 的依赖

    • 正确处理 Pivot 图表中的 Unicode 数据。修复了 #5

    • 更新示例项目,包含在 X 轴上渲染 DateField 值的 Chart 和 PivotChart 示例

    • 允许绘制 extra()annotate() 字段。修复了 #8#12

    • 重构 RecursiveDefaultDict 以允许将图表对象序列化到/从缓存。修复了 #10

    • 添加有关支持的第三方 JavaScript 版本的信息。修复了 #14

  • 0.2.5(2016年8月3日)
    • 解决 Python 3 与 Python 2 列表排序问题,该问题会破坏在同一轴上显示多个数据源的图表!

    • 使 demoproject/ 与 Django 1.10 兼容

  • 0.2.4(2016年8月2日)
    • 修复了 get_all_field_names()get_field_by_name() 在 Django 1.10 中删除的问题。修复了 #39

    • 针对 django.db.sql.query.Query.aggregates 删除进行更新

  • 0.2.3(2016年7月30日)
    • 为图表添加了新的 to_json() 方法。这对于在 AJAX 中创建 Highcharts 非常有用

    • 与 Grant McConnaughey 的 django-chartit2 分支合并,该分支添加了对 Python 3 和最新的 Django 1.8.x 和 1.9.x 的支持

    • 允许与 lambda 字段一起使用字典字段。关闭 #26

    • 文档改进

    • 大量代码清理和风格改进

  • 0.2.2版本作为django-chartit2(2016年1月28日)
    • 修复了另一个阻止通过PyPI安装的问题

  • 0.2.0版本作为django-chartit2(2016年1月20日)
    • 修复了可能阻止通过PyPI安装的问题

  • 0.1版本(2011年11月5日)
    • django-chartit的初始发布

功能

  • 从模型中绘制图表。

  • 在同一个图表上绘制多个模型的数据,使用同一坐标轴。

  • 从模型中绘制数据透视表。数据可以通过多列进行透视。

  • 通过多列对数据透视表进行图例透视。

  • 将多个模型的数据合并到同一个数据透视表中绘制。

  • 绘制帕累托图,以特定列为帕累托。

  • 在数据透视表中仅绘制每个类别顶部的一些项目。

  • Python 3兼容性

  • Django 1.8和1.9兼容性

  • 将文档上传到ReadTheDocs

  • 通过Travis CI进行自动化测试

  • 通过Coveralls跟踪测试覆盖率

安装

您可以从PyPI安装Django-Chartit。只需执行以下操作:

$ pip install django_chartit

然后,将chartit添加到“settings.py”中的“INSTALLED_APPS”。

您还需要支持JavaScript库。有关更多详细信息,请参阅必需的JavaScript库部分。

如何使用

在网页上绘制图表或数据透视表涉及以下步骤。

  1. 创建一个DataPoolPivotDataPool对象,该对象指定您需要检索的数据以及从哪里检索。

  2. 创建一个ChartPivotChart对象来绘制DataPoolPivotDataPool中的数据。

  3. 从django view函数将Chart/PivotChart对象返回到django模板。

  4. 使用load_charts模板标记将图表加载到具有特定ids的HTML标记中。

以上步骤的说明将通过示例进行解释。请继续阅读。

如何创建图表

以下是创建折线图的简短示例。假设我们有一个简单的模型,其中包含3个字段 - 一个用于月份,两个用于波士顿和休斯顿的温度。

class MonthlyWeatherByCity(models.Model):
    month = models.IntegerField()
    boston_temp = models.DecimalField(max_digits=5, decimal_places=1)
    houston_temp = models.DecimalField(max_digits=5, decimal_places=1)

假设我们想在x轴上绘制月份,在y轴上绘制两个城市的温度。

from chartit import DataPool, Chart

def weather_chart_view(request):
    #Step 1: Create a DataPool with the data we want to retrieve.
    weatherdata = \
        DataPool(
           series=
            [{'options': {
               'source': MonthlyWeatherByCity.objects.all()},
              'terms': [
                'month',
                'houston_temp',
                'boston_temp']}
             ])

    #Step 2: Create the Chart object
    cht = Chart(
            datasource = weatherdata,
            series_options =
              [{'options':{
                  'type': 'line',
                  'stacking': False},
                'terms':{
                  'month': [
                    'boston_temp',
                    'houston_temp']
                  }}],
            chart_options =
              {'title': {
                   'text': 'Weather Data of Boston and Houston'},
               'xAxis': {
                    'title': {
                       'text': 'Month number'}}})

    #Step 3: Send the chart object to the template.
    return render_to_response({'weatherchart': cht})

您可以使用django模板中的load_charts过滤器来渲染图表。

<head>
    <!-- code to include the highcharts and jQuery libraries goes here -->
    <!-- load_charts filter takes a comma-separated list of id's where -->
    <!-- the charts need to be rendered to                             -->
    {% load chartit %}
    {{ weatherchart|load_charts:"container" }}
</head>
<body>
    <div id='container'> Chart will be rendered here </div>
</body>

如何创建数据透视表

以下是创建数据透视表的示例。假设我们有以下模型。

class DailyWeather(models.Model):
    month = models.IntegerField()
    day = models.IntegerField()
    temperature = models.DecimalField(max_digits=5, decimal_places=1)
    rainfall = models.DecimalField(max_digits=5, decimal_places=1)
    city = models.CharField(max_length=50)
    state = models.CharField(max_length=2)

我们想绘制一个数据透视表,以月份(沿x轴)与每月最高平均降雨量(沿y轴)的顶部3个城市进行比较。

from django.db.models import Avg
from chartit import PivotDataPool, PivotChart

def rainfall_pivot_chart_view(request):
    # Step 1: Create a PivotDataPool with the data we want to retrieve.
    rainpivotdata = PivotDataPool(
        series=[{
            'options': {
                'source': DailyWeather.objects.all(),
                'categories': ['month'],
                'legend_by': 'city',
                'top_n_per_cat': 3,
            },
            'terms': {
                'avg_rain': Avg('rainfall'),
            }
        }]
    )

    # Step 2: Create the PivotChart object
    rainpivcht = PivotChart(
        datasource=rainpivotdata,
        series_options=[{
            'options': {
                'type': 'column',
                'stacking': True
            },
            'terms': ['avg_rain']
        }],
        chart_options={
            'title': {
                'text': 'Rain by Month in top 3 cities'
            },
            'xAxis': {
                'title': {
                    'text': 'Month'
                }
            }
        }
    )

    # Step 3: Send the PivotChart object to the template.
    return render_to_response({'rainpivchart': rainpivcht})

您可以使用django模板中的load_charts过滤器来渲染图表。

<head>
    <!-- code to include the highcharts and jQuery libraries goes here -->
    <!-- load_charts filter takes a comma-separated list of id's where -->
    <!-- the charts need to be rendered to                             -->
    {% load chartit %}
    {{ rainpivchart|load_charts:"container" }}
</head>
<body>
    <div id='container'> Chart will be rendered here </div>
</body>

渲染多个图表

可以在同一模板中渲染多个图表。第一个参数是load_charts的Chart对象或Chart对象列表,第二个是逗号分隔的HTML ID列表,图表将在这里渲染。

调用Django的render时,必须将所有图表作为列表传递

return render(request, 'index.html',
             {
                'chart_list' : [chart_1, chart_2],
             }
        )

然后在您的模板中,您必须使用正确的语法

<head>
    {% load chartit %}
    {{ chart_list|load_charts:"chart_1,chart_2" }}
</head>
<body>
    <div id="chart_1">First chart will be rendered here</div>
    <div id="chart_2">Second chart will be rendered here</div>
</body>

演示

上述示例只是Django-Chartit能做什么的简要尝鲜。有关更多示例和查看图表的实时效果,请查看demoproject/目录。要执行演示,请运行以下命令

cd demoproject/
PYTHONPATH=../ python ./manage.py migrate
PYTHONPATH=../ python ./manage.py runserver

文档

完整文档可在此处找到。

必需的JavaScript库

以下JavaScript库是使用Django-Chartit所必需的。

  • jQuery - 已知版本1.6.4和1.7与django-chartit配合良好。

  • Highcharts - 已知版本2.1.7和2.2.0与django-chartit配合良好。

项目详情


下载文件

下载适用于您平台的项目文件。如果您不确定选择哪一个,请了解更多关于 安装包 的信息。

源代码分发

django_chartit-0.2.9.tar.gz (27.6 kB 查看哈希值)

上传时间 源代码

构建分发

django_chartit-0.2.9-py3-none-any.whl (32.4 kB 查看哈希值)

上传时间 Python 3

支持者