Giter Site home page Giter Site logo

agiliq / django-graphos Goto Github PK

View Code? Open in Web Editor NEW
443.0 443.0 98.0 1.31 MB

Django charting made *really* easy.

Home Page: http://agiliq.com/demo/graphos

License: BSD 2-Clause "Simplified" License

Python 24.85% HTML 9.20% CSS 6.63% JavaScript 59.32%

django-graphos's Introduction

Graphos

Build Status

Graphos is a Django app to normalize data to create beautiful charts. It provides a JS agnostic way to work with charts and allows seamless and quick switching between different chart providers.

Supported Backends:

  • Python Nested lists
  • Django ORM
  • CSV Files
  • MongoDB

Charting API Supported

Chart types supported

Flot

  • Line chart
  • Bar Chart
  • Column chart
  • Pie chart
  • Point Chart

Google Charts

  • Line chart
  • Bar chart
  • Column chart
  • Pie chart
  • Area chart
  • Candlestick chart
  • Treemap chart
  • Gauge chart

YUI

  • Line chart
  • Bar chart
  • Column chart
  • Pie chart
  • Area chart
  • Spline chart
  • Areaspline chart

Morris.js

  • Line chart
  • Bar chart
  • Donut chart
  • Area chart

Highcharts

(You will need to buy a license if you use highcharts for commerical use)

  • Line Chart
  • Bar Chart
  • Column Chart
  • Pie Chart
  • Area Chart

C3.js

  • Line chart
  • Column chart (You need to rotate the axis of bar chart to render column chart)
  • Bar chart
  • Donut chart
  • Pie chart
  • Spline chart

Matplotlib

  • LineChart
  • BarChart

With Graphos, switching from google's LineChart to yui LineChart can be done within minutes. So would be the case in switching from yui AreaChart to morris AreaChart.

Running demo project locally

  • Clone the project

    git clone https://github.com/agiliq/django-graphos.git

  • Cd to demo directory

    cd django-graphos/demo_project/

  • Create local settings.

    cp demo_project/settings/local.py-dist demo_project/settings/local.py

  • Install requirements

    pip install -r requirements.txt

  • Run migrate

    python manage.py migrate

  • Run server

    python manage.py runserver

The installed demo app shows the various suported chart types.

In case you want to use mongo data while charting, you must have mongodb properly setup and pymongo installed. Make sure mongo server is running.

mongod --dbpath ~/data/db

Mongo setup is optional and is not needed to get running with demo project.

Overview of Plot generation

Generating a plot requires two things. A DataSource object and a Chart object.

In your view, you do something like this:

from graphos.sources.simple import SimpleDataSource
from graphos.renderers.gchart import LineChart

data =  [
        ['Year', 'Sales', 'Expenses'],
        [2004, 1000, 400],
        [2005, 1170, 460],
        [2006, 660, 1120],
        [2007, 1030, 540]
    ]
# DataSource object
data_source = SimpleDataSource(data=data)
# Chart object
chart = LineChart(data_source)
context = {'chart': chart}
return render(request, 'yourtemplate.html', context)

And then in the template:

{{ chart.as_html }}

In this example we are planning to use Google chart, as is evident from the import statement in the view, we import gchart.LineChart. So we must also include the google chart javascript in our template.

<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
    google.load("visualization", "1", {packages:["corechart"]});
</script>

So the template would look like

<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
    google.load("visualization", "1", {packages:["corechart"]});
</script>

{{ chart.as_html }}

If we want to use yui LineChart instead of google LineChart, our view would have:

from graphos.renderers.yui import LineChart
chart = LineChart(data_source)

And our template would inclue yui javascript and it would look like:

<script src="http://yui.yahooapis.com/3.10.0/build/yui/yui-min.js"></script>
{{ chart.as_html }}

See, how easy it was to switch from gchart to yui. You did not have to write or change a single line of javascript to switch from gchart to yui. All that was taken care of by as_html() of the chart object.

DataSources

SimpleDataSource

This should be used if you want to generate a chart from Python list.

