Modify Chart js - javascript

I use chart JS
var chartGood = "rgba(50,182,93,0.5)";
var lineChartData = {
labels : ["3/14","3/15","3/16","3/17","3/18","3/19","3/20","3/21","3/22","3/23"],
datasets : [
{
fillColor : chartGood,
strokeColor : "rgba(255,255,255,1)",
pointColor : "rgba(50,182,93,1)",
pointStrokeColor : "#fff",
data : [12, 21, 28, 29, 31, 55, 52, 50, 49, 59]
}
]
}
var myLine = new Chart(document.getElementById("cpu-chart").getContext("2d")).Line(lineChartData);
I have 2 questions
How to make last bar another color
How to make last label as image

You can use the ChartNew.Js libary available at https://github.com/FVANCOP/ChartNew.js/ . This libary adds the functionality to add an array of object for the color options. It does add some options for changing the labels as well, but I do not think it is possible to use an image for the actual chart's labels. You may be able to modify the tooltip that pops up for that label doing something like: How to add image to chart.js tooltip?, but I cant say for sure. Here is some code that I used in a recent app to color code each bar based on the percent value of the data:
//Set all canvas options and fill with data
self.chartJs = function () {
//create an array for each column to be set into the chart properties -- also create arrays for the colors of the columns
var arrayOfJobData = self.chartData();
var descArray = [];
var effArray = [];
var colorArray = [];
for (i = 0; i < arrayOfJobData.length; i++) {
//console.log(arrayOfJobData[i].Cost_Code_Description);
descArray.push(arrayOfJobData[i].Cost_Code_Description);
//console.log(arrayOfJobData[i].Efficency);
effArray.push(arrayOfJobData[i].Efficency);
//Create an array of colors to match with the corresponding efficency % to show a + - relationship in the color scheme
if (arrayOfJobData[i].Efficency < 100) {
colorArray.push("red");
}
else if (arrayOfJobData[i].Efficency >= 100) {
colorArray.push("green");
}
}
//chart data is set and colors selected
var barChartData = {
labels: descArray, //array labels holding the desc for each cost code
datasets: [
{
type: "Bar",
//label: "Efficency %",
fillColor: colorArray,
strokeColor: "black",
pointColor: "rgba(220,220,220,1)",
pointstrokeColor: "white",
drawMathLine: "mean", //using the math functions add-in draw a line with the average %
mathLineStrokeColor: "orange",
data: effArray //array of efficency percent values
}]
}
You can basically build your own array of colors using a method somewhat like was mentioned by the other guy to set only the last color if you want too. The important thing is that you should use ChartNew.js to do what you want with ease.
Here is something more aligned with what you want in colors:
var chartGood = "rgba(50,182,93,0.5)";
var lineChartData = {
labels : ["3/20","3/21","3/22","3/23"],
datasets : [
{
fillColor: ["chartGood ","chartGood ","chartGood ","red"],
strokeColor : "rgba(255,255,255,1)",
pointColor : "rgba(50,182,93,1)",
pointStrokeColor : "#fff",
data : [ 52, 50, 49, 59]
}
]
}
There is also pretty good documentation for ChartNew.js at : https://github.com/FVANCOP/ChartNew.js/wiki/100.Available_options

for the point 1 :
To plot your last bar with different color, you can divide your dataset to different data arrays as follow : the first data array : you replace the last value by null ... and for the second data array, all the values are null except the last one !!
"datasets": [{
fillColor : chartGood,
strokeColor : "rgba(255,255,255,1)",
pointColor : "rgba(50,182,93,1)",
pointStrokeColor : "#fff",
data : [12, 21, 28, 29, 31, 55, 52, 50, 49, null]
},
{
fillColor : chartGood,
strokeColor : "rgba(255,0,0,1)",
pointColor : "rgba(50,182,93,1)",
pointStrokeColor : "#fff",
data : [null, null, null, null, null, null, null, null, null, 59]
}],
For the second point :
If you want that the last label will be an image : this is not possible with Chart.js .... however you can use some (html, css) tricks to place your image over the last label ...
As example you can plot a table below the labels, the number of columns = length of the labels set (in your case = 10)
You set as style = visibility: hidden for each column .. only the last one (visible)
You put a negative margin-top value (to place your image over the label)
Hope this help

Related

Want to change chartjs bar width and on click of bar stroke values from another div should get change

I am using chartjs script to display a bar chart. Displayed the views and visitors bars and overlapped it on one another. Now I want to reduce the width of the resultant bar and on the clickEvent of the bar stroke should another div get changed which is having proper values from a database. I have gone through all queries related with chartjs on StackOverflow, but failed to implement it.
This is what I have tried:
<canvas id="barChart" style="height:5px; width:30px;" ></canvas>
script=>
/* javascript to show bar chart for weekly analysis */
$(function () {
var areaChartData = {
labels : ['Nov-15', 'Nov-22', 'Nov-29', 'Dec-06','Dec-13', 'Dec-19']
datasets: [
{
label : 'Total View Count',
fillColor : '#0087be',
strokeColor : '#0087be',
pointColor : '#0087be',
pointStrokeColor : '#0087be',
pointHighlightFill : '#fff',
pointHighlightStroke: 'rgba(220,220,220,1)',
barPercentage : 0.5,
data : [1, 3, 2,2, 7,2,]
},
{
label : 'Total Visitors Count',
fillColor : 'rgba(60,141,188,0.9)',
strokeColor :'rgba(60,141,188,0.8)',
pointColor : '#3b8bba',
pointStrokeColor : 'rgba(60,141,188,1)',
pointHighlightFill : '#fff',
pointHighlightStroke : 'rgba(60,141,188,1)',
barPercentage : 0.5,
data : [1, 2, 1, 2, 4, 2]
},
],
}
var barChartCanvas = $('#barChart').get(0).getContext('2d')
var barChart = new Chart(barChartCanvas)
var barChartData = areaChartData
barChartData.datasets[1].fillColor = '#004069'
barChartData.datasets[1].strokeColor = '#004069'
barChartData.datasets[1].pointColor = '#004069'
var barChartOptions = {
options: {
scales: {
xAxes: [{
barPercentage: 1,
categoryPercentage: 0.5 / 10 * barChartData.datasets[0].data.length }],
yAxes: [{
ticks: {
beginAtZero:true
}
}],
}
},
//Boolean - Whether the scale should start at
zero, or an order of magnitude down from the lowest value
barStrokeWidth : 2,
barValueSpacing : 15,
barDatasetSpacing : -175,
datasetStroke : true,
barDatasetWidth : -10,
dataPointMaxWidth : 20,
responsive : true,
maintainAspectRatio : true,
}
barChartOptions.datasetFill = false;
barChart.Bar(barChartData, barChartOptions)
});
[bar image shown in picture want to reduce bar stroke width. Two
bars are having different blue color shed][1]

I want to set level with in time interval in array form

I am using angular js and moment.js. Right now I am generating levels for line graph. So I need to set some levels for x axis values. I want to set hours interval in x'axis. Right now I am using these(x'aix) values statically, But now I want to set dynamically with javascript function.
var lineData = { labels: ["0hr", "1hr", "2hr", "3hr", "4hr", "5hr", "6hr"],
datasets: [
{
label: "My Second dataset",
fillColor: "rgba(151,187,205,0.2)",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(151,187,205,1)",
data: [28, 48, 40, 19, 86, 27, 80]
}
]
};
var startFromTime=11;
var endToTime=15;
I want to set time interval from 11 to 15 in labels.
labels: ["0hr", "1hr", "2hr", "3hr", "4hr", "5hr", "6hr"]
can I set assign these value in array form to variable and this variable assign into labels:[1,2,3,4]
You don't need moment.JS for this rather a plain old JavaScript function would do the job.
function getTimeLabels(start) {
var timeStart = start;
var limit = 7;
var resultArr = [];
var counter = 0;
for (var x = 0; x < (timeStart + limit); x++) {
if (x > 24) {
resultArr.push(counter + "hr");
}
resultArr.push(x + "hr");
}
return resultArr;
}
Here you pass the number you wish to start at and it will generate your labels, it also takes into account when x goes over 24 and uses a different counter to finish operations occurring after.
your code modified:
var lineData = { labels: getTimeLabels(0),
datasets: [
{
label: "My Second dataset",
fillColor: "rgba(151,187,205,0.2)",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(151,187,205,1)",
data: [28, 48, 40, 19, 86, 27, 80]
}
]
};
var startFromTime=11;
var endToTime=15;

