Related
// Set Chart Global Variables
let x_values = [0];
let y_values = [0];
let new_number = 0;
let index = 0;
// Intialize The Chart Canvas
let ctx = document.getElementById('chart_canvas').getContext('2d');
// Create New Line Chart
my_chart = new Chart(ctx, {
type: "line",
data: {
labels: [x_values[0]],
datasets: [{
backgroundColor: [],
fill: true,
pointStyle: "circle",
label: "Values",
data: [y_values[0]]
}]
}
});
// ------ Local Functions ------
function add() {
index = x_values.length;
new_number += 10;
my_chart.data.labels.push(index);
x_values.push(index);
my_chart.data.datasets.forEach((dataset) => {
dataset.data.push(new_number);
//The line below might be wrong since it is not changing the background color.
dataset.backgroundColor.push("#88c0d080");
});
my_chart.update();
}
function subtract() {
index = x_values.length;
new_number -= 10;
my_chart.data.labels.push(index);
x_values.push(index);
my_chart.data.datasets.forEach((dataset) => {
dataset.data.push(new_number);
//This line below might be wrong since it is not changing the background color.
dataset.backgroundColor.push("#bf616a80");
});
my_chart.update();
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Testing Chart.js Line Chart</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.8.0/chart.min.js" integrity="sha512-sW/w8s4RWTdFFSduOTGtk4isV1+190E/GghVffMA9XczdJ2MDzSzLEubKAs5h0wzgSJOQTRYyaz73L3d6RtJSg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
</head>
<body>
<button type="button" onclick="add()" id="btnAdd">Add 10</button>
<button type="button" onclick="subtract()" id="btnSubtract">Subtract 10</button>
<canvas id="chart_canvas">Your browser does not support the HTML5 canvas tag.</canvas>
</body>
</html>
Expected Behavior:
When the "Add 10" button is clicked, a new point entry needs to be added with a backgroundColor fill
color of teal (#88c0d080).
When the "subtract 10" button is clicked, a new point entry needs to be added with a backgroundColor fill color of red (#bf616a80).
Current Behavior:
Only the point background color is being changed rather than the backgroundColor fill color.
Your help will be much appreciated.
You can use segment styling that update dynamicly when you add new data:
const options = {
type: 'line',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
borderColor: 'orange',
fill: true,
segment: {
backgroundColor: (ctx) => (ctx.p0.parsed.y > ctx.p1.parsed.y ? 'red' : 'teal')
}
}]
},
options: {}
}
const ctx = document.getElementById('chartJSContainer').getContext('2d');
const c = new Chart(ctx, options);
document.getElementById('add').addEventListener('click', () => {
c.data.labels.push(c.data.labels.length);
c.data.datasets[0].data.push(c.data.datasets[0].data[c.data.datasets[0].data.length - 1] + 10)
c.update()
});
document.getElementById('subb').addEventListener('click', () => {
c.data.labels.push(c.data.labels.length);
c.data.datasets[0].data.push(c.data.datasets[0].data[c.data.datasets[0].data.length - 1] - 10)
c.update()
});
<body>
<button id="add">
Add 10
</button>
<button id="subb">
Subtract 10
</button>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.8.0/chart.js"></script>
</body>
I have created a Radar Chart using ChartJS as follows:
HTML:
<canvas id="radarChartTest" width="800" height="600"></canvas>
<script>
radarChartTest(["A", "B", "C", "D"], [5, 10, 15, 20], document.getElementById("radarChartTest"));
</script>
JS:
function radarChartTest(categories, totals, chartToPopulate) {
var chartDisplay = chartToPopulate;
var newChart = new Chart(chartDisplay, {
type: 'radar',
data: {
labels: categories,
datasets: [
{
data: totals,
label: "test"
}
]
}
})
}
JSFiddle
The chart draws and populates fine. However, when I hover over a radar point, it does not display the value:
There should be a number after test:.
I am expecting something similar to this:
Am I missing an attribute or something? I have checked the documentation but could not spot anything for it. I have also compared my code to where I found (a working example), but could not spot anything there either.
This is due to a bug in the that version (2.8.0) of Chart.js (Values on Tooltip of Radar Chart is not shown).
You can fix it by upgrading to 2.9.0.
Updated working Fiddle with version 2.9.0
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.9.0"> </script>
As far as I can tell I had the same problem a while ago, maybe, because I'll need to research a little more about this issue, the problem is due to a previous version of Chart.js. In any case here is a CodePen with a solution to your problem RadarChart Example. Hope this helps. Cheers, sigfried.
UPDATE
Since this is not only about the answers here is the link from the documentation of Chart.js that I used to solve the tooltips issue Label Callbacks.
I tried to re-create the problem you have but it looks all good to me.(A number after "total")
Since you only post part of your code, I am not sure where you are confused.
So I attached the full code I created here. Compare it to your code and let me know if you still can't generate the figure you want.
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript chart</h2>
<p>Radar Chart Demo </p>
<canvas id="radar-chart" width="800" height="600"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js">
</script>
<script>
function radarChart(categories, totals, averages, chartToPopulate, chartTitle) {
var chartDisplay = chartToPopulate;
var newChart = new Chart(chartDisplay, {
type: 'radar',
data: {
labels: categories,
datasets: [
{
data: averages,
pointBackgroundColor: ["rgba(199,54,54,1)", "rgba(199,54,122,1)", "rgba(199,54,154,1)", "rgba(146,54,199,1)", "rgba(69,54,199,1)", "rgba(54,103,199,1)", "rgba(54,165,199,1)", "rgba(54,199,180,1)"],
pointBorderColor: ["rgba(199,54,54,1)", "rgba(199,54,122,1)", "rgba(199,54,154,1)", "rgba(146,54,199,1)", "rgba(69,54,199,1)", "rgba(54,103,199,1)", "rgba(54,165,199,1)", "rgba(54,199,180,1)"],
pointRadius: 15,
pointStyle: "cross",
pointHoverRadius: 25,
pointHoverBorderWidth: 3,
pointRotation: 45,
pointBorderWidth: 1.2,
backgroundColor: "rgba(61,49,225,0.5)",
borderColor: "rgba(61,49,225,1)",
label: "Averages",
fill: true
},
{
data: totals,
pointBackgroundColor: ["rgba(199,54,54,1)", "rgba(199,54,122,1)", "rgba(199,54,154,1)", "rgba(146,54,199,1)", "rgba(69,54,199,1)", "rgba(54,103,199,1)", "rgba(54,165,199,1)", "rgba(54,199,180,1)"],
pointBorderColor: ["rgba(199,54,54,1)", "rgba(199,54,122,1)", "rgba(199,54,154,1)", "rgba(146,54,199,1)", "rgba(69,54,199,1)", "rgba(54,103,199,1)", "rgba(54,165,199,1)", "rgba(54,199,180,1)"],
pointRadius: 15,
pointStyle: "cross",
pointHoverRadius: 25,
pointHoverBorderWidth: 3,
pointRotation: 45,
pointBorderWidth: 1.2,
backgroundColor: "rgba(225,49,52,0.35)",
borderColor: "rgba(225,49,52,1)",
label: "Totals",
fill: true
},
]
},
options: {
maintainAspectRation: false,
title: {
display: true,
text: chartTitle,
fontSize: 16
}
}
})
return chartDisplay;
}
var Chart = radarChart(["1","2","3","4"], [100,200,300,400], [10,20,30,40],
document.getElementById("radar-chart"), "TEST")
document.getElementById("radar-chart").innerHTML = Chart;
</script>
</body>
</html>
I am using the version 2.8, and i got the same problem, to fix
tooltips: {
enabled: true,
callbacks: {
label: function(tooltipItem, data) {
return data.datasets[tooltipItem.datasetIndex].label + ' : ' + data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
}
}
}
See the issue
https://github.com/chartjs/Chart.js/issues/6188#issuecomment-497251833
I have a graph like above. I only want one category with a green border. For example, only x-axis 2235 with a border green.
Or some other way to highlight just 2235 green.
Since I'm using a multi-bar graph, I don't know how to apply borderColor or borderWidth to a single point in the dataset. Any ideas? Thanks!
Hope my snippet will help you.
Long story short: I have no idea how to achieve a similar result using only configuration, but manipulating with your chart after initialization does real magic.
Do not forget about chart.update() when you dynamically change something in your chart.
Cheers!
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<canvas id="myChart" width="400" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.0/Chart.min.js"></script>
<script>
const context = document.getElementById("myChart").getContext('2d');
const chart = new Chart(context, {
type: 'bar',
data: {
labels: ["First", "Second", "Third"],
datasets: [{
label: "Red",
backgroundColor: "red",
borderColor: [],
borderWidth: 4,
data: [4, 3, 5]
},
{
label: "Green",
backgroundColor: "green",
borderColor: [],
borderWidth: 4,
data: [7, 2, 6]
},
{
label: "Blue",
backgroundColor: "blue",
borderColor: [],
borderWidth: 4,
data: [3, 7, 4]
},
]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
const color = "yellow";
const indexOfBordered = 1;
chart.data.datasets.forEach(dataset => {
dataset.borderColor[indexOfBordered] = color;
});
chart.update();
</script>
</body>
</html>
This question is in continuation of this post Dynamically update values of a chartjs chart and the example http://jsbin.com/yitep/5/edit?html,js,output
I am new to chartJS, in the above example it is shown how to update dynamically chart data. But, can any one help me with how to start with a blank chart and then update dynamically.
Note: It is possible in Highcharts, is the same possible in chartJS.
EDIT
http://www.chartjs.org/docs/
The chartjs library is now the most updated and useful. Use the link above.
I think what you need to do is download the updated Chart.Js library, ChartNew.js at: https://github.com/FVANCOP/ChartNew.js/ . This updated library has an update function among many other improvements that make things much easier. You can download the zip file using the link above and find tons great example files that will help you figure out most issues. There is also some pretty good documentation at: https://github.com/FVANCOP/ChartNew.js/wiki/100.Available_options .
I will add a full example from the above library that you can copy and paste into an html file in order to see exactly how you can create a dynamic chart. Just take a look and play around with the examples until you start to see how things work.
<!doctype html>
<!--[if lte IE 8]><SCRIPT src='source/excanvas.js'></script><![endif]--><SCRIPT src='../ChartNew.js'></script>
<SCRIPT src='../Add-ins/format.js'></script>
<SCRIPT>
function setColor(area,data,config,i,j,animPct,value)
{
if(value > 35)return("rgba(220,0,0,"+animPct);
else return("rgba(0,220,0,"+animPct);
}
var charJSPersonnalDefaultOptions = { decimalSeparator : "," , thousandSeparator : ".", roundNumber : "none", graphTitleFontSize: 2 };
defCanvasWidth=600;
defCanvasHeight=300;
var mydata = {
labels : [],
datasets : [
{
fillColor : "rgba(220,220,220,0.5)",
strokeColor : "rgba(220,220,220,1)",
pointColor : "rgba(220,220,220,1)",
pointstrokeColor : "yellow",
xPos : [],
data : [],
title : "2014"
}
]
}
var startWithDataset =1;
var startWithData =1;
var opt = {
animationStartWithDataset : startWithDataset,
animationStartWithData : startWithData,
animation : true,
animationLeftToRight : true,
animationSteps : 20,
animationEasing: "linear",
canvasBorders : true,
canvasBordersWidth : 3,
canvasBordersColor : "black",
graphTitle : "animation With Update",
legend : true,
// inGraphDataShow : true,
annotateDisplay : true,
onAnimationComplete : startUpdate,
graphTitleFontSize: 18,
responsive : true,
scaleOverride: true,
scaleSteps: 10,
scaleStepWidth: 10,
scaleStartValue: 0,
fmtXLabel : "fmttime hh:mm:ss",
animationCount: 1,
animationPauseTime : 0,
animationBackward: true
};
function startUpdate(ctx, config, data, tp, count) {
setTimeout(function (){updt(ctx,data,config);}, 1000+Math.random()*500);
// setTimeout(function (){updt(ctx,data,config);}, 1000);
};
function updt(ctx,data,config) {
updtData(data);
config.animationSteps = 50*data.datasets[0].xPos.length;
config.animationStartValue=1-(2/data.datasets[0].xPos.length);
deleteHighLight(ctx,data);
updateChart(ctx,data,config,true,true);
}
function updtData(data) {
var i;
var t=new Date();
var coeff = 1000 ;
var rounded = new Date(Math.round(t.getTime() / coeff) * coeff + coeff);
for(i=0;i<10;i++)
{
var t2 = new Date(rounded - (18-2*i) * 1000);
data.labels[i]=t2;
}
data.xBegin=data.labels[0];
data.xEnd=data.labels[9];
data.datasets[0].xPos[data.datasets[0].xPos.length]=t;
vl=Math.random()*100;
data.datasets[0].data[data.datasets[0].data.length]=vl;
// remove data outside first time;
while(data.datasets[0].xPos[0]<data.labels[0]) {
data.datasets[0].xPos.splice(0,1);
data.datasets[0].data.splice(0,1);
}
}
updtData(mydata);
updtData(mydata);
updtData(mydata);
mydata.datasets[0].xPos[0]=new Date(mydata.datasets[0].xPos[0]-2000);
mydata.datasets[0].xPos[1]=new Date(mydata.datasets[0].xPos[1]-1000);
</SCRIPT>
<html>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<head>
<title>Demo ChartNew.js</title>
</head>
<body>
<center>
<FONT SIZE=6><B>Demo of ChartNew.js !</B></FONT> <BR>
<script>
document.write("<canvas id=\"canvas_Line\" height=\""+defCanvasHeight+"\" width=\""+defCanvasWidth+"\"></canvas>");
window.onload = function() {
var myLine = new Chart(document.getElementById("canvas_Line").getContext("2d")).Line(mydata,opt);
}
</script>
</body>
</html>
The provided code example is taken directly from the GitHub download folder. They provide a great deal of examples to help make sense of the the documentation.
Check out this simple example I wrote in jsfiddle. I first created a bar chart and then used chart.update()method to update it in every second.
//value for x-axis
var emotions = ["calm", "happy", "angry", "disgust"];
//colours for each bar
var colouarray = ['red', 'green', 'yellow', 'blue'];
//Let's initialData[] be the initial data set
var initialData = [0.1, 0.4, 0.3, 0.6];
//Let's updatedDataSet[] be the array to hold the upadted data set with every update call
var updatedDataSet;
/*Creating the bar chart*/
var ctx = document.getElementById("barChart");
var barChart = new Chart(ctx, {
type: 'bar',
data: {
labels: emotions,
datasets: [{
backgroundColor: colouarray,
label: 'Prediction',
data: initialData
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true,
min: 0,
max: 1,
stepSize: 0.5,
}
}]
}
}
});
/*Function to update the bar chart*/
function updateBarGraph(chart, label, color, data) {
chart.data.datasets.pop();
chart.data.datasets.push({
label: label,
backgroundColor: color,
data: data
});
chart.update();
}
/*Updating the bar chart with updated data in every second. */
setInterval(function() {
updatedDataSet = [Math.random(), Math.random(), Math.random(), Math.random()];
updateBarGraph(barChart, 'Prediction', colouarray, updatedDataSet);
}, 1000);
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.3.0/Chart.min.js"></script>
<body>
<div>
<h1>Update Bar Chart</h1>
<canvas id="barChart" width="800" height="450"></canvas>
</div>
<script src="barchart.js"></script>
</body>
</head>
</html>
Hope this helps.
I have set up a simple column chart in Highcharts 4 with jQuery 1.9.1 where I parse a CSV file. I get the normal page showing with the column chart, but when I click on a bar nothing happens. I actually do see the arrays being created in the console (IE11) and they appear to be just what I need, they are in the correct syntax and the IDs match.
The JS fiddle [was...://jsfiddle.net/tjxwty3y/ ... I have changed this in the edit at the bottom ] . I put an example of the CSV that I use, but do not know how to link an external one into the JS Fiddle. I have tried the examples with CSV/TSVs embedded in the code and they have worked, so I think it has to do with how I am pushing the data, hence the external reference.
The CSV is very simple. I have the 3 categories in the first column, their values for the front chart, followed by the IDs in the 3rd and finally the drilldown values in the 4th and 5th.
CSV looks like this
AREA,VALUE,TYPE,SHIFT1,SHIFT2
Blog1,50000,Blog1_Shift,5,6
Blog2,60000,Blog2_Shift,2,3
Blog3,40000,Blog3_Shift,7,8
I have looked at multiple posts (and some videos) where the CSV or TSV is within the JS Fiddle and on Highcharts website, but I completely am not seeing where I have gone wrong (and I know that I have).
Just in case, here is the raw data from js fiddle which has the libraries (I typically use Higcharts 4 and JQuery 1.11 but here I've modified some older code that used JQuery 1.9.1):
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title> - jsFiddle demo</title>
<script type='text/javascript' src='//code.jquery.com/jquery-1.9.1.js'></script>
<link rel="stylesheet" type="text/css" href="/css/result-light.css">
<script type='text/javascript' src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type='text/javascript' src="http://code.highcharts.com/highcharts.js"></script>
<script type='text/javascript' src="http://code.highcharts.com/modules/data.js"></script>
<script type='text/javascript' src="http://code.highcharts.com/modules/drilldown.js"></script>
<style type='text/css'></style>
<script type='text/javascript'>
//<![CDATA[
$(window).load(function () {
$(document).ready(function () {
var options = {
chart: {
renderTo: 'container',
type: 'column'
},
title: {
text: 'My Title Here'
},
xAxis: {
categories: [],
name: []
},
yAxis: {
title: {
text: 'Value Here'
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
y: 15,
borderWidth: 0,
itemStyle: {
color: '#333',
fontSize: '15px',
},
navigation: {
activeColor: '#3E576F',
animation: true,
arrowSize: 12,
inactiveColor: '#CCC',
style: {
fontWeight: 'bold',
color: '#333',
fontSize: '15px',
}
}
},
tooltip: {
shared: true,
crosshairs: true
},
plotOptions: {
series: {
marker: {
lineWidth: 1
}
}
},
series: [],
drilldown: []
};
$.get("http://my/csv/notvalid/dev_drilldown4.csv", function (csvData) {
var lines = csvData.split('\n');
var series = {
data: [],
visible: true,
type: 'column',
colorByPoint: true,
drilldown: true
};
var drilldown = {
series: []
};
$.each(lines, function (lineNo, line) {
if (lineNo > 0 && lineNo < 4) {
var items = line.split(',');
var seriesname = String(items[0]); // this is the area
var area_cost = parseFloat(items[1]); // this is the data for the rollup
var drill_id = String(items[2]); // this will be the id of the drilldown
var shift_one_value = parseFloat(items[3]); // shift1 value
var shift_two_value = parseFloat(items[4]); // shift2 value
series.data.push({
name: seriesname,
y: area_cost,
drilldown: drill_id
});
drilldown.series.push({
id: drill_id,
data: [["shift1", shift_one_value],["shift2", shift_two_value]]
});
}
});
console.log(series.data);
console.log(drilldown.series);
options.series.push({ data: series.data });
options.drilldown.push({ series: drilldown.series });
var chart = new Highcharts.Chart(options);
});
});
});
</script>
</head>
<body>
<div id="container" style="width: 800px; height: 400px; margin: 0 auto"></div>
</body>
</html>
I appreciate any for help/advice.
Thanks
EDIT:
Now that I have added in Salman's and Pawell's edits, including adding in the CSV to the jsFiddle (see Pawell's jsFiddle for what it now looks like) I encountered an additional issue, but it is/was working now!
I realized I forgot the "name" of the series and added that in, adjusting the 'var series' and changing the 'series.data.push' to 'series.push' and watched the log as mentioned by Salman. Now nothing appears, but the console log appears to show the data with the names, ids and data, but no chart (and no error).
The js fiddle is: http://jsfiddle.net/5jzb8hzb/1/. Would you know why changing the 'series.data.push' caused the initial chart to not render?
As noticed by #Salman, there is a couple of issues:
first load Highcahrts then drilldown.js (issue only in jsFiddle)
you shouldn't push to the drilldown array, but assign created series
you have drilldown: [], while should be drilldown: {}
for series you have options.series.push({ data: series.data }), while simply use options.series.push(series) or options.series = [series]
Extra note: I suggest to check values if those are not NaN's - sometimes editors create extra empty new line at the end of the file.
After all fixes, here is fully working code: http://jsfiddle.net/tjxwty3y/7/
Minimized example:
var options = {
chart: {
renderTo: 'container'
},
series: [],
drilldown: {}
};
var csvData = document.getElementById("data").innerHTML; // like $.get()
var lines = csvData.split('\n');
var series = {
data: [],
visible: true,
type: 'column',
colorByPoint: true,
drilldown: true
};
var drilldown = {
series: []
};
// I know with the below I get an extra line so can deal with that when I get the rest of the data sorted
$.each(lines, function (lineNo, line) {
if (lineNo > 0 && lineNo < 4) {
var items = line.split(',');
var seriesname = String(items[0]); // this is the area name
var area_cost = parseFloat(items[1]); // this is the data for the area rollup
var drill_id = String(items[2]); // this will be the id of the drilldown
var shift_one_value = parseFloat(items[3]); // drilldown shift1 value
var shift_two_value = parseFloat(items[4]); // drilldown shift2 value
if(!isNaN(area_cost) && !isNaN(shift_one_value) && !isNaN(shift_two_value)) {
series.data.push({
name: seriesname,
y: area_cost,
drilldown: drill_id
});
drilldown.series.push({
id: drill_id,
data: [
["shift1", shift_one_value],
["shift2", shift_two_value]
]
});
}
}
});
options.series = [series];
options.drilldown = drilldown;
var chart = new Highcharts.Chart(options);
There is a bug in the code; if you log options you will detect it. drilldown configuration is supposed to have a series key. But in your case the key is inside drilldown[0]; probably because of using push function.
The code worked after I changed
options.drilldown.push({ series: drilldown.series });
to
options.drilldown.series = drilldown.series;
There was also another bug- drilldown library should be loaded after highcharts.
Edit: Updated fiddle: http://jsfiddle.net/dxann41x/1/