Create dynamic labels for Google Chart using GChartWrapper

£可爱£侵袭症+ 提交于 2019-12-11 09:19:18

问题


I'm using the awesome Google Chart Wrapper to create charts as part of my Django project. Right now I'm creating the chart instance using Python in my views, and then adding the instance to the template context and displaying the charts in my templates successfully.

What I'm having trouble doing is displaying a dynamic set of X-Axis labels. Here is the relevant code from Google Chart Wrapper:

def label(self, index, *args): 
    """ 
    Label each axes one at a time 
    args are of the form <label 1>,...,<label n> 
    APIPARAM: chxl 
    """ 
    self.data['labels'].append( 
    str('%s:|%s'%(index, '|'.join(map(str,args)) )).replace('None','') 
    ) 
    return self.parent 

and how I'm currently creating the chart in my view:

from GChartWrapper import *

chart = Sparkline([1,2,3,4,5,6,7], encoding='text')
chart.axes.label(...) # need to set labels here

I have a list of date strings that I'd like to display as the x-axis labels, does anyone know how I would go about doing that?


回答1:


In order to understand how to properly pass the labels it's important to know what *args means.

*args (which is an asterisk + an arbitrary argument name) in a function (or method as in this case) definition means any number (including 0) of anonymous arguments.

See this answer for a more thorough explanation.

This means that the method in question accepts one obligatory argument index which is the index of the axis to be labelled and any number of anonymous arguments (actual labels).

Knowing this, it should already be clear that the proper way to call label() is as follows:

chart.axes.label( 0, 'date 1', 'date 2', 'date 3', ... )

where 0 is the index of the X-axis and all the other arguments are respective labels.

The reason why this is implemented in this manner is that the number of lables is unknown - it depends on the chart, so accepting any number of labels seems like a good idea.

You may also want to take a look at the example here



来源:https://stackoverflow.com/questions/13055783/create-dynamic-labels-for-google-chart-using-gchartwrapper

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!