from graphos.sources.simple import SimpleDataSource
data = SimpleDataSource(data=data)

Data could be:

data = [
       ['Year', 'Sales', 'Expenses', 'Items Sold', 'Net Profit'],
       ['2004', 1000, 400, 100, 600],
       ['2005', 1170, 460, 120, 710],
       ['2006', 660, 1120, 50, -460],
       ['2007', 1030, 540, 100, 490],
       ]

or it could be

data = [
       ['Year', 'Sales', 'Expenses'],
       ['2004', 1000, 400],
       ['2005', 1170, 460],
       ['2006', 660, 1120],
       ['2007', 1030, 540],
       ]

or it could be

data = [
       ['Year', 'Sales', 'Expenses'],
       ['2004', 1000, 400],
       ['2005', 1170, 460],
       ]

You got the idea.

data has to be a list of lists. First row of data tells the headers. First element of each list elementis the x axis.

This data essentially tells that in year 2004, sales was 1000 units and expense was 400 units. And in year 2005, sales was 1170 units and expense was 460 units.

ModelDataSource

This should be used if you want to generate a chart from a Django queryset.

from graphos.sources.model import ModelDataSource
queryset = Account.objects.all()
data_source = ModelDataSource(queryset,
							  fields=['year', 'sales'])

This assumes that there is a Django model called Account which has fields year and sales. And you plan to plot year on x axis and sales on y axis.

Or you could say

data_source = ModelDataSource(queryset,
							  fields=['year', 'sales', 'expenses'])

This would plot the yearly sale and yearly expense

CSVDataSource

This should be used if you want to generate a chart from a CSV file.

from graphos.sources.csv_file import CSVDataSource
csv_file = open("hello.csv")
data_source = CSVDataSource(csv_file)

MongoDataSource

TODO

Charts

We have following charts

  • Gchart

    • gchart.LineChart
    • gchart.BarChart
    • gchart.ColumnChart
    • gchart.PieChart
    • gchart.AreaChart
    • gchart.TreeMapChart
    • gchart.CandlestickChart
    • gchart.GaugeChart
  • Yui

    • yui.LineChart
    • yui.BarChart
    • yui.ColumnChart
    • yui.PieChart
    • yui.AreaChart
    • yui.SplineChart
    • yui.AreaSplineChart
  • Flot

    • flot.LineChart
    • flot.BarChart
    • flot.ColumnChart
    • flot.PieChart
    • flot.PointChart
  • Morris

    • morris.LineChart
    • morris.BarChart
    • morris.AreaChart
    • morris.DonutChart
  • Highcharts

    • highcharts.LineChart
    • highcharts.BarChart
    • highcharts.ColumnChart
    • highcharts.PieChart
    • highcharts.AreaChart

Most of the chart providers support LineChart, BarChart, ColumnChart and PieChart, and it is very easy to switch from specific chart type of one provider to other. eg: It is super quick to switch from gchart LineChart to flot LineChart.

More Examples

Using SimpleDataSource with gchart LineChart

View
data =  [
        ['Year', 'Sales', 'Expenses'],
        [2004, 1000, 400],
        [2005, 1170, 460],
        [2006, 660, 1120],
        [2007, 1030, 540]
    ]
from graphos.sources.simple import SimpleDataSource
from graphos.renderers.gchart import LineChart
chart = LineChart(SimpleDataSource(data=data))
Template
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
    google.load("visualization", "1", {packages:["corechart"]});
</script>

{{ chart.as_html }}

Using SimpleDataSource with yui LineChart

View
data =  [
        ['Year', 'Sales', 'Expenses'],
        [2004, 1000, 400],
        [2005, 1170, 460],
        [2006, 660, 1120],
        [2007, 1030, 540]
    ]
from graphos.sources.simple import SimpleDataSource
from graphos.renderers.yui import LineChart
chart = LineChart(SimpleDataSource(data=data))
Template
<script src="http://yui.yahooapis.com/3.10.0/build/yui/yui-min.js"></script>
{{ chart.as_html }}

