How to display data with value '0' in chart with chart.js? - django

I have a chart of 3 data-Chinese Book, English Book, Malay Book.
Chinese book has 300, English Book has 400, Malay Book has 0.
It works fine when I only display Chinese Book and English Book.
When I add in Malay Book for display, it doesn't return errors but displays nothing.
Here is my function for bar chart,
function setChart(){
var ctx = document.getElementById("avgPageCount");
var avgPageCount = new Chart(ctx, {
type: 'bar',
data: {
labels: {{ chartdata_labels|safe }},
datasets: [{
label: '# of votes',
data: {{ chartdata_data }},
backgroundColor: {{ chart_bg | safe }} ,
borderColor: {{ chart_bd | safe }},
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
});
}
window.onload = setChart;
Malay book will return 0 since there is no new register book for this month.
malay_book= Book.objects.filter(reg_date__range(current_month_first_day,today)).aggregate(Sum('total'))['total_sum']
_out_label.append('Malay Book')
_out_data.append(malay_book)
Is the chart won't display value with '0'?

Related

How to select time on my chart js graph on Django?

I'm trying to do a selection on what only will be displayed on my chart, but I don't know what it's called hehe. please help
my views.py look like this.
class ResView(LoginRequiredMixin, ListView):
model = Rainfall
template_name = 'home.html'
context_object_name = 'res'
paginate_by = 8
queryset = Rainfall.objects.all().order_by('-id')
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context["qs"] = Rainfall.objects.all()
return context
my chart look like this.
<script>
(function () {
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: [{% for i in qs %}'{{i.timestamp}}',{% endfor %}],
datasets: [{
label: 'Rainfall Graph',
data: [{% for i in qs %}'{{i.amount}}',{% endfor %}],
lineTension: 0,
backgroundColor: 'transparent',
borderColor: '#c9c5c5',
borderWidth: 2,
pointRadius: 1,
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: false
}
}]
},
legend: {
display: false
}
}
})
}());
Now I want to select what to display on my chart. something like a dropdown like this. That I have an option.
<select>
<option value="hour">Hour</option>
<option value="day">Day</option>
<option value="month">Month</option>
</select>

Add space Between Columns in Bar chart. chartjs

I'm creating graphs using chart js V 2.9.3.
When I create the graph with a small amount of data it renders data perfectly but when the amount of data is increasing, the chart becomes Crowded.
A graph has two columns in single label.
I'm also not able to set the labels without rotation.
var config = {
type: 'bar',
data: {
labels: _datesForLabel,
datasets: _chartDataWithOptions,
},
options: {
tooltips: {
},
plugins: {
colorschemes: {
scheme: 'office.Waveform6'
}
},
scales: {
yAxes: [{
ticks: {
min: 0,
}
}],
xAxes: [{
barThickness: 40,
maxBarThickness: 40,
barPercentage: 1.0,
categoryPercentage: 1.0,
ticks: {
min: 0,
},
}]
}
}
};
myBarChart = new Chart(ctx, config);
These are the options I used.
given is the screenshot of the output
output Image
can anyone help me with this.
thank you
Remove this barThickness: 40, (40 in pixels). In your case "No space/room" for such width = overlaps & broken layout.
https://www.chartjs.org/docs/latest/charts/bar.html#barthickness
Basic snippet (Base on your code) (change barThickness barPercentage barPercentage):
https://www.chartjs.org/docs/latest/charts/bar.html#barpercentage-vs-categorypercentage
var canvas = document.getElementById("myChart");
var ctx = canvas.getContext("2d");
var _datesForLabel = ["2020-02-10",
"2020-02-13",
"2020-02-17",
"2020-02-18",
"2020-02-19",
"2020-02-20",
"2020-02-21",
"2020-02-22",
"2020-02-23",
"2020-02-24",
"2020-02-25",
"2020-02-26",
"2020-02-27",
"2020-02-28",
"2020-02-29",
"2020-03-01",
"2020-03-02",
"2020-03-03",
"2020-03-04",
"2020-03-05",
"2020-03-07",
"2020-03-08",
"2020-03-09",
"2020-03-10","2020-02-10",
"2020-02-13",
"2020-02-17",
"2020-02-18",
"2020-02-19",
"2020-02-20",
"2020-02-21",
"2020-02-22",
"2020-02-23",
"2020-02-24",
"2020-02-25",
"2020-02-26",
"2020-02-27",
"2020-02-28",
"2020-02-29",
"2020-03-01",
"2020-03-02",
"2020-03-03",
"2020-03-04",
"2020-03-05",
"2020-03-07",
"2020-03-08",
"2020-03-09",
"2020-03-10"]
var _chartDataWithOptions =[];
_chartDataWithOptions.push({
label:"dataseries1",
data:[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24],
backgroundColor:"blue"
})
_chartDataWithOptions.push({
label:"dataseries2",
data:[2,3,4,5,6,7,8,9,10,12,13,11,10,19,14,12,11,18,26,23,21,28,24,2,3,4,6,9,1,2,1,11,12,13,14,15,16,17,18,19,20,21,22,23,11,22,4,6,3,6],
backgroundColor:"red"
})
var config = {
type: 'bar',
data: {
labels: _datesForLabel,
datasets: _chartDataWithOptions,
borderSkipped: 'top'
},
options: {
// responsive: true,
tooltips: {
// mode: ''
},
plugins: {
colorschemes: {
scheme: 'office.Waveform6'
}
},
scales: {
yAxes: [{
ticks: {
min: 0,
}
}],
xAxes: [{
// barThickness: 40, // number (pixels) or 'flex'
maxBarThickness: 40,
barPercentage: 1,/* change this */
categoryPercentage: 0.5,/* change this */
ticks: {
min: 0,
},
}]
}
}
};
myBarChart = new Chart(ctx, config);
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js" ></script>
<div style="height: 500px; width: 100%;">
<canvas id="myChart" ></canvas>
</div>
About "set labels without rotation" - again "no room" - by maxRotation: 0, - full answer + example her: Chart Js Change Label orientation on x-Axis for Line Charts
"To much points/data" issue:
For now "no way" to auto group data - one idea is to use
stacked: true ("save room") - or manually filter your data (Show fewer points - related StackOverflow Q: Chartjs 2 scaling lots of data points).
Related Github feature request: https://github.com/chartjs/Chart.js/issues/4053

