How to show second set of labels to Chart.js doughtnut chart? - charts

I succesfully added second set of labels by following other question on SO.
But now I want to show legend for all labels and second set appears crossed out. How to avoid that?
Here is my attempt:
https://jsfiddle.net/L5gs39u2/1/
var platform_labels = ["Tablet","Ordenador"];
var platform_dataset = [14,5];
var os_labels = ["Android","Windows","GNU\/Linux"];
var os_dataset = [14,4,1];
var devices_labels = ["Tablet","Ordenador","Android","Windows","GNU\/Linux"];
var chartColors = {
red: 'rgb(255, 99, 132)',
orange: 'rgb(255, 159, 64)',
yellow: 'rgb(255, 205, 86)',
green: 'rgb(75, 192, 192)',
blue: 'rgb(54, 162, 235)',
purple: 'rgb(153, 102, 255)',
grey: 'rgb(201, 203, 207)'
};
var config = {
type: 'doughnut',
data: {
datasets: [{
data: platform_dataset,
backgroundColor: [
chartColors.red,
chartColors.orange,
chartColors.yellow
],
label: 'Platform',
labels: platform_labels
}, {
data: os_dataset,
backgroundColor: [
chartColors.purple,
chartColors.green,
chartColors.blue
],
label: 'OS',
labels: os_labels
}],
labels: devices_labels
},
options: {
tooltips: {
callbacks: {
label: function (tooltipItem, data) {
var dataset = data.datasets[tooltipItem.datasetIndex];
var index = tooltipItem.index;
return dataset.labels[index] + ": " + dataset.data[index];
}
}
}
}
};
var ctx = document.getElementById('deviceChart').getContext('2d');
var employeesGraph = new Chart(ctx, config);

You have to generate the legend labels yourself by defining a legend.labels.generateLabels function together with a legend.onClick function that takes care of hiding and showing individual pie slices. This could look as follows:
legend: {
labels: {
generateLabels: () => {
let labels = [];
config.data.datasets.forEach((ds, iDs) => labels = labels.concat(ds.labels.map((l, iLabel) => ({
datasetIndex: iDs,
labelIndex: iLabel,
text: l,
fillStyle: ds.backgroundColor[iLabel],
hidden: employeesGraph ? employeesGraph.getDatasetMeta(iDs).data[iLabel].hidden : false,
strokeStyle: '#fff'
}))));
return labels;
}
},
onClick: (event, legendItem) => {
const metaData = employeesGraph.getDatasetMeta(legendItem.datasetIndex).data;
metaData[legendItem.labelIndex].hidden = !metaData[legendItem.labelIndex].hidden;
employeesGraph.update();
}
},
Please have a look at your amended code below:
var platform_labels = ["Tablet", "Ordenador"];
var platform_dataset = [14, 5];
var os_labels = ["Android", "Windows", "GNU\/Linux"];
var os_dataset = [14, 4, 1];
var devices_labels = ["Tablet", "Ordenador", "Android", "Windows", "GNU\/Linux"];
var chartColors = {
red: 'rgb(255, 99, 132)',
orange: 'rgb(255, 159, 64)',
yellow: 'rgb(255, 205, 86)',
green: 'rgb(75, 192, 192)',
blue: 'rgb(54, 162, 235)',
purple: 'rgb(153, 102, 255)',
grey: 'rgb(201, 203, 207)'
};
var config = {
type: 'doughnut',
data: {
datasets: [{
data: platform_dataset,
backgroundColor: [
chartColors.red,
chartColors.orange,
],
label: 'Platform',
labels: platform_labels
}, {
data: os_dataset,
backgroundColor: [
chartColors.purple,
chartColors.green,
chartColors.blue
],
label: 'OS',
labels: os_labels
}],
labels: devices_labels
},
options: {
legend: {
labels: {
generateLabels: () => {
let labels = [];
config.data.datasets.forEach((ds, iDs) => labels = labels.concat(ds.labels.map((l, iLabel) => ({
datasetIndex: iDs,
labelIndex: iLabel,
text: l,
fillStyle: ds.backgroundColor[iLabel],
hidden: employeesGraph ? employeesGraph.getDatasetMeta(iDs).data[iLabel].hidden : false,
strokeStyle: '#fff'
}))));
return labels;
}
},
onClick: (event, legendItem) => {
const metaData = employeesGraph.getDatasetMeta(legendItem.datasetIndex).data;
metaData[legendItem.labelIndex].hidden = !metaData[legendItem.labelIndex].hidden;
employeesGraph.update();
}
},
tooltips: {
callbacks: {
label: function(tooltipItem, data) {
var dataset = data.datasets[tooltipItem.datasetIndex];
var index = tooltipItem.index;
return dataset.labels[index] + ": " + dataset.data[index];
}
}
}
}
};
var ctx = document.getElementById('deviceChart').getContext('2d');
var employeesGraph = new Chart(ctx, config);
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.js"></script>
<canvas id="deviceChart" height="120"></canvas>