Using SimpleDataSource with yui BarChart

View
data =  [
        ['Year', 'Sales', 'Expenses'],
        [2004, 1000, 400],
        [2005, 1170, 460],
        [2006, 660, 1120],
        [2007, 1030, 540]
    ]
from graphos.sources.simple import SimpleDataSource
from graphos.renderers.yui import BarChart
chart = BarChart(SimpleDataSource(data=data))
Template
<script src="http://yui.yahooapis.com/3.10.0/build/yui/yui-min.js"></script>
{{ chart.as_html }}

Using SimpleDataSource with gchart BarChart

View
data =  [
        ['Year', 'Sales', 'Expenses'],
        [2004, 1000, 400],
        [2005, 1170, 460],
        [2006, 660, 1120],
        [2007, 1030, 540]
    ]
from graphos.sources.simple import SimpleDataSource
from graphos.renderers.gchart import BarChart
chart = BarChart(SimpleDataSource(data=data))
Template
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
    google.load("visualization", "1", {packages:["corechart"]});
</script>
{{ chart.as_html }}

Options

Your rendered chart is contained in a div.

Setting id of chart containing div

You might want to do additional jquery or javascript operations with your chart containing div. In such case you might want to set an id on the div. You can do this while instantiating the chart element.

chart = gchart.LineChart(html_id='gchart_div')

Setting width and height of chart containing div

You can control the width and height of chart containing div while instantiating the chart element.

chart = gchart.LineChart(simple_data_source, height=100, width=100)

Chart specific options

Different chart providers give different options to customise the chart.

Google chart api allows setting title for the rendered chart, see Gchart documentation, using title attribute. You can accomplish this by adding a keyword argument called options while instantiating the chart element.

chart = gchart.LineChart(simple_data_source, height=100, width=100, options={'title': 'Sales growth'})

Google pie chart allows making the chart as 3 dimensional. You can accomplish this by using keyword argument options.

pie_chart = gchart.PieChart(simple_data_source, options={'is3D': True})

Morris.js allows options like lineWidth, smooth etc. You can find more here. You can accomplish this by using options.

chart = morris.LineChart(simple_data_source, options={'lineWidth': 50, 'smooth': False})

Installation

pip install django-graphos

Compatibility

Graphos is compatible with Python 2.7 and Python 3.3+

available on pypi

Handling non serializable fields

You need to override get_data() of existing DataSource and convert datetime field into something which could be serialized.

Assuming you are using a Python list as data, then you need to do:

from graphos.sources.simple import SimpleDataSource
class MySimpleDataSource(SimpleDataSource):
	def get_data(self):
		data = super(MySimpleDataSource, self).get_data()
		header = data[0]
		data_without_header = data[1:]
		for row in data_without_header:
			# Assuming first column contains datetime
			row[0] = row[0].year
		data_without_header.insert(0, header)
		return data_without_header

And data has

d1 = datetime(2015, 7, 8, 1, 1)
d2 = datetime(2016, 7, 8, 3, 1)

data1 = [
         ['Year', 'Sales', 'Expenses', 'Items Sold', 'Net Profit'],
         [d1, 1000, 400, 100, 600],
         [d2, 1170, 460, 120, 310],
 ]

chart = flot.LineChart(MySimpleDataSource(data=data1))

If you are planning to use queryset with ModelDataSource, then you would create following class

from graphos.sources.model import ModelDataSource
class MyModelDataSource(ModelDataSource):
    def get_data(self):
        data = super(MyModelDataSource, self).get_data()
        header = data[0]
        data_without_header = data[1:]
        for row in data_without_header:
            # Assuming second column contains datetime
            row[1] = row[1].year
		data_without_header.insert(0, header)
		return data_without_header

And you would use this class like:

queryset = Account.objects.all()
chart = flot.LineChart(MyModelDataSource(queryset=queryset, fields=['sales', 'datetime_field','expenses']))

Creating new DataSource

A DataSource is a class which has these three methods.