How to push datasets dynamically for chart.js (bar chart)?

Im using chartjs (bar chart) to display some data.
Im trying to dynamically add data to datasets array but its not working.
for example, lets say I have 2 objects in datasets array, and I dynamically creating this object and trying to push him into datasets (from Chrome console)
after the page loaded and chart is already up.
var e = {
fillColor : "#efefef",
strokeColor : "#efefef",
highlightFill: "#efefef",
highlightStroke: "#efefef",
data : [randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor()]
}
and then
barChartData.datasets.push(e)
I also tried to do window.myBar.update()
but again nothing happend.
Do you know this issue?
Thanks,
I don't think you can use addData to add a series - it's for adding points / bars to existing series.
However you can insert your new series directly into the chart object. With the chart object and new dataset like so
var ctx = document.getElementById("chart").getContext("2d");
var myBarChart = new Chart(ctx).Bar(data);
var myNewDataset = {
label: "My Second dataset",
fillColor: "rgba(187,205,151,0.5)",
strokeColor: "rgba(187,205,151,0.8)",
highlightFill: "rgba(187,205,151,0.75)",
highlightStroke: "rgba(187,205,151,1)",
data: [48, 40, 19, 86, 27, 90, 28]
}
the code to insert a new dataset would be
var bars = []
myNewDataset.data.forEach(function (value, i) {
bars.push(new myBarChart.BarClass({
value: value,
label: myBarChart.datasets[0].bars[i].label,
x: myBarChart.scale.calculateBarX(myBarChart.datasets.length + 1, myBarChart.datasets.length, i),
y: myBarChart.scale.endPoint,
width: myBarChart.scale.calculateBarWidth(myBarChart.datasets.length + 1),
base: myBarChart.scale.endPoint,
strokeColor: myNewDataset.strokeColor,
fillColor: myNewDataset.fillColor
}))
})
myBarChart.datasets.push({
bars: bars
})
myBarChart.update();
Fiddle - http://jsfiddle.net/pvak6rkx/ (inserts the new dataset after 3 seconds)
In version 2.x, you can add (or remove) data to the chart directly and then call update(), e.g.
barChart.data.datasets.push({
label: 'label2',
backgroundColor: '#ff0000',
data: [1,2,3]
});
barChart.update();
Here's a jsfiddle example.
Your missing the data key from your chart instance i.e. barChartData.data.datasets.push(e);
No need for any methods. The js chart object data.datasets key accepts an array of objects. Therefore in your case use :
var e = {
fillColor : "#efefef",
strokeColor : "#efefef",
highlightFill: "#efefef",
highlightStroke: "#efefef",
data : [randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor()]
}
barChartData.data.datasets[] = e; // this will append additional data to your chart
barChartData.update();
Just make sure that barChartData is an instance of your js chart.

