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
Related
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/
I am testing out HighCharts and ChartJS to see which to use. For Highcharts, I was able to find a hack to create a bar chart that had double grouping on the x-axis.
This is what I want to look like:
I am new to both charting JS options and wonder if there is a way to do this in ChartJS.
I have the datasets something like this:
xAxis: {
categories: [{
name: "Total",
categories: ["2004", "2008", "2012"]
}, {
name: "Lower than 2.50",
categories: ["2004", "2008", "2012"]
}]
},
yAxis: {
min: 0,
title: {
text: 'Percent (%)'
}
},
series: [{
name: 'Male',
data: [42.4, 43.0, 43.0, 50.3, 49.4, 48.4]
}, {
name: 'Female',
data: [57.6, 57.0, 57.0, 49.7, 50.6, 51.6]
}]
Essentially I need a nest series on the x-axis and I am open to plugins or code from Github to do this.
You can make use of the Plugin Core API. It offers different hooks that may be used for executing custom code. In below code, I use the afterDraw hook to draw the category labels and the delimiter lines.
new Chart('myChart', {
type: 'bar',
plugins: [{
afterDraw: chart => {
let ctx = chart.chart.ctx;
ctx.save();
let xAxis = chart.scales['x-axis-0'];
let xCenter = (xAxis.left + xAxis.right) / 2;
let yBottom = chart.scales['y-axis-0'].bottom;
ctx.textAlign = 'center';
ctx.font = '12px Arial';
ctx.fillText(chart.data.categories[0], (xAxis.left + xCenter) / 2, yBottom + 40);
ctx.fillText(chart.data.categories[1], (xCenter + xAxis.right) / 2, yBottom + 40);
ctx.strokeStyle = 'lightgray';
[xAxis.left, xCenter, xAxis.right].forEach(x => {
ctx.beginPath();
ctx.moveTo(x, yBottom);
ctx.lineTo(x, yBottom + 40);
ctx.stroke();
});
ctx.restore();
}
}],
data: {
labels: ['2004', '2008', '2012', '2016', '2004', '2008', '2012', '2016'],
categories: ['Total', 'Lower than 2.50'],
datasets: [{
label: 'Male',
data: [42.4, 43.0, 43.0, 50.3, 49.4, 48.4, 51.2, 51.8],
backgroundColor: 'rgba(124, 181, 236, 0.9)',
borderColor: 'rgb(124, 181, 236)',
borderWidth: 1
},
{
label: 'Female',
data: [57.6, 57.0, 57.0, 49.7, 50.6, 51.6, 53.7, 54.6],
backgroundColor: 'rgba(67, 67, 72, 0.9)',
borderColor: 'rgb(67, 67, 72)',
borderWidth: 1
}
]
},
options: {
legend: {
position: 'bottom',
labels: {
padding: 30,
usePointStyle: true
}
},
scales: {
yAxes: [{
ticks: {
min: 0,
max: 80,
stepSize: 20
},
scaleLabel: {
display: true,
labelString: 'Percent (%)'
}
}],
xAxes: [{
gridLines: {
drawOnChartArea: false
}
}]
}
}
});
canvas {
max-width: 400px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"></script>
<canvas id="myChart" height="200"></canvas>
You have to define a second x-axis and play around with the many ticks and gridLines options.
Please take a look at below runnable code and see how it could be done. This is obviously only a draft and needs to optimized and made more generic.
new Chart(document.getElementById('myChart'), {
type: 'bar',
data: {
labels: ['2004', '2008', '2012', '2004', '2008', '2012'],
datasets: [{
label: 'Male',
data: [42.4, 43.0, 43.0, 50.3, 49.4, 48.4],
backgroundColor: 'rgba(124, 181, 236, 0.9)',
borderColor: 'rgb(124, 181, 236)',
borderWidth: 1
},
{
label: 'Female',
data: [57.6, 57.0, 57.0, 49.7, 50.6, 51.6],
backgroundColor: 'rgba(67, 67, 72, 0.9)',
borderColor: 'rgb(67, 67, 72)',
borderWidth: 1
}
]
},
options: {
legend: {
position: 'bottom',
labels: {
usePointStyle: true
}
},
scales: {
yAxes: [{
ticks: {
min: 0,
max: 80,
stepSize: 20
},
scaleLabel: {
display: true,
labelString: 'Percent (%)'
}
}],
xAxes: [{
gridLines: {
drawOnChartArea: false
}
},
{
offset: true,
ticks: {
autoSkip: false,
maxRotation: 0,
padding: -15,
callback: (v, i) => {
if (i == 1) {
return 'Total';
} else if (i == 4) {
return 'Lower than 2.50';
} else {
return '';
}
}
},
gridLines: {
drawOnChartArea: false,
offsetGridLines: true,
tickMarkLength: 20,
color: ['white', 'white', 'white', 'lightgray', 'white', 'white', 'lightgray']
}
}
]
}
}
});
canvas {
max-width: 400px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"></script>
<canvas id="myChart" height="200"></canvas>
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>
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);
How to change color of some data points in graph to red:
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
you can provide an array of colors for option: pointBackgroundColor
and optionally: pointBorderColor
each color in the array represents a point on the line.
see following working snippet...
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,
borderColor: window.chartColors.blue,
// provide colors for each point
pointBackgroundColor: [window.chartColors.blue, window.chartColors.blue, window.chartColors.blue, window.chartColors.red, window.chartColors.orange, window.chartColors.yellow, window.chartColors.green, window.chartColors.purple, window.chartColors.grey, window.chartColors.blue, window.chartColors.blue, window.chartColors.blue],
pointBorderColor: [window.chartColors.blue, window.chartColors.blue, window.chartColors.blue, window.chartColors.red, window.chartColors.orange, window.chartColors.yellow, window.chartColors.green, window.chartColors.purple, window.chartColors.grey, window.chartColors.blue, window.chartColors.blue, 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'
}
}]
}
},
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;
});
});
.row {
background: #f8f9fa;
margin-top: 20px;
}
.col {
border: solid 1px #6c757d;
padding: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.9.3"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.css">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.css">
<div id="collapse2TertiaryOne0" class="collapse show" style="padding:0px;">
<div class="" style="padding: 0px;">
<div class="tabs">
<ul class="nav nav-tabs nav-justified" role="group">
<li class="nav-item" role="button">
test
</li>
</ul>
<div class="tab-content">
<div id="dataLog0" class="tab-pane active">
<canvas class="wrapper col-12" id="chart2" style="padding-left:2px;padding-right:2px" name="chart2"></canvas>
</div>
</div>
</div>
</div>
</div>