get_data
get_header
get_first_column

get_header is used by a Renderer to create the labels. get_first_column is used to set the x axis labels get_data is used to get the data for display. It should always return a nested list. Eg:

[
    ['Year', 'Sales', 'Expenses'],
    [2004, 1000, 400],
    [2005, 1170, 460],
    [2006, 660, 1120],
    [2007, 1030, 540]
]

If you create a class extending SimpleDataSource, and implement get_data. You get get_header and get_first_column for free.

Creating new Renderer

A renderer is a class which takes a DataSource and can convert it to the html to display.

The only required method on a Renderer is as_html. This will convert the data to a format which can display the chart.

Generally you will convert the data to json and pass it to the template which you return.

License

BSD

django-graphos's People

Contributors

akshar-raaj avatar anentropic avatar arjunchitturi avatar ashiksujath2 avatar atmb4u avatar balu-varanasi avatar gpichot avatar iansprice avatar ishail avatar krvc avatar kyogesh avatar luzfcb avatar mahmoudhossam avatar manjunath24 avatar nanuxbe avatar rameshugar avatar shabda avatar sheepeatingtaz avatar tuxcanfly avatar yashrastogi16 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

django-graphos's Issues

Separate html and script from template

Hi,

It might be useful to have {{ chart.as_html }} and {{ chart.as_script }} or something similar in order to collect all scripts at the end of the page. The first method would make the divs will be rendered and the second will show the script.
When we load jquery at botton of the page, we got ReferenceError for $ function, because the script function appears before than the chart js library was loaded.

Thanks for consider this option!

ImportError: No module named local

I try to run this same demo project with my local machine i install the packages which you mention in the requirements.txt but its showing in this errror , i dont know why this happen , if this issue simple means please let me know.

Add more yui charts

You need to follow the pattern shown in PR #60

Combo, combospline and markerseries are missing. You will need to add them to yui.py. Check if the current data format we have works with these chart types else you will need to override get_data().

Add these three to demo page for yui.

zip object is not JSON serializable when generating graph

By following the tutorial, I have the following set up

# view 
def salesboard(request):
    # render the graph here
    data =  [
            ['Year', 'Sales', 'Expenses'],
            [2004, 1000, 400],
            [2005, 1170, 460],
            [2006, 660, 1120],
            [2007, 1030, 540]
        ]
    chart = flot.LineChart(SimpleDataSource(data=data), html_id="Line Chart")
    return render_to_response('scoreboard.html', {'chart':chart})

Template
{{ chart.as_html }}

Error

Error during template rendering

In template C:\Users\TIMLEU~1\Desktop\SYSTEM~1\sp-venv\lib\site-packages\graphos\templates\graphos\flot.html, error at line 4
<zip object at 0x00000052AAC8D448> is not JSON serializable
1   <div id="{{ chart.html_id }}" style="width:{{ chart.width }}px;height:{{ chart.height }}px;"></div>
2   <script type="text/javascript">
3   $(function () {
4       data{{ chart.html_id }} = {{ chart.get_series_objects_json|safe }}
5       $plot{{ chart.html_id }} = $.plot(
6           $("#{{ chart.html_id }}"),
7           data{{ chart.html_id }},
8           {{ chart.get_options_json|safe }}
9       );
10  });
11  </script>

Is there a way to plot multiple datasets to a single graph?

Firstly, loving the simplicity of Graphos.
I do have a question however; Is there a way to plot multiple datasets to a single graph, and if not are there any plans to introduce this feature?

i.e.

queryset1 = model.objects.filter(salesman='adam')
queryset2 = model.objects.filter(salesman='bob')
data_source = [ModelDataSource(queryset1, fields=['monthly_sales']),
                        ModelDataSource(queryset2, fields=['monthly_sales'])]

I cant find any reference in the documentation

what is chart.as_html?