chart.js scatter chart- datasets data in array not showing data [duplicate]

I wish to pass values of an array to the data and label fields of the chart.js dataset.
Here the code from success of ajax call made to fetch json data. I fetch the json data and store it into an array.
Data = jQuery.parseJSON(result);
var count = Data.length;
var counter = 0;
while(count > 0) {
LabelResult[counter] =[Data[counter].TIME];
counter++;
count --;
}
Now i wish to use this label values into the labels filed.
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: [LabelResult],
datasets: [{
label: '# of Votes',
data: [DataResult],
borderWidth: 1
}]
}
});
But there seems some issue and the data is not getting rendered on the chart
LabelResult is an array, change
labels: [LabelResult]
to
labels: LabelResult
Also:
data: [DataResult]
to
data: DataResult
Like:
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: LabelResult,
datasets: [{
label: '# of Votes',
data: DataResult,
borderWidth: 1
}]
}
});
I think you could try to remove some brackets.
while(count > 0){
LabelResult[counter] = Data[counter].TIME; // here removed brackets
counter++;
count --;
}
and
data: {
labels: LabelResult, // here removed brackets
datasets: [{
label: '# of Votes',
data: DataResult, // here removed brackets
borderWidth: 1
}]
},
I hope that will works.

problem with multiple datasets in chart.js