The second set of labels are striked through because chartjs see's them as hidden, i.e. they have no values so are not rendered and the labels are only getting drawn from the first dataset.
There is a few ways around this, you could either disable the legend and then create a custom legend but I'm not sure if this will grab all of the labels:
var chart = new Chart(ctx, {
type: 'line',
data: data,
options: {
legend: {
display: false
},
legendCallback: function(chart) {
var text = [];
text.push('<ul>');
for (var i=0; i<devices_labels.length; i++) {
text.push('<li>');
text.push('<span style="background-color:' +
chart.data.datasets[i].borderColor + '">' + devices_labels[i] +
'</span>');
text.push('</li>');
}
text.push('</ul>');
return text.join("");
}
}
});
Or you could extend chartjs to change the behaviour of labels for hidden data:- change legend item style when dataset is hidden
Or the simplest way is to just add in some dummy data, to your first dataset:-
var platform_labels = ["Tablet","Ordenador"];
var platform_dataset = [14, 5, 0, 0, 0];
var os_labels = ["Android","Windows","GNU\/Linux"];
var os_dataset = [14,4,1];
var devices_labels = ["Tablet","Ordenador","Android","Windows","GNU\/Linux"];
var chartColors = {
red: 'rgb(255, 99, 132)',
orange: 'rgb(255, 159, 64)',
yellow: 'rgb(255, 205, 86)',
green: 'rgb(75, 192, 192)',
blue: 'rgb(54, 162, 235)',
purple: 'rgb(153, 102, 255)',
grey: 'rgb(201, 203, 207)'
};
var config = {
type: 'doughnut',
data: {
datasets: [{
data: platform_dataset,
backgroundColor: [
chartColors.red,
chartColors.orange,
chartColors.purple,
chartColors.green,
chartColors.blue
],
label: 'Platform',
labels: platform_labels
}, {
data: os_dataset,
backgroundColor: [
chartColors.purple,
chartColors.green,
chartColors.blue
],
label: 'OS',
labels: os_labels
}],
labels: devices_labels
}
};
var ctx = document.getElementById('deviceChart').getContext('2d');
var employeesGraph = new Chart(ctx, config);

Related

How to fill background colors on line-charts?