def show_employee(request):
emp = Employee.objects.raw('select id,job_title, count(job_title) as count_job_title from employee group by job_title order by count(job_title) desc,job_title desc limit 5')
data_source = ModelDataSource(emp, fields=['job_title', 'count_job_title'],)
line_chart = morris.LineChart(data_source)
return render(request,'blog/show_employee.html',{'line_chart':line_chart})

{% extends 'blog/base.html' %}

{% block content %}


{{ line_chart.as_html }}

{% endblock %}

This does not show anything in graph??

Display chart inside javascript

So from javascript I make an ajax call to a url thay is handled by a view function that return a google linechart object. How to display the chart from inside the callback function in the javascript? Whay should the view function return ?Httpresponse with the chart? Or how this can be done???

Another good library to charts in SGV

Sorry, I have not found a better place to talk about it.
I found this library, so I decided to share.

http://pygal.org
http://pygal.org/documentation/
http://pygal.org/chart_types/
try online: http://cabaret.pygal.org/

pygal provides 10 kinds of charts:

  • Line charts:
    • Basic
    • Stacked
  • Bar charts / Histograms
    • Basic
    • Stacked
    • Horizontal
  • XY charts
    • Basic
    • Scatter Plot
    • DateY
  • Pies
    • Basic
    • Multi-series pie
  • Radar charts
    • Basic
  • Box plot
    • Basic
  • Dot charts
    • Basic
  • Funnel charts
    • Basic
  • Gauge charts
    • Basic
  • Pyramid charts
    • Basic
  • Worldmap charts
    • Basic
  • Country charts
    • French map

pygal provides 14 built-in styles
pygal provides 5 parametric styles:
pygal provides 2 ways to customize styles: Using Style python class or using a custom css

Add more gchart charts in ui

All chart types supported by gchart should be shown at http://localhost:8000/gchart/. Two things need to be done here:

  1. Candlestick chart isn't shown in html even though it's passed from the context. See why candlestick chart isn't shown.
  2. gchart supports AreaChart but AreaChart isn't shown in html. Show AreaChart in gchart demo.

highchart tooltip useHTML does not work

BarChart:

        options={
        'tooltip': {
            'shared': True,
            'useHTML': True,
            'headerFormat': '<span style="font-size:10px">{point.key}</span><table>',
            'pointFormat': '<tr><td style="color:{series.color};padding:0">{series.name}: </td>'
                           '<td style="padding:0"><b>{point.y:.1f} mm</b></td></tr>',
            'footerFormat': '</table>'
        },
    }

useHTML attribute does not work in html page. I saw '<' is escaped.
After I remove 'cls=JSONEncoderForHTML' params from highcharts.py line:179 , it works.

Add documentation on how to handle non serializable fields

datetime.datetime() is non JSON serializable. So json data for this can't be passed to graphos renderers. See #35 for detail.

The workaround for this is to write a subclass which inherits from SimpleDataSource or ModelDataSource and override get_data(). The workaround is already mentioned in a comment of #35. This workaround should be added in README.md.

What about scatter plots

I'm impressed with the scope of chart types that are available, but I'm surprised to not find that scatter plots are among them...

Am I missing something? If not, is this something that will be added anytime soon?

Issue with pip

Hi, I have this error with pip 1.4.1:

$ pip install django-graphos
Downloading/unpacking django-graphos
Could not find a version that satisfies the requirement django-graphos (from versions: 0.0.1a0, 0.0.2a0)
Cleaning up...
No distributions matching the version for django-graphos

Getting blank chart when trying to use ModelDataSource

I'm getting a blank chart when I'm trying to pull data from a Django model. Here is the relevant code:

views.py:

    queryset = HisCorOsCompliance.objects.filter(facility='ALL')
    data_source = ModelDataSource(queryset, fields=['server_compliance', 'date'],)                          
    chart = morris.LineChart(data_source)      
    context = {'chart':chart}  

    return render(request, 'portal/index.html',  context)

html:

        {% if chart %}
        {{ chart.as_html }}
        {% endif %}

I'm getting a large, blank chart as a result. I can verify that the query is working correctly. if I do a "print data" within the get_field_values function within model.py, the console prints all of the values that I'm trying to display.