I'm trying to use chart.js to create a bar chart that shows the number of ad impressions in an ad buy by publication. The desired chart would show a bar for each publication representing the number of impressions for the ad on that website.
I thought that this needs to happen as multiple datasets, one for each publication, where each dataset contains one data point. Here's the code I'm using for this approach:
var chartData_webbanner_300x600 = {
labels: ["Publication 1", "Publication 2"],
datasets: [
{
label: "Publication 1",
backgroundColor: "#971317",
data: [30000]
},
{
label: "Publication 2",
backgroundColor: "#0b72ba",
data: [40000]
},
]
};
window.onload = function() {
var ctx_webbanner_300x600 = document.getElementById('chart_webbanner_300x600').getContext('2d');
window.myBar = new Chart(ctx_webbanner_300x600, {
type: 'bar',
data: chartData_webbanner_300x600,
options: {
title: {
display: true,
text: 'Web Banner Impressions'
},
responsive: true,
}
});
}; //window.onload = function()
The resulting chart only shows one bar. Here's a screenshot:
I also tried this as a single dataset, but had no luck there. This is the approach I tried with that:
var chartData_webbanner_300x600 = {
labels: ["Total Impressions"],
datasets: [
{
label: ["Publication 1", "Publication 2"],
backgroundColor: ["#971317","#0b72ba"],
data: [30000,40000]
}
]
};
window.onload = function() {
var ctx_webbanner_300x600 = document.getElementById('chart_webbanner_300x600').getContext('2d');
window.myBar = new Chart(ctx_webbanner_300x600, {
type: 'bar',
data: chartData_webbanner_300x600,
options: {
title: {
display: true,
text: 'Web Banner Impressions'
},
responsive: true,
}
});
}; //window.onload = function()
Here's how that is displaying (with no bars):
Please let me know if you have any ideas on what I'm doing wrong. Thank you for taking the time to help!
I was able to get it working with this code:
var graphData = {
labels: ['Publication 1', 'Publication 2'],
datasets: [{
label: 'Impressions',
data: [30000, 40000],
backgroundColor: [
"#971317",
"#0b72ba"
],
}, ]
};
var ctx_webbanner_300x600 = document.getElementById('chart_webbanner_300x600').getContext('2d');
var chr = new Chart(ctx_webbanner_300x600, {
data: graphData,
type: 'bar',
options: {
scales: {
yAxes: [{
display: true,
ticks: {
beginAtZero: true // minimum value will be 0.
}
}]
}
}
});
This is based on what I found here Setting specific color per label in chart.js and here How to set max and min value for Y axis - which overcame a problem where the scale was starting at the lowest value in my data set.

Chartjs 2: Multi level/hierarchical category axis in chartjs