I'm migrating some plots from Plot.ly to Chart.js v2.9, and I'm trying to add background colors to my new Chart.js plots to match their predecessor:
But when I add the appropriate plugin to my Chart.js config, instead I get this:
Here is my plugin code:
[{
beforeDraw: function (chart, easing) {
let config: DragenChartConfiguration = chart.config;
if (chart.ctx) {
if (config.dragen?.hBars) {
var ctx = chart.ctx;
var chartArea = chart.chartArea;
for (const hBar of config.dragen.hBars) {
ctx.save();
ctx.fillStyle = hBar.color;
ctx.fillRect(chartArea.left, hBar.from, chartArea.right - chartArea.left, hBar.to - hBar.from);
ctx.restore();
}
}
}
}
}]
Where each "Hbar" object simply defines a color and a Y-axis range I want to color:
hBars: Array(3)
0: {from: 28, to: 100, color: "rgb(195, 230, 195)"}
1: {from: 20, to: 28, color: "rgb(230, 220, 195)"}
2: {from: 0, to: 20, color: "rgb(230, 195, 195)"}
length: 3
What am I missing here?
You are taking raw values instead of getting the pixels for those values, if you do that it will work:
Plugin V3:
{
id: 'backgrounds',
beforeDraw: (chart, args, options) => {
const { ctx, chartArea, scales: {y} } = chart;
options.hbars.forEach((hBar) => {
ctx.save();
ctx.fillStyle = hBar.color;
ctx.fillRect(chartArea.left, y.getPixelForValue(hBar.from), chartArea.right - chartArea.left, y.getPixelForValue(hBar.to) - y.getPixelForValue(hBar.from));
ctx.restore();
})
}
}
Plugin V2:
{
id: 'backgrounds',
beforeDraw: (chart, x, options) => {
const { ctx, chartArea, scales } = chart;
const y = scales['y-axis-0']
options.hbars.forEach((hBar) => {
ctx.save();
ctx.fillStyle = hBar.color;
ctx.fillRect(chartArea.left, y.getPixelForValue(hBar.from), chartArea.right - chartArea.left, y.getPixelForValue(hBar.to) - y.getPixelForValue(hBar.from));
ctx.restore();
})
}
Working example V3:
var options = {
type: 'line',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [100, 19, 3, 5, 2, 3],
borderWidth: 1
},
{
label: '# of Points',
data: [7, 11, 5, 8, 3, 7],
borderWidth: 1
}
]
},
options: {
plugins: {
backgrounds: {
hbars: [{
from: 28,
to: 100,
color: "rgb(195, 230, 195)"
},
{
from: 20,
to: 28,
color: "rgb(230, 220, 195)"
},
{
from: 0,
to: 20,
color: "rgb(230, 195, 195)"
}
]
}
}
},
plugins: [{
id: 'backgrounds',
beforeDraw: (chart, args, options) => {
const {
ctx,
chartArea,
scales: {
y
}
} = chart;
options.hbars.forEach((hBar) => {
ctx.save();
ctx.fillStyle = hBar.color;
ctx.fillRect(chartArea.left, y.getPixelForValue(hBar.from), chartArea.right - chartArea.left, y.getPixelForValue(hBar.to) - y.getPixelForValue(hBar.from));
ctx.restore();
})
}
}]
}
var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.2.0/chart.js"></script>
</body>
Working example V2:
var options = {
type: 'line',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [100, 19, 3, 5, 2, 3],
borderWidth: 1
},
{
label: '# of Points',
data: [7, 11, 5, 8, 3, 7],
borderWidth: 1
}
]
},
options: {
plugins: {
backgrounds: {
hbars: [{
from: 28,
to: 100,
color: "rgb(195, 230, 195)"
},
{
from: 20,
to: 28,
color: "rgb(230, 220, 195)"
},
{
from: 0,
to: 20,
color: "rgb(230, 195, 195)"
}
]
}
}
},
plugins: [{
id: 'backgrounds',
beforeDraw: (chart, x, options) => {
const {
ctx,
chartArea,
scales
} = chart;
const y = scales['y-axis-0']
options.hbars.forEach((hBar) => {
ctx.save();
ctx.fillStyle = hBar.color;
ctx.fillRect(chartArea.left, y.getPixelForValue(hBar.from), chartArea.right - chartArea.left, y.getPixelForValue(hBar.to) - y.getPixelForValue(hBar.from));
ctx.restore();
})
}
}]
}
var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"></script>
</body>
Fiddle V3: https://jsfiddle.net/Leelenaleee/6s8upz10/15/
Fiddle V2: https://jsfiddle.net/Leelenaleee/tj71gLa2/10/

PUG rendering of Chart

