Package: pyChart.JS
An easy to use, class-based approach to implementing Chart.js into Python projects.Initially designed as a Django app, it is now self-contained and outputs chart data in JSON, meaning it can easily be used in:DjangoFlaskAJAX/Rest API requestsOther Python projectsGetting StartedInstall withpip>pipinstallpychart.jsYou will need to havechart.jsorchart.min.jsready for use in your HTML document. The following is a drop-in CDN script to use:<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.js"></script>Basic Usage1. Chart Element in HTML and JSAs stated above, the output is a JSON object which can be used directly in any template. The following is an example HTML document with a simple chart element. Here, the chart object is going to be passed into the{{ chartJSON | safe }}tag. Note here that it has to be flagged as safe otherwise it will not work.<canvasid="myChart"></canvas><script>vardata={{chartJSON|safe}}varctx=document.getElementById("myChart").getContext('2d');varmyChart=newChart(ctx,data);</script>2. Python CodeThe following is a minimal example of a chart you can generate and pass into your HTML using a Django view.Click to see more:Create ChartfrompychartjsimportBaseChart,ChartType,ColorclassMyBarGraph(BaseChart):type=ChartType.Barclassdata:label="Numbers"data=[12,19,3,17,10]backgroundColor=Color.GreenUpdate data label and use it in a Django Viewdefhomepage(request):NewChart=MyBarGraph()NewChart.data.label="My Favourite Numbers"# can change data after creationChartJSON=NewChart.get()returnrender(request=request,template_name='main/home.html',context={"chartJSON":ChartJSON})3. The ResultExtending With More FeaturesThe above is what's achievable with minimal code but you can do almost anything the JS equivalent can do. Where a feature isn't implemented natively in ObjectiveChartJS, you can use a dictionary or list as per normal.Here's a skeleton of what can be used:classMyChart(BaseChart):type=ChartType.Lineclasslabels:# ...classdata:# ...classoptions:# ...classpluginOptions:# ...Base VariablesChart TypeCan use the variables in ChartType or can be entered directlytype=ChartType.Line#...from pychartjs import ChartTypetype='Bar'In-line JSCallbacks to Javascript functions or direct code can be implemented anywhere in the chart class as long as it is a string encapsulated within<<>>note: Using this will render the output non-compliant to the JSON standard, and as such it likely will not work with AJAX/RESTcallback = "<<myJavascriptFunction>>"
inlineJS = "<<function(value,index,values){return'$'+value;}>>"SubclassesLabels ClassUsed to define the labels used for each data item. If it is left blank, labels will be generated automatically from the first data collection.Can be any of:A single list of strings for all labelsIndependent variables for each label(Planned) Select from pre-determined lists for common datasets, e.g. Days, Monthsclasslabels:grouped=['Mon','Tue','Wed']# orday1='Mon'day2='Tue'day3='Wed'Data ClassUsed to define dataordatasets. If you only have one dataset, this can be defined directly in the class. Otherwise, use subclasses for each dataset. For each subclass, the name of the class is used as the label if one isn't specified.Can be either of:A single dataset, defined directly as variables in the classMultiple datasets, each with their own subclass.Rules:Must include adatavariable of typelistMust not have functions/methods. These will not work due to the reference methods used internally. However, you can use in-line operators or call to a functionoutsidethe Chart class. You just can't define a function within the dataset class.If you don't want a variable to be compiled, prefix it with an underscore, e.g._color#One Dataset:classdata:data=[12,19,3,17,10]label="Fruit Eaten"backgroundColor=Color.Palette(Color.Green)borderColor=Color.Hex(0xA2E6B1FF)#Multiple Datasets:classdata:classApples:data=[2,8,3,3,2]classOranges:data=[2,3,0,12,1]label="Bananas"# Overrides the generated label 'Oranges'Options ClassDefine extended options here. Note however that plugin options get defined under their own heading,notin here (to avoid over-nesting).
Options can be defined either as dictionaries or by using theOptions.Generic()object. builders forTitle,Legend,Legend LabelsandLayoutare provided for convenience.Can include:Top-level options as variablesDeeper options as dictionaries orOptions.Genericobjectscallbacks or javascript functions can be included if the variable is surrounded by<< >>tagsclassoptions:# Object-basedtitle=Options.Title("My Fruit Consumption")animation=Options.Generic(duration=1000)_labels=Options.Legend_Labels(fonColor=Color.Gray,fullwidth=True)legend=Options.Legend(position='bottom',labels=_labels)# Dictionary-basedtitle={"text":"My Fruit Consumption","display":True}animation={"duration":1000}hover={"animationDuration":500}responsiveAnimationDuration=0legend={'position':'bottom','labels':{'fontColor':Color.Gray,'fullWidth':True}}Plugin Options ClassUsed to define options for plugins. Could theorectically be included in the above options class, but has been split out here to reduce clutter.Can include:One subclass per plugin (class name = plugin name)To disable a plugin, no subclass is required; simply putpluginName = Falseat the top of the pluginOptions classclasspluginOptions:stacked100=False# Disables the plugin 'stacked100'classcolorSchemes:scheme="brewer.Paired12"custom="<< customColorFunction >>"ColorsSome rudimentary color functions are provided to make generating charts and graphs easier.All colors are returned in a formatted string'rgba(R, G, B, A)'regardless of input typeColor.Hex() accepts a string or a Hex Integer.Color.RGBA() accepts either RGB or RGBA values.Color.HSLA()Color.HSVA()frompychartjsimportColorcolor1=Color.Magenta#22 basic colors availablecolor2=Color.Hex("#242424")color3=Color.Hex(0x242424FF)color4=Color.RGBA(35,22,225)color5=Color.RGBA(35,22,255,1.0)>>>'rgba(240, 50, 230, 1.0)'Color PalettesColor palettes can be generated using theColor.Palette()function. It returns a list ofrgba()formatted colors which can be used directly in the chart.BaseColor= Color to use as the generator for the palette. Must be a formatted string as above, which means it can accept any of the Color.X() functions as an input.n= Number of colors to generate. Defaults to 5.generator= Component to use to generate palette. Can be'hue','saturation','lightness'or'alpha'. Defaults tosaturationp1=Color.Palette(Color.Red)p2=Color.Palette(Color.Hex("#432475"),n=3,generator='lightness')>>>['rgba(55, 30, 97, 1.0)','rgba(111, 60, 195, 1.0)','rgba(183, 157, 224, 1.0)']Color GradientsLinear and Radial gradients can be generated using theColor.JSLinearGradientandColor.JSRadialGradientobjects.Note that this returns an escaped javascript generator function.Construction can be done in a similar fashion to the javascript way as seenhere, or alternatively the whole gradient can be build in the constructor.chartContextName= javascript chart context that you use in your HTML. Defaults to'ctx'.x1, y1, x2, y2(Linear) = start and stop gradient coordinatesx1, y1, r1, x2, y2, r2(Radial) = start, stop and radii of the circles to generate the gradient between.*colorStops= optional colorstops can be passed through as tuples to condense creation of gradients into one lineStops can be added by calling theaddColorStop()functionClick to see more examples:Example One#Define and apply color separately_color=Color.JSLinearGradient('ctx',0,0,1000,0)_color.addColorStop(0,Color.Blue)_color.addColorStop(1,Color.Green)backgroundColor=_color.returnGradient()Example Two#Inline construction of gradientbackgroundColor=_color.JSLinearGradient('ctx2',0,0,0,1000,(0,Color.Red),(1,Color.Blue)).returnGradient()Example Three#Radial GradientbackgroundColor=_color.JSRadialGradient('ctx2',50,50,0,50,50,100(0,Color.Red),(1,Color.Blue)).returnGradient()Putting it all togetherThe following is an example of a complex chart that can be created with many of the above features:classMyChart(BaseChart):type=ChartType.Barclasslabels:group=['Mon','Tue','Wed','Thu','Fri','Sat','Sun']classdata:classapples:data=[2,8,11,7,2,4,3]backgroundColor=Color.Palette(Color.Hex('#30EE8090'),7,'lightness')borderColor=Color.GreenyAxisID='apples'classtotalEnergy:label="Total Daily Energy Consumption (kJ)"type=ChartType.Linedata=[5665,5612,7566,8763,5176,5751,6546]backgroundColor=Color.RGBA(0,0,0,0)borderColor=Color.PurpleyAxisID='totalenergy'classoptions:title=Options.Title("Apples I've eaten compared to total daily energy")scales={"yAxes":[{"id":"apples","ticks":{"beginAtZero":True,"callback":"<<function(value, index, values) {return value + ' Big Ones';}>>",}},{"id":"totalenergy","position":"right","ticks":{"beginAtZero":True}}]}OutputAnother exampleclassNewChart(BaseChart):type=ChartType.Lineclasslabels:Years=list(range(2017,2023))classdata:classWhales:data=[80,60,100,80,90,60]_color=Color.JSLinearGradient('ctx',0,0,1000,0)_color.addColorStop(0,Color.Green)_color.addColorStop(1,Color.Purple)borderColor=_color.returnGradient()fill=FalsepointBorderWidth=10pointRadius=3classBears:data=[60,50,80,120,140,180]borderColor=Color.JSLinearGradient('ctx',0,0,1000,0,(0,Color.Red),(1,Color.Magenta)).returnGradient()fill=FalsepointBorderWidth=10pointRadius=3classDolphins:data=[150,80,60,30,50,30]borderColor=Color.JSLinearGradient('ctx',0,0,1000,0,(0,Color.Yellow),(1,Color.Orange)).returnGradient()fill=FalsepointBorderWidth=10pointRadius=3classoptions:title=Options.Title(text="Wildlife Populations",fontSize=18)_lables=Options.Legend_Labels(fontColor=Color.Gray,fullWidth=True)legend=Options.Legend(position='Bottom',labels=_lables)_yAxes=[Options.General(ticks=Options.General(beginAtZero=True,padding=15,max=200))]scales=Options.General(yAxes=_yAxes)OutputMore ExamplesCan be foundhere