Is it possible to define a bar chart with a multi level/category axis?
For instance I'd like to display the Region/Province categories like in this Excel chart:
I found this example using multiple xAxes.
xAxes:[
{
id:'xAxis1',
type:"category",
ticks:{
callback:function(label){
var month = label.split(";")[0];
var year = label.split(";")[1];
return month;
}
}
},
{
id:'xAxis2',
type:"category",
gridLines: {
drawOnChartArea: false, // only want the grid lines for one axis to show up
},
ticks:{
callback:function(label){
var month = label.split(";")[0];
var year = label.split(";")[1];
if(month === "February"){
return year;
}else{
return "";
}
}
}
}
]
The problem is it seems that the two axes are not really linked and the alignment of second axis is based on values instead of aligning in middle of lower level category. this case cause issues
Is there a clean way to achieve this in chart.js?
Update:
I ended up creating a feature request on chartjs.
you can provide value separately for different axis via datesets and provide an object with different configuration option (borderColor, pointBackgroundColor, pointBorderColor) etc, i hope It'll help.
here is the link for the with an update (fiddle you shared) Updated Fiddle
data: {
labels: ["January;2015", "February;2015", "March;2015", "January;2016", "February;2016", "March;2016"],
datasets: [{
label: '# of Votes',
xAxisID:'xAxis1',
data: [12, 19, 3, 5, 2, 3]
},
// here i added another data sets for xAxisID 2 and it works just fine
{
label: '# of Potatoes',
xAxisID:'xAxis2',
data: [9, 17, 28, 26, 29, 9]
}]
}
I hope that solves your problem :)
Hope this helps,
I did a bit of research and couldn't find methods to implement your solution in chartjs. Chartjs has grouped bar charts but not subgrouped bar charts like in your case.
Example: http://jsfiddle.net/harshakj89/ax3zxtzw/
Here are some alternatives,
D3js (https://d3js.org/) can be used to create sub grouped bar charts.Data can be loaded from csv or json. D3 is highly configurable, but you may have to put some effort than chartsjs.
https://plnkr.co/edit/qGZ1YuyFZnVtp04bqZki?p=preview
https://stackoverflow.com/questions/37690018/d3-nested-grouped-bar-chart
https://stackoverflow.com/questions/15764698/loading-d3-js-data-from-a-simple-json-string
ZingChart is a commercial tool and can be used to implement bar charts with sub groupes.
https://www.zingchart.com/docs/chart-types/bar-charts/
But I prefer D3 over this library. because D3 comes under BSD License.
This should work as per your requirement http://tobiasahlin.com/blog/chartjs-charts-to-get-you-started/#8-grouped-bar-chart
The best library I could found to have exactly this feature is Highcharts, this is my implementation:
and here http://jsfiddle.net/fieldsure/Lr5sjh5x/2/ you can find out how to implement it.
$(function () {
var chart = new Highcharts.Chart({
chart: {
renderTo: "container",
type: "column",
borderWidth: 5,
borderColor: '#e8eaeb',
borderRadius: 0,
backgroundColor: '#f7f7f7'
},
title: {
style: {
'fontSize': '1em'
},
useHTML: true,
x: -27,
y: 8,
text: '<span class="chart-title"> Grouped Categories with 2 Series<span class="chart-href"> Black Label </span> <span class="chart-subtitle">plugin by </span></span>'
},
yAxis: [{ // Primary yAxis
labels: {
format: '${value}',
style: {
color: Highcharts.getOptions().colors[0]
}
},
title: {
text: 'Daily Tickets',
style: {
color: Highcharts.getOptions().colors[0]
}
}
}, { // Secondary yAxis
title: {
text: 'Invoices',
style: {
color: Highcharts.getOptions().colors[0]
}
},
labels: {
format: '${value}',
style: {
color: Highcharts.getOptions().colors[0]
}
},
opposite: true
}]
,
series: [{
name: 'Daily',
type: 'column',
yAxis: 1,
data: [4, 14, 18, 5, 6, 5, 14, 15, 18],
tooltip: {
valueSuffix: ' mm'
}
}, {
name: 'Invoices',
type: 'column',
data: [4, 17, 18, 8, 9, 5, 13, 15, 18],
tooltip: {
valueSuffix: ' °C'
}
}],
xAxis: {
categories: [{
name: "1/1/2014",
categories: ["Vendor 1", "Vendor 2", "Vendor 3"]
}, {
name: "1/2/2014",
categories: ["Vendor 1", "Vendor 2", "Vendor 3"]
}, {
name: "1/3/2014",
categories: ["Vendor 1", "Vendor 2", "Vendor 3"]
}]
}
});
});
body {
padding: 0px !important;
margin: 8px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://blacklabel.github.io/grouped_categories/grouped-categories.js"></script>
<div id="container" class="chart-container"></div>
But the problem is the library is not free for commercial purposes, and this is the Chartjs implementation, in my case it is look like this:
const data ={"labels":[{"label":"Exams","children":["Wellness Examination"]},{"label":"Surgery","children":["Neuter Surgery"]},{"label":"Vaccines","children":["Bordetella"]},{"label":"Dentistry","children":["Dental Cleaning"]},{"label":"Diagnostics","children":["Other","Pre-Anesthetic","Adult Diagnostics","Pre-Anesthetic Diagnostics","Heartworm & Tick Borne Disease Test"]},{"label":"Treatments/Other","children":["Other","Microchip"]}],"datasets":[{"label":"Consumed","backgroundColor":"red","tree":[{"value":0,"children":["0"]},{"value":0,"children":["0"]},{"value":1,"children":["1"]},{"value":0,"children":["0"]},{"value":15,"children":["0","1","3","11","0"]},{"value":15,"children":["2","13"]}]},{"label":"Purchased","backgroundColor":"blue","tree":[{"value":28,"children":["28"]},{"value":1,"children":["1"]},{"value":24,"children":["24"]},{"value":10,"children":["10"]},{"value":103,"children":["2","16","34","49","2"]},{"value":165,"children":["75","90"]}]}]};
window.onload = () => {
const ctx = document.getElementById("canvas").getContext("2d");
window.myBar = new Chart(ctx, {
type: 'bar',
data: data,
options: {
responsive: true,
title: {
display: true,
text: 'Chart.js Hierarchical Bar Chart'
},
layout: {
padding: {
// add more space at the bottom for the hierarchy
bottom: 45
}
},
scales: {
xAxes: [{
type: 'hierarchical',
stacked: false,
// offset settings, for centering the categorical
//axis in the bar chart case
offset: true,
// grid line settings
gridLines: {
offsetGridLines: true
}
}],
yAxes: [{
stacked: false,
ticks: {
beginAtZero: true
}
}]
}
}
});
};
canvas {
-moz-user-select: none;
-webkit-user-select: none;
-ms-user-select: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://unpkg.com/chart.js/dist/Chart.bundle.js"></script>
<script src="https://unpkg.com/chartjs-scale-hierarchical"></script>
<div id="container" style="width: 75%;">
<canvas id="canvas"></canvas>
</div>
for each more column just add another dataset.