I am having issues trying to get this chartJS piechart to render in PUG. I would like to put the chartJS code in its own folder and then render it across a PUG template. Can explain what I am doing wrong or point me to some docs that may hep with this? As everyone will be able to see I am attempting to try this in a few different ways. I have placed screen shots in hopes that someone might be able to tell me the cleanest way to go about it, as well as simply getting it to render on the page. I have placed screenshots, please let me know if there is any further info that I could provide. Thanks for any help you can provide.
[app.JS File][1]
const express = require('express');
const bodyParser = require('body-parser')
const path = require('path')
const app = express();
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname, 'css')));
app.set('view engine', 'pug')
app.locals.basedir = path.join(__dirname, 'views');
app.get ('/', (req, res) => {
res.render("dashboard", {title: "Home"})
})
app.listen(3000, () => {
console.log('listening to PORT 3000')
})
[JavaScript Pug Code][2]
$( document ).ready(function () {
var ctx = document.getElementById("myChart").getContext('2d');
var chart = new Chart(ctx, {
type: 'pie',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
});
})
[Main Dashboard Page][3]
html(lang="en")
head
meta(charset="UTF-8")
meta(name="viewport", content="width=device-width, initial-scale=1.0")
title USRA-NASA-NAMS
link(rel="stylesheet" href="./insight.css")
script(src="https://code.jquery.com/jquery-3.5.0.min.js")
script(src='https://cdn.jsdelivr.net/npm/chart.js#2.8.0')
script(type="text/javascript" src='pieChart.js')
<!DOCTYPE html>
<html>
<body>
<div id="chartContainer" style="height: 300px; width: 100%;">
<script type="text/javascript">
window.onload = function () {
var chart = new CanvasJS.Chart("chartContainer");
chart.options.axisY = { prefix: "$", suffix: "K" };
chart.options.title = { text: "Fruits sold in First & Second Quarter" };
var series1 = { //dataSeries - first quarter
type: "column",
name: "First Quarter",
showInLegend: true
};
var series2 = { //dataSeries - second quarter
type: "column",
name: "Second Quarter",
showInLegend: true
};
chart.options.data = [];
chart.options.data.push(series1);
chart.options.data.push(series2);
series1.dataPoints = [
{ label: "banana", y: 58 },
{ label: "orange", y: 69 },
{ label: "apple", y: 80 },
{ label: "mango", y: 74 },
{ label: "grape", y: 64 }
];
series2.dataPoints = [
{ label: "banana", y: 63 },
{ label: "orange", y: 73 },
{ label: "apple", y: 88 },
{ label: "mango", y: 77 },
{ label: "grape", y: 60 }
];
chart.render();
}
[Pug Page with PieChart Code][4]
div(class="chart")
canvas(id="chartPic" width="400" height="400")
script(src="chart.js")
script.
-window.onload = function() {
-var red="#{red}", green="#{green}", blue="#{blue}";
-var ctx = document.getElementById("chartPic").getContext('2d');
-var chart = new Chart(ctx, {
-type: 'pie',
-data: {
-labels: ["red", "green", "blue"],
-datasets: [{
-label: 'Number of votes',
-data: [1, 1, 1],
-backgroundColor: [red, green, blue],
-borderColor: [green, blue, red],
-borderWidth: 1
}],
},
-options: {
-title: {
-display: true,
-text: "chart",
},
-legend: {
-position: 'bottom'
},
}
});
};

Echarts:how to set markLine lable above the line and at the end of the line?