I've been able to get a chart working by using the SimpleDataSource. I'm sure there's something really basic that I'm overlooking, but I'm having a really hard time figuring it out. Any help is appreciated!

Chart does not load when table update instead of page refresh

I realize that when i use {{chart.as_html}} it works fine on page refresh or when the page is loaded for the first time. But when i do a table update whereby i only update the table with ajax where the chart is with new data instead of page refresh, the graph is not drawn and its just blank.

Anyway to work around this or is it a bug? I cant seem to find any solution for this. Any help is highly appreciated.

Thanks

pip install django-graphos fails with TypeError

I'm working on a heroku/django build that I'm testing in a virtualenv, which I would like to use django-graphos for. I ran pip install from the venv and had it fail on me. After posting the following error on StackOverflow, I got a comment pointing out that the print statement referenced below is not valid python 3 code. The error is as follows:

(venv) $ > pip install django-graphos
Collecting django-graphos
  Using cached django-graphos-0.1.1.tar.gz
    Complete output from command python setup.py egg_info:
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/private/var/folders/qt/s4gp855d38s6rrj34fdlmwk40000gn/T/pip-build-q69jbvga/django-graphos/setup.py", line 132, in <module>
        package_data=find_package_data("graphos", only_in_packages=False),
      File "/private/var/folders/qt/s4gp855d38s6rrj34fdlmwk40000gn/T/pip-build-q69jbvga/django-graphos/setup.py", line 106, in find_package_data
        print >> sys.stderr, (
    TypeError: unsupported operand type(s) for >>: 'builtin_function_or_method' and '_io.TextIOWrapper'
----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in /private/var/folders/qt/s4gp855d38s6rrj34fdlmwk40000gn/T/pip-build-10_yhb6j/django-graphos/

And subsequently it was pointed out that the error was fixed but not merged to master in September of 2015. After cloning to my own repo (https://github.com/iannesbitt/django-graphos), editing settings.py to include python-3-friendly print() calls, and pulling the branch started by user @nanuxbe to master, I was able to install successfully using pip install git+https://github.com/iannesbitt/django-graphos.git. Of course shortly after that, I discovered that there was a working python-graphos-3 available through pip, which essentially made my clone and pull meaningless, but hey, it works.

Make requirements more lean

I want to test this out -- tried running and it looks like this requires mongodb? Can the redis and mongo requirements be made optional?

AttributeError: 'module' object has no attribute 'Connection'

pymongo.Connection is not support , please fix it. thx
django-graphos-master/demo_project/demo/utils.py
1 import pymongo
2 from pymongo import MongoClient
3 from .models import Account
4
5
6 DB_HOST = ["localhost"]
7 DB_PORT = 27017
8
9
10 def get_db(db_name):
11 DB_HOST = ["localhost"]
12 DB_PORT = 27017
13 #db = pymongo.Connection(DB_HOST, DB_PORT)[db_name]
14 db = MongoClient(DB_HOST, DB_PORT)[db_name]
15 return db
16
17
18 def get_mongo_cursor(db_name, collection_name, max_docs=100):
19 #db = pymongo.Connection(host=DB_HOST,
20 db = MongoClient(host=DB_HOST,
21 port=DB_PORT)[db_name]
22 collection = db[collection_name]
23 cursor = collection.find()
24 if cursor.count >= max_docs:
25 cursor = cursor[0:max_docs]
26 return cursor

Documentation Error

In the tutorial a wrong import statement is used.

Found in the ModelDataSource section

from graphos.sources.models import ModelDataSource
should in fact be
from graphos.sources.model import ModelDataSource

Passing chart options to Highcharts.js?

Hello. Firstly, thanks for graphos - it's been helpful.

I'm trying to pass chart options to Highcharts.js but they don't seem to be passing through to the initializing JavaScript. Here is some sample code:

from graphos.sources.simple import SimpleDataSource
from graphos.renderers.highcharts import BarChart

def view(request):
    data = [ ... ]
    data_source = SimpleDataSource(data=data)

    chart = BarChart(data_source, options={'title': 'My Chart', 'legend': {'enabled' : False}})

I'm trying to set turn the legend off as per Highchart docs, but no luck. Any suggestions?

Morris Donut not supporting colors option?

I'm trying to get the donut to respond to colors via the code below without success:

class ThresholdFactorsView(BaseAthleteView):
template_name = 'factors.html'

def get_context_data(self, **kwargs):
    context = super(ThresholdFactorsView, self).get_context_data(**kwargs)
    factors_list = self.client.get_threshold_factors()
    chart_data, chart_colors = self.build_feature_data(factors_list)
    threshold_data_source = SimpleDataSource(data=chart_data)
    threshold_factors_chart = DonutChart(data_source=threshold_data_source, options={'colors': chart_colors})
    context['factors_chart'] = threshold_factors_chart
    context['slug'] = 'factors'
    return context

def build_feature_data(self, factors_list):
    colors = []
    rval = [['label','value']]
    for row in factors_list:
        feature = row['feature']
        coef = row['coef']
        color = "#008000"
        if coef < 0:
            color = "#FF0000"
        rval.append([feature, abs(coef)])
        colors.append(color)
    return rval, colors

I have a fix for it if you'd like me to send it along...

Issue with GoogleCharts and counting unique values

Hi,

It seems that you don't handle the dictionaries properly in your code, check this simple code:

    isps = Ip.objects.all().values('isp').annotate(the_count=Count('isp'))
    data_source = ModelDataSource(isps, fields=['isp', 'the_count'])
    chart = BarChart(data_source, options={'title': "ISP Count"})

The error I get is:

Traceback (most recent call last):
  File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/exception.py", line 41, in inner
    response = get_response(request)
  File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py", line 187, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py", line 185, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/xxx/xxx/xxx/views.py", line 75, in stats
    data_source = ModelDataSource(isps, fields=['isp', 'the_count'])
  File "/usr/local/lib/python3.5/dist-packages/graphos/sources/model.py", line 36, in __init__
    self.data = self.create_data()
  File "/usr/local/lib/python3.5/dist-packages/graphos/sources/model.py", line 41, in create_data
    data.append(get_field_values(row, self.fields))
  File "/usr/local/lib/python3.5/dist-packages/graphos/sources/model.py", line 8, in get_field_values
    value = getattr(row, field)
AttributeError: 'dict' object has no attribute 'isp'

Bug in documentation

In the chapter "Overview of Plot generation" you should mention to add 'graphos' to the INSTALLED_APPS in settings.py

datetime.date is not JSON serializable

Trying to create a graph using a date on one of the axis generates a TypeError, as the date object is not serializable in JSON.

Full traceback:

Template error:
In template /usr/local/lib/python2.7/dist-packages/graphos/templates/graphos/flot.html, error at line 6
   datetime.date(2015, 1, 13) is not JSON serializable
   1 : <div id="{{ chart.html_id }}" style="width:{{ chart.width }}px;height:{{ chart.height }}px;"></div>
   2 : <script type="text/javascript">
   3 : $(function () {
   4 :  $.plot(
   5 :          $("#{{ chart.html_id }}"), 
   6 :           {{ chart.get_series_objects_json|safe }} , 
   7 :          {{ chart.get_options_json|safe }}
   8 :      );
   9 : });
   10 : </script>

Traceback:
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response
  111.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/var/www/myDjangoProject/views.py" in viewDailyList
  22.         return render(request, 'myTemplates/viewDailyList.html', {'DataChart':chart,})
File "/usr/local/lib/python2.7/dist-packages/django/shortcuts.py" in render
  48.     return HttpResponse(loader.render_to_string(*args, **kwargs),
File "/usr/local/lib/python2.7/dist-packages/django/template/loader.py" in render_to_string
  178.         return t.render(context_instance)
File "/usr/local/lib/python2.7/dist-packages/django/template/base.py" in render
  148.             return self._render(context)
File "/usr/local/lib/python2.7/dist-packages/django/test/utils.py" in instrumented_test_render
  88.     return self.nodelist.render(context)
File "/usr/local/lib/python2.7/dist-packages/django/template/base.py" in render
  844.                 bit = self.render_node(node, context)
File "/usr/local/lib/python2.7/dist-packages/django/template/debug.py" in render_node
  80.             return node.render(context)
File "/usr/local/lib/python2.7/dist-packages/django/template/loader_tags.py" in render
  126.         return compiled_parent._render(context)
File "/usr/local/lib/python2.7/dist-packages/django/test/utils.py" in instrumented_test_render
  88.     return self.nodelist.render(context)
File "/usr/local/lib/python2.7/dist-packages/django/template/base.py" in render
  844.                 bit = self.render_node(node, context)
File "/usr/local/lib/python2.7/dist-packages/django/template/debug.py" in render_node
  80.             return node.render(context)
File "/usr/local/lib/python2.7/dist-packages/django/template/loader_tags.py" in render
  65.                 result = block.nodelist.render(context)
File "/usr/local/lib/python2.7/dist-packages/django/template/base.py" in render
  844.                 bit = self.render_node(node, context)
File "/usr/local/lib/python2.7/dist-packages/django/template/debug.py" in render_node
  80.             return node.render(context)
File "/usr/local/lib/python2.7/dist-packages/django/template/debug.py" in render
  90.             output = self.filter_expression.resolve(context)
File "/usr/local/lib/python2.7/dist-packages/django/template/base.py" in resolve
  596.                 obj = self.var.resolve(context)
File "/usr/local/lib/python2.7/dist-packages/django/template/base.py" in resolve
  734.             value = self._resolve_lookup(context)
File "/usr/local/lib/python2.7/dist-packages/django/template/base.py" in _resolve_lookup
  788.                             current = current()
File "/usr/local/lib/python2.7/dist-packages/graphos/renderers/base.py" in as_html
  43.         return render_to_string(self.get_template(), context)
File "/usr/local/lib/python2.7/dist-packages/django/template/loader.py" in render_to_string
  172.         return t.render(Context(dictionary))
File "/usr/local/lib/python2.7/dist-packages/django/template/base.py" in render
  148.             return self._render(context)
File "/usr/local/lib/python2.7/dist-packages/django/test/utils.py" in instrumented_test_render
  88.     return self.nodelist.render(context)
File "/usr/local/lib/python2.7/dist-packages/django/template/base.py" in render
  844.                 bit = self.render_node(node, context)
File "/usr/local/lib/python2.7/dist-packages/django/template/debug.py" in render_node
  80.             return node.render(context)
File "/usr/local/lib/python2.7/dist-packages/django/template/debug.py" in render
  90.             output = self.filter_expression.resolve(context)
File "/usr/local/lib/python2.7/dist-packages/django/template/base.py" in resolve
  596.                 obj = self.var.resolve(context)
File "/usr/local/lib/python2.7/dist-packages/django/template/base.py" in resolve
  734.             value = self._resolve_lookup(context)
File "/usr/local/lib/python2.7/dist-packages/django/template/base.py" in _resolve_lookup
  788.                             current = current()
File "/usr/local/lib/python2.7/dist-packages/graphos/renderers/flot.py" in get_series_objects_json
  31.         return json.dumps(self.get_series_objects())
File "/usr/lib/python2.7/json/__init__.py" in dumps
  231.         return _default_encoder.encode(obj)
File "/usr/lib/python2.7/json/encoder.py" in encode
  200.         chunks = self.iterencode(o, _one_shot=True)
File "/usr/lib/python2.7/json/encoder.py" in iterencode
  263.         return _iterencode(o, 0)
File "/usr/lib/python2.7/json/encoder.py" in default
  177.         raise TypeError(repr(o) + " is not JSON serializable")

Exception Type: TypeError at /viewGraph/
Exception Value: datetime.date(2015, 1, 13) is not JSON serializable

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.