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 Issues

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.

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

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?

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

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

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!

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'

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

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

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.

Bug in documentation

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

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?

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.

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

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

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

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.

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.

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?

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!

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

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>

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.