In echarts-3.6.2, when I set position:'end' for markLine, the lable will display at the end of line
markLine: {
data: [{
symbol:"none",
name: 'GOAL',
yAxis: 3.12 ,
label:{
normal:{
show:true,
position:'end'
}
},
lineStyle: {
normal: {
color: '#5C57FF',
width: 2
}
},
}]
},
However, I want to dislay it above the line at the end of the line? How to make it?
Change position value to insideEndTop(see in docs):
markLine: {
data: [{
symbol: "none",
name: 'GOAL',
yAxis: 3.12,
label: {
normal: {
show: true,
position: 'insideEndTop'
}
},
lineStyle: {
normal: {
color: '#5C57FF',
width: 2
}
},
}]
},
hello,do you have any ideas for not using position: 'insideEndTop', I could not upgrade the echarts plugin
I can't help without a crutch/workaround because it's very old version. You need to update the Echarts immediately, it's only right way. Or you can try to simulate markLine with the graphic component, something like below but it's highway to hell.
var myChart = echarts.init(document.getElementById('main'));
var option = {
color: ['rgba(92, 87, 255, 0.3)'],
grid: {
left: 50,
bottom: 50,
},
graphic: [{
type: 'group',
id: 'markLine',
bounding: 'raw',
children: [{
id: 'lineShape',
$action: 'replace',
type: 'line',
invisible: true,
shape: {
x1: 50,
y1: 300,
x2: 120,
y2: 300,
},
style: {
stroke: '#5C57FF',
lineWidth: 2,
},
zlevel: 10,
}, {
type: 'polygon',
$action: 'replace',
id: 'arrowShape',
invisible: true,
scale: [0.5, 0.3],
position: [90, 292.5],
shape: {
points: [
[16, 5],
[16, 47],
[38, 26]
]
},
style: {
fill: '#5C57FF',
}
}, {
type: 'text',
$action: 'replace',
id: 'labelShape',
invisible: true,
style: {
text: 'GOAL: 3.12',
x: -100,
y: 290,
fill: '#5C57FF',
font: 'bolder 12px sans-serif',
},
zlevel: 10,
}],
}],
xAxis: {
data: ["1", "2", "3", "4", "5", "6"]
},
yAxis: {
type: 'value',
max: 50
},
series: [{
name: 'Series',
type: 'bar',
data: [5, 20, 36, 10, 10, 20],
}]
};
myChart.setOption(option);
function renderMarkLine({ instance, yAxisValue, text, speed }){
var currentStep = 0;
var arrowShape = (val) => {
return {
stopCoord: 710, // 525
opts: {
invisible: false,
id: 'arrowShape',
position: [5 + val, yAxisValue - 7.5] // yAxisValue + 7.5
}
}
};
var lineShape = (val) => {
return {
stopCoord: 680, //540
opts: {
id: 'lineShape',
invisible: false,
shape: {
x1: 50,
y1: yAxisValue, // +0
x2: 50 + val,
y2: yAxisValue
}
}
}
};
var labelShape = (val) => {
return {
stopCoord: 660, // 460
opts: {
id: 'labelShape',
invisible: false,
style: {
x: -10 + val,
y: yAxisValue - 10, // 10
fill: '#5C57FF',
font: 'bolder 12px sans-serif'
}
}
}
};
var interval = setInterval(function(){
var graphicData = [];
[arrowShape, lineShape, labelShape].forEach(el => {
if (el(null).stopCoord > currentStep){
graphicData.push(el(currentStep).opts);
}
});
if (graphicData.length === 0) clearInterval(interval);
instance.setOption({ graphic: graphicData });
currentStep += 10;
}, speed);
};
renderMarkLine({ instance: myChart, yAxisValue: 500, speed: 0 });
<script src="https://cdn.jsdelivr.net/npm/echarts#3.6.2/dist/echarts.min.js"></script>
<div id="main" style="width:800px;height:600px;"></div>

ChartJs: X Axis labels cutting at bottom