Change label font color for a line chart using Chart.js

I'm using Chart.js to generate some charts. The line chart requires labels. I can't seem to figure out a way to change the color of those labels.
var chartGood = "rgba(50,182,93,0.5)";
var lineChartData = {
labels : ["3/14","3/15","3/16","3/17","3/18","3/19","3/20","3/21","3/22","3/23"],
datasets : [
{
fillColor : chartGood,
strokeColor : "rgba(255,255,255,1)",
pointColor : "rgba(50,182,93,1)",
pointStrokeColor : "#fff",
data : [12, 21, 28, 29, 31, 55, 52, 50, 49, 59]
}
]
}
var myLine = new Chart(document.getElementById("cpu-chart").getContext("2d")).Line(lineChartData);
I've tried:
labelColor : "#fff",
legend : {
font : {
color : "#fff"
}
}
label : {
font : {
color : "#fff"
}
}
And a few other combinations but nothing seems to work. I thought I found what I was looking for in the docs
//String - Scale label font colour
scaleFontColor : "#fff",
but that didn't solve my issue either.
Yes, the scaleFontColor option changes the color of labels.
You probably tried to add it to the data object, that's why it didn't work. Actually it should be passed as a second parameter of the Line function like this:
var myLine = new Chart(document.getElementById("cpu-chart").getContext("2d"))
.Line(lineChartData, { scaleFontColor: "#ff0000" });
Edit:
Similarly, to change the font size use scaleFontSize.
Example:
scaleFontSize: 16

creating a multidimensional array and fill it

I want to draw a graph on my page and would like to use Charts.js. The Documentation on
http://www.chartjs.org/docs/
says that the Chars I want to create needs an Array of Labels like this:
var data = {
labels : ["January","February","March","April","May","June","July"],
datasets : [
{
fillColor : "rgba(220,220,220,0.5)",
strokeColor : "rgba(220,220,220,1)",
pointColor : "rgba(220,220,220,1)",
pointStrokeColor : "#fff",
data : [65,59,90,81,56,55,40]
},
{
fillColor : "rgba(151,187,205,0.5)",
strokeColor : "rgba(151,187,205,1)",
pointColor : "rgba(151,187,205,1)",
pointStrokeColor : "#fff",
data : [28,48,40,19,96,27,100]
}
]
}
Question: How do I create such a Array?
Question: How can I fill this array with the Input of a Textfield?
Thanks!
Jan
A1) The way you have written is the right way to create arrays in javascript
A2) Suppose you have a textfield with id='month'. You can access its value like this:
var month = document.getElementById('month').value
Next you can create an array var label = []; and add the data from the text field by pushing in the array. i.e label.push(month)
Once you have populated the array for label, you can assign this array to property labels of your data object.
Similarly to assign values to data, create an array var values = []; var values2 = []; Now populate the values and values2 array by pushing values into it.
var label = [];
var values = [];
var values2 = [];
var month = document.getElementById('month').value;
//keep on doing this for all input fields
label.push(month)
//similarly push data into values and values2.
//Now build your structure for chart as follows:
var data = {
labels : label,
datasets : [
{
fillColor : "rgba(220,220,220,0.5)",
strokeColor : "rgba(220,220,220,1)",
pointColor : "rgba(220,220,220,1)",
pointStrokeColor : "#fff",
data : values
},
{
fillColor : "rgba(151,187,205,0.5)",
strokeColor : "rgba(151,187,205,1)",
pointColor : "rgba(151,187,205,1)",
pointStrokeColor : "#fff",
data : values2
}
]
}
Here label , values and values2 are the arrays you got from your textfields.
Hope this helps.
define something like this{
data = {
label:""
fields: [],
};
push the value
data.fields.push({
label: "label",
value: "your constructed value"
});

Categories