I am creating vertical x axis labels however the labels cut off at bottom on mobile device:
my code is as follows:
window.chartColors = {
red: 'rgb(255, 99, 132)',
orange: 'rgb(255, 159, 64)',
yellow: 'rgb(255, 205, 86)',
green: 'rgb(51, 204, 51)',
blue: 'rgb(54, 162, 235)',
purple: 'rgb(153, 102, 255)',
grey: 'rgb(201, 203, 207)'
};
var options2 = {
type: 'line',
data: {
labels: ["02/07/2020 8:01", "02/07/2020 13:00", "02/07/2020 17:00", "02/07/2020 22:00", "02/08/2020 8:01", "02/08/2020 13:01", "02/08/2020 17:00", "02/08/2020 22:00", "02/09/2020 8:01", "02/09/2020 13:00", "02/09/2020 17:00", "02/09/2020 22:00"],
datasets: [
{
label: 'Water Level',
data: [13.534,13.652,13.298,13.062,11.763,13.613,13.534,12.629,11.369,13.495,13.574,13.456],
borderWidth: 1,
lineTension: 0,
fill: false,
backgroundColor: window.chartColors.blue,
borderColor: window.chartColors.blue,
}
],
scales: {
xAxes: [{
ticks: {
beginAtZero: false
}
}]
}
},
options: {
legend: {
position: 'bottom',
display: false
},
responsive: true,
bezierCurve: false,
scales: {
xAxes: [{
ticks: {
autoSkip: true,
maxRotation: 90,
minRotation: 90
}
}],
yAxes: [{
ticks: {
min: 0,
max: 36,
stepSize: 10
},
scaleLabel: {
display: true,
labelString: 'inches'
}
}]
},
backgroundRules: [{
backgroundColor: window.chartColors.green,
yAxisSegement: 6
}, {
backgroundColor: window.chartColors.grey,
yAxisSegement: 12
}, {
backgroundColor: window.chartColors.red,
yAxisSegement: 999999
}]
},
plugins: [{
beforeDraw: function (chart) {
var rules = chart.chart.options.backgroundRules;
var ctx = chart.chart.ctx;
var yAxis = chart.chart.scales["y-axis-0"];
var xaxis = chart.chart.scales["x-axis-0"];
for (var i = 0; i < rules.length; ++i) {
var yAxisSegement = (rules[i].yAxisSegement > yAxis.ticksAsNumbers[0] ? yAxis.ticksAsNumbers[0] : rules[i].yAxisSegement);
var yAxisPosStart = yAxis.height - ((yAxisSegement * yAxis.height) / yAxis.ticksAsNumbers[0]) + chart.chart.controller.chartArea.top;
var yAxisPosEnd = (i === 0 ? yAxis.height : yAxis.height - ((rules[i - 1].yAxisSegement * yAxis.height) / yAxis.ticksAsNumbers[0]));
ctx.fillStyle = rules[i].backgroundColor;
ctx.fillRect(xaxis.left, yAxisPosStart, xaxis.width, yAxisPosEnd - yAxisPosStart + chart.chart.controller.chartArea.top);
}
}
}]
};
var ctx2 = document.getElementById('chart2').getContext('2d');
var chart2 = new Chart(ctx2, options2);
Fiddle: https://jsfiddle.net/nitinjs/3nkwbeh0/10/
help
update
to replicate in firefox press CTRL + shift + m
If you add this option to your chart options it will solve the problem:
maintainAspectRatio: false,
full javscript (added code at line 40):
window.chartColors = {
red: 'rgb(255, 99, 132)',
orange: 'rgb(255, 159, 64)',
yellow: 'rgb(255, 205, 86)',
green: 'rgb(51, 204, 51)',
blue: 'rgb(54, 162, 235)',
purple: 'rgb(153, 102, 255)',
grey: 'rgb(201, 203, 207)'
};
var options2 = {
type: 'line',
data: {
labels: ["02/07/2020 8:01", "02/07/2020 13:00", "02/07/2020 17:00", "02/07/2020 22:00", "02/08/2020 8:01", "02/08/2020 13:01", "02/08/2020 17:00", "02/08/2020 22:00", "02/09/2020 8:01", "02/09/2020 13:00", "02/09/2020 17:00", "02/09/2020 22:00"],
datasets: [
{
label: 'Water Level',
data: [13.534,13.652,13.298,13.062,11.763,13.613,13.534,12.629,11.369,13.495,13.574,13.456],
borderWidth: 1,
lineTension: 0,
fill: false,
backgroundColor: window.chartColors.blue,
borderColor: window.chartColors.blue,
}
],
scales: {
xAxes: [{
ticks: {
beginAtZero: false
}
}]
}
},
options: {
legend: {
position: 'bottom',
display: false
},
maintainAspectRatio: false, // <--- THIS LINE WAS ADDED
responsive: true,
bezierCurve: false,
scales: {
xAxes: [{
ticks: {
autoSkip: true,
maxRotation: 90,
minRotation: 90
}
}],
yAxes: [{
ticks: {
min: 0,
max: 36,
stepSize: 10
},
scaleLabel: {
display: true,
labelString: 'inches'
}
}]
}
},
plugins: []
};
var ctx2 = document.getElementById('chart2').getContext('2d');
var chart2 = new Chart(ctx2, options2);
function RefreshGraph2() {
console.log(chart2);
var dt2 = {
serial: "310021000e51353532343635",
from: $("#txtFrom2").val(),
to: $("#txtTo2").val()
};
$.post("/Mobile/GetGraphData", dt2, function(data) {
var labels2 = _.pluck(data.result, 'createdAtLabel');
var values2 = _.pluck(data.result, 'waterLevel');
chart2.data.labels = labels2;
chart2.data.datasets[0].data = values2;
console.log(labels2);
console.log(values2);
//chart2.data.datasets[0].data = data.result;
chart2.update();
return false;
});
}
$(document).ready(function () {
$("#btnRefresh2").on("click", function () {
RefreshGraph2();
return false;
});
});
JSFiddle

Radar charts for chartjs always stay filled

I am trying to use the datasetFill option for the radar charts for chartjs and I noticed that the charts always stay filled even when I set datasetFill to false. Here is a link to a fiddle that gives an example of what I'm trying to do http://jsfiddle.net/5gHVY/143/. Here is the code below:
//line chart data
var lineData = {
labels: ["Jan", "Feb", "March", "April", "May", "June", "July"],
datasets: [{
fillColor: "rgba(255,255,0,100)",
strokeColor: "rgba(63,169,245,1)",
pointColor: "rgba(63,169,245,1)",
pointStrokeColor: "#fff",
data: [65, 59, 90, 81, 56, 55, 40]
}, {
fillColor: "rgba(255,255,255,0)",
strokeColor: "rgba(102,45,145,1)",
pointColor: "rgba(102,45,145,1)",
pointStrokeColor: "#fff",
data: [28, 48, 40, 19, 96, 27, 100]
}]
}
var lineOptions = {
animation: true,
pointDot: true,
scaleOverride : true,
scaleShowGridLines : false,
scaleShowLabels : true,
scaleSteps : 4,
scaleStepWidth : 25,
scaleStartValue : 25,
datasetFill: false,
};
var radarOptions = {
datasetFill: false,
};
//radar chart data
var radarData = {labels : ["Eating","Drinking","Sleeping","Designing","Coding","Partying","Running"],
datasets : [
{
fillColor: "rgba(102,45,145,.1)",
strokeColor: "rgba(102,45,145,1)",
pointColor : "rgba(220,220,220,1)",
pointStrokeColor : "#fff",
data : [65,59,90,81,56,55,40]
},
{
fillColor: "rgba(63,169,245,.1)",
strokeColor: "rgba(63,169,245,1)",
pointColor : "rgba(151,187,205,1)",
pointStrokeColor : "#fff",
data : [28,48,40,19,96,27,100]
}
]
}
//Create Line chart
var ctx = document.getElementById("lineChart").getContext("2d");
var myNewChart = new Chart(ctx).Line(lineData, lineOptions);
//Create Radar chart
var ctx2 = document.getElementById("radarChart").getContext("2d");
var myNewChart2 = new Chart(ctx2).Radar(radarData, radarOptions);
edit: A pull request was just merged to fix this issue (https://github.com/nnnick/Chart.js/pull/1127), you will need to build the chart.js main file though as it is only in the src for the moment, just clone the project and run the gulp build.
The radar draw method is not taking this option into acount. Until a fix is present in the main Chart js you can extend the radar chart and override the draw method to take this option into account
Chart.types.Radar.extend({
// Passing in a name registers this chart in the Chart namespace in the same way
name: "RadarAlt",
draw : function(ease){
var easeDecimal = ease || 1,
ctx = this.chart.ctx;
this.clear();
this.scale.draw();
Chart.helpers.each(this.datasets,function(dataset){
//Transition each point first so that the line and point drawing isn't out of sync
Chart.helpers.each(dataset.points,function(point,index){
if (point.hasValue()){
point.transition(this.scale.getPointPosition(index, this.scale.calculateCenterOffset(point.value)), easeDecimal);
}
},this);
//Draw the line between all the points
ctx.lineWidth = this.options.datasetStrokeWidth;
ctx.strokeStyle = dataset.strokeColor;
ctx.beginPath();
Chart.helpers.each(dataset.points,function(point,index){
if (index === 0){
ctx.moveTo(point.x,point.y);
}
else{
ctx.lineTo(point.x,point.y);
}
},this);
ctx.closePath();
ctx.stroke();
ctx.fillStyle = dataset.fillColor;
if(this.options.datasetFill)
{
ctx.fill();
}
//Now draw the points over the line
//A little inefficient double looping, but better than the line
//lagging behind the point positions
Chart.helpers.each(dataset.points,function(point){
if (point.hasValue()){
point.draw();
}
});
},this);
}
});
here it is in action
Chart.types.Radar.extend({
// Passing in a name registers this chart in the Chart namespace in the same way
name: "RadarAlt",
draw: function(ease) {
var easeDecimal = ease || 1,
ctx = this.chart.ctx;
this.clear();
this.scale.draw();
Chart.helpers.each(this.datasets, function(dataset) {
//Transition each point first so that the line and point drawing isn't out of sync
Chart.helpers.each(dataset.points, function(point, index) {
if (point.hasValue()) {
point.transition(this.scale.getPointPosition(index, this.scale.calculateCenterOffset(point.value)), easeDecimal);
}
}, this);
//Draw the line between all the points
ctx.lineWidth = this.options.datasetStrokeWidth;
ctx.strokeStyle = dataset.strokeColor;
ctx.beginPath();
Chart.helpers.each(dataset.points, function(point, index) {
if (index === 0) {
ctx.moveTo(point.x, point.y);
} else {
ctx.lineTo(point.x, point.y);
}
}, this);
ctx.closePath();
ctx.stroke();
ctx.fillStyle = dataset.fillColor;
if (this.options.datasetFill) {
ctx.fill();
}
//Now draw the points over the line
//A little inefficient double looping, but better than the line
//lagging behind the point positions
Chart.helpers.each(dataset.points, function(point) {
if (point.hasValue()) {
point.draw();
}
});
}, this);
}
});
var radarOptions = {
datasetFill: false,
};
//radar chart data
var radarData = {
labels: ["Eating", "Drinking", "Sleeping", "Designing", "Coding", "Partying", "Running"],
datasets: [{
fillColor: "rgba(102,45,145,.1)",
strokeColor: "rgba(102,45,145,1)",
pointColor: "rgba(220,220,220,1)",
pointStrokeColor: "#fff",
data: [65, 59, 90, 81, 56, 55, 40]
}, {
fillColor: "rgba(63,169,245,.1)",
strokeColor: "rgba(63,169,245,1)",
pointColor: "rgba(151,187,205,1)",
pointStrokeColor: "#fff",
data: [28, 48, 40, 19, 96, 27, 100]
}]
}
//Create Radar chart
var ctx2 = document.getElementById("radarChart").getContext("2d");
var myNewRadarChart = new Chart(ctx2).RadarAlt(radarData, radarOptions);
<script src="http://www.chartjs.org/assets/Chart.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="radarChart" width="800" height="650"></canvas>