How to get the dataset value in table using Jquery - javascript

I was trying to get the label and data value from the following
var barChartData = {
labels: Months,
datasets: [{
label: 'Dataset 1',
backgroundColor: "#09a",
data: [5, 10, 15, 20, 25, 30, 35]
}]
};
I tried using alert(JSON.stringify(barChartData.datasets.data)); but I got output as undefined. Please help me to find out this .

Like Sachin K wrote in the comment.
You forget that datasets is an array containing an object.
Therefor you need
alert(JSON.stringify(barChartData.datasets[0].data))
With the [0] you specify that you want the value from the first element in the array (array's are zero based)

Try this approach..
var barChartData = {
labels: 'Months',
datasets: [{
label: 'Dataset 1',
backgroundColor: "#09a",
data: [5, 10, 15, 20, 25, 30, 35]
}]
};
//For multiple dataset
var data = []; label = [];
barChartData.datasets.map(function(dt) {
data.push(dt.data);
label.push(dt.label);
})
//Single datasets
var data1 = barChartData.datasets[0].data;
var label1 = barChartData.datasets[0].label;
console.log(data, label, data1, label1);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Related

Set a limit / max number for legends

Lets say I have a Donut chart with 5 items in data like this
const data = {
labels: ['E-commerce', 'Enterprise', 'Green', 'Grey', 'Purple'],
datasets: [
{
label: '# of Votes',
data: [12, 19, 3, 5, 3],
backgroundColor: ['#C07CC3', '#9C3848', '#9DDBAD', '#ADA8B6', '#606EDA'],
borderWidth: 1,
},
],
}
I don't want it to show all the legends as I don't have space or whatever reason
How can I hide the Green and purple in this example?
I mean only from legends not from chart
I see two easy ways, how you could approach this problem:
(I personally I would use the second option below, it is more configurable, but it needs just abit of coding)
You can simply delete the labels you want to delete from the labels- array, and they won't show up in the legend.
But keep in mind you would have to change the order of the data and backgroundColor arrays, to match this change.
Here a short demo:
const data = {
labels: ['E-commerce', 'Enterprise', 'Grey'], // <-- just remove the unwanted labels
datasets: [{
data: [12, 19, 5, 3, 3], // <-- reorder
backgroundColor: ['#C07CC3', '#9C3848', '#ADA8B6', '#9DDBAD', '#606EDA'], // <-- reorder
borderWidth: 1,
}],
};
const config = {
type: 'doughnut',
data: data,
options: {
maintainAspectRatio: false,
plugins: {
legend: {
position: 'right',
labels: {
usePointStyle: true,
},
}
},
}
};
new Chart(
document.getElementById('chart'),
config
);
<script src="//cdn.jsdelivr.net/npm/chart.js"></script>
<div class="chart" style="height:184px; width:350px;">
<canvas id="chart" ></canvas>
</div>
Better and cleaner (but some coding is needed), you can filter out label-items, you don't want to display, with the function array filter. (details can be found in the documentation)
UPDATED Alternative Version Demo:
here only the Top 3 labels (limiting the amount of labels with the variable maxLabelsToShow) will be shown (sort order is descending, but changing this is would be easy)
function getLabelsOnlyTopX(num, data, labels){
let selectedLabels = []
//we don't want to alter the order
let helperData = [...data];
//sort in descending order
helperData.sort( (a,b) => b-a);
//get top X Values
helperData = helperData.slice(0, num);
//get index for the data
let indexes = data.map( (value, index) => ({value,index}) ).filter(item => helperData.some(n1 => n1 == item.value))
//slecet only labels with the correct index
selectedLabels = labels.filter((value, index) => indexes.some( n => n.index == index))
// just be sure that a maximum of num labels are sent
return selectedLabels.slice(0, num);
}
let maxLabelsToShow = 3;
let serverData = [12, 19, 3, 5, 3]
let labels = ['E-commerce', 'Enterprise', 'Green', 'Grey', 'Purple'];
// Calling the newly created function
let showOnly = getLabelsOnlyTopX(maxLabelsToShow, serverData, labels);
const data = {
labels: labels,
datasets: [{
data: serverData,
backgroundColor: ['#C07CC3', '#9C3848',
'#9DDBAD', '#ADA8B6', '#606EDA'],
borderWidth: 1,
}],
};
const config = {
type: 'doughnut',
data: data,
options: {
maintainAspectRatio: false,
plugins: {
legend: {
position: 'right',
labels: {
usePointStyle: true,
/* FILTER function */
filter: function(item, chart) {
return showOnly.indexOf( item.text) > -1;
}
},
}
},
}
};
new Chart(
document.getElementById('chart'),
config
);
<script src="//cdn.jsdelivr.net/npm/chart.js"></script>
<div class="chart" style="height:184px; width:350px;">
<canvas id="chart" ></canvas>
</div>

Chart.js show negative value in the top half

I am creating a chart.js which has both positive and negative values
but how to make all values be on the top half
(ignore the if it's positive or negative when drawing but keep the label)
var tax_dash = new Chart(ctx_tax_dash, {
type: "bar",
data: {
labels: lable_set,
datasets: [{
label: "Tax in",
data: total_tax_in_t_data__year,
backgroundColor: '#0fd96d',
// borderColor: sales_t_data,
borderWidth: 1,
},
{
label: "Tax out",
data: total_tax_out_t_data__year,
backgroundColor: '#0f81d9',
// borderColor: sales_t_data,
borderWidth: 1,
},
{
label: "Net VAT",
data: total_tax_in_out_t_data__year,
backgroundColor: '#d96a0f',
// borderColor: sales_t_data,
borderWidth: 1,
},
],
},
options: {
legend: {
display: true,
}
},
});
EDIT
what I am trying to do
possible solution: is (multi-axis) dual y axis.multi-axis example
~ issue: how to flip the axis so that the -100 be to the top and 0 be on the bottom
~ issue: how to split the data set base on the (sign)
OR
possible solution 2 : make all variable positive
#Gkiokan> solution: use the popup modifier to the showing values with negative
~ ++ issue: how the function will know if the value is negative
~ issue: the user needs to know that this value is negative in the label
Solution 2
I did it this morning user what Math.abs from #Lawrence comment and "popup modifier" from #Gkiokan comment as well as this jsfiddle
Thank you very much for the help. Chatting with smarter people rubs off on you :)
total_tax_in_t_data_portal_month_year = [Math.abs(12),Math.abs(-234),Math.abs(234)];
total_tax_in_t_data_portal_month_year_sign = [12,-234,234];
var tax_dash_portal = new Chart(ctx_tax_dash_portal, {
type: "bar",
data: {
labels: lable_set,
datasets: [
{
label: "VAT In",
data: total_tax_in_t_data_portal_month_year,
sign: total_tax_in_t_data_portal_month_year_sign,
backgroundColor: "#0fd96d",
// borderColor: sales_t_data,
borderWidth: 1,
},
{
label: "VAT Out",
data: total_tax_out_t_data_portal_month_year,
sign: total_tax_out_t_data_portal_month_year_sign,
backgroundColor: "#0f81d9",
// borderColor: sales_t_data,
borderWidth: 1,
},
{
label: "Net VAT",
data: total_tax_t_data_portal_month_year,
sign: total_tax_t_data_portal_month_year_sign,
backgroundColor: "#d96a0f",
// borderColor: sales_t_data,
borderWidth: 1,
},
],
},
options: {
legend: {
display: true,
},
tooltips: {
enabled: true,
callbacks: {
label: function (tooltipItem, data) {
var label = data.labels[tooltipItem.index];
var val = data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
var sign = data.datasets[tooltipItem.datasetIndex].sign[tooltipItem.index];
if(sign < 0){
return label + ": -" + val;
}else{
return label + ': ' + val;
}
}
}
}
},
});
total_tax_in_t_data_portal_month_year is an example as the values come from a function
Math.abs is used to remove the negative sign
then I added sign to the datasets for essay access
tooltips callbacks is called on every variable so I added the if statement there
to add - if sign < 0 and do nothing if not
In my opinion you can have a data Set to save the orginal Data and the modified
Data and then use the values as you need. You can not trust the value characters. My solution will work kind cross over as you have control over both values.
I've made a jsfiddle for you which demonstrates the orginal Data vs modified Data usage. Please click first on Modify Data which will then map the data, so you can see the work in progress. In your case you would modify the data before calling the charts.
Actually you will need just a couple of methods as followed:
updateItemValues to modify the negative values and put it to the other object
tooltipCallback callback for the tooltip to use the mapped orginal value
let data = {
modified: false,
orginalData : {
'tax_in' : [10, 20, -30, -40, -100, -50],
'tax_out' : [-10, 10, 20, 10, -40, -70],
'net_vat' : [-50, -9, -40, -20, -10, -90],
},
modifiedData : {
// this modified data will be calculated before putting it in the charts
// for demo purpose we will just copy the values for now.
'tax_in' : [10, 20, -30, -40, -100, -50],
'tax_out' : [-10, 10, 20, 10, -40, -70],
'net_vat' : [-50, -9, -40, -20, -10, -90],
},
updateModifiedData(){
// loop though the orginal Data
Object.keys(this.orginalData).forEach( (item, indexx) => {
console.log('modifying item chart data for: ', item)
this.updateItemValues(item)
})
this.modified = true
document.getElementById('status').innerHTML = 'modified'
},
updateItemValues(dataKey){
let temp = []
this.orginalData[dataKey].forEach( (value, index) => {
console.log('- validating ', dataKey, 'index: ', index, '; value: ', value)
// if we have a negative value, just multiply by -1 so get it positive
if(value <= 0){
value = value * -1
}
// add to the temporary variable
temp.push(value)
})
// put the modified data to some place to have it saved
this.modifiedData[dataKey] = temp
console.log('-- final data modded ', temp)
},
tooltipCallback(tooltipItem, chartData) {
// find reference values
let index = tooltipItem.index
let dataIndex = tooltipItem.datasetIndex
// find the name of dataset
let key = chartData.datasets[dataIndex].name
// validate or whatever with the orginal value
let orginalValueOfItem = data.orginalData[key][index]
let modifiedValueOfItem = data.modifiedData[key][index]
// Modify your final tooltip here
return 'Orginal Value: ' + orginalValueOfItem + ' ; Modified Value: ' + modifiedValueOfItem
}
}
How can you use this solution?
Pretty simple.
Copy that data Object in your code.
Fill the data.orginalData value with your orginal charts data based on key
example data.orginalData.tax_in = [...]
In your datasets add name property with the corresponding key
Extend the Charts options with the tooltipCallback
Call data.updateModifiedData() to get the modified data
Checkout the jsFiddle for reference if you need to.
Have fun.

Set state of nested Array object?

How can I setstate of value object inside datasets.I tried to set the state by below approach but got the error.
this.setState({ datasets: { ...this.state.datasets, value: labels} });
//code for state
this.state = {
labels: ['January', 'February', 'March',
'April', 'May'],
datasets: [
{
label: 'Rainfall',
backgroundColor: 'rgba(75,192,192,1)',
borderColor: 'rgba(0,0,0,1)',
borderWidth: 2,
value: [65, 59, 80, 81, 56],
}
]
}
In your state, datasets is an array. However, in the setstate call you are destructuring it as an object. You should do this to get it to work:
this.setState({ datasets: [ {...this.state.datasets[0], value: labels }] });
Not sure I'm totally clear on what you are trying to do, but I think the issue is that state.datasets is an array of objects, and you aren't addressing a particular element in the array. You may want to try something along these lines:
this.setState( state => {
let newData = state.datasets[0]
newData.value = labels
return newData
}

Storing Highcharts in array issue

I am plotting a number of highcharts dynamically in a loop and pushing each highchart to an array. So that while clicking on an external button, I can export the charts. But while pushing charts to array, only the last entry is properly set with options.
i had a reference to a fiddle that suggests to clone the options. [https://jsfiddle.net/ndb21y1w/][2]
https://www.highcharts.com/forum/viewtopic.php?t=38574
The fiddle have same series data plotted on all the charts. How to solve this if the data is different for each chart populated. Thanks for any help in advance.
Adding more clarity to question :
The data is populated dynamically in loop. My code logic is like:
counter i;
setInterval(function() {
//logic to populated data...
//It is a multiline chart, so three sets of arrays are populated.
//filling data1[], data2[] and data3[] .
drawChart(data1, data2, data3);
if(condition true) clearInterval();
i++;
});
drawChart(data1, data2, data3) {
var chart = new Highcharts.Chart({
title: {
text: "title",
},
xAxis: {
categories: [1,2,3,4...],
},
series: [{
type: 'line',
data: data1,
}, {
type: 'line',
data: data2,
}, {
type: 'line',
data: data3,
},
});
chartArray.push(chart);
}
This chartArray is where I mentioned to get the last entry only properly.
To create a chart you have to pass an HTML element that will be a chart container. In your code that what's missing. Check the demo I have prepared to reproduce this issue: https://jsfiddle.net/BlackLabel/c60y1t2v/
Code:
var chartArray = [],
counter = 1,
dataArr = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
],
containers = document.getElementById('containers');
function drawChart(data) {
var cnt = document.createElement('div'),
cntId = 'container' + counter++,
chart;
cnt.setAttribute('id', cntId);
containers.appendChild(cnt);
chart = new Highcharts.Chart(cntId, {
title: {
text: "title",
},
xAxis: {
categories: [1, 2, 3, 4],
},
series: [{
type: 'line',
data: data,
}]
});
return chart;
}
dataArr.forEach(function(data) {
var chart = drawChart(data);
chartArray.push(chart);
});
You need to define options each time you use a new chart. Reinitialize the OriginalOptions every time you create a new chart.
const options = [...Array(5)].map(() => {
const originalOptions = {
series: [{
data: [], // some random data
type: 'column'
}]
}
return Object.assign(originalOptions)
})
Fiddle
Updated:
For dynamically repopulating the chart, you have to initialize an empty chart and then add new series + redraw whenever your data is populated.
Your redraw function will look something like this:
var i = 0;
var data = [];
var chart = new Highcharts.Chart('container',{
series: []
});
var interval = setInterval(function() {
i++;
data[i] = [i*10 + 1, i*10+2, i*10+3];
drawChart(data[i]);
if(i > 2) clearInterval(interval);
},1000);
function drawChart(data) {
var series = {
type: 'line',
data: data
}
chart.addSeries(series, false);
chart.redraw();
}
See Updated Fiddle
To Print HTML as PDF you can use this software "wkhtmltopdf"
in Linux you need to use this command :
sudo apt-get install wkhtmltopdf
There are many library based on "wkhtmltopdf" in many languages so you can use it.
Library for PHP : https://github.com/mikehaertl/phpwkhtmltopdf
Store chart options in Array then map over to Initialize Highchart for each options.
var chartArray = [];
function drawChart(data1, data2, data3, i) {
// Create container for charts
const el = document.createElement('div');
document.body.appendChild(el).setAttribute("id", "container"+i);
// Create charts
var chart = new Highcharts.chart(el, {
series: [{
type: 'line',
data: data1,
}, {
type: 'line',
data: data2,
}, {
type: 'line',
data: data3,
}]
});
chartArray.push(chart);
console.log(chartArray);
}
var counter = 0;
var delayTime = 2000;
var timer = setInterval(function(){
var data1 = [30, 70, 50];
var data2 = [40, 70, 60];
var data3 = [10, 90, 20];
drawChart(data1, data2, data3, counter);
if(counter == 2){
clearInterval(timer);
}
counter++;
},delayTime);
<script src="https://code.highcharts.com/highcharts.js"></script>

how do you set the yaxis values in highcharts

my json data looks like this:
[
[1362027751000, 1362027781000, 1362027811000, 1362027841000, 1362027871000, 1362027901000, 1362027931000, 1362027961000, 1362027991000, 1362028021000 ],
[ 66, 72, 69, 72, 69, 68, 71, 73, 63, 57 ],
[ 50, 5, 67, 72, 34, 100, 10, 100, 23, 56 ]
]
the first row is date in epoch time, the second is cpu utilization and the third is the memory utilization. I would like to create time series chart, date being on xaxis and CPU and mmeory data on yaxis with different lines. How would I accomplish this given the data provided with the json external file. I see examples where that the in the javascript but this is really not realistics. Any help is greatly appriciated.
I attempted to the following where I wanted to split cpu and memory. I am not getting any results back, empty page. Is this the way to address this or there are other ways to draw multiple variables in one chart?
my javascript looks like this:
<script type="text/javascript">
$(document).ready(function() {
var options = {
chart: {
renderTo: 'container',
type: 'area'
},
xAxis: {
type: 'datetime'
},
//series: [{}]
series: [{{
type: 'spline',
name: 'CPU',
data: cpu
}, {
type: 'spline',
name: 'memory',
data: memory
}}]
};
$.getJSON('data.json', function(data) {
options.series[0].data = data;
var cpu = [];
var memory=[];
for(i=0; i< data.length, i++) {
for(j=0; j<data[i].length; j++){
alert(data[i].length);
cpu.push([
data[i][j], // the date
data[1][j] // the cpu
]);
memory.push([
data[i][j], // the date
data[2][j] // the volume
])
}
}
var chart = new Highcharts.Chart(options);
//alert(JSON.stringify(data, null, 4));
});
});
</script>
the charts does not look right. It looks like xaxis and yaxix are both reporting the date value. Is there a way to set the yaxis values?
My preference is to send in the data for a series as [x,y] pairs. So your data would look like:
[
[1362027751000, 66], [1362027781000, 72], [1362027811000, 69], [1362027841000, 72], [1362027871000, 69], [1362027901000, 68], [1362027931000, 71], [1362027961000, 73], [1362027991000, 63], [1362028021000, 57 ]
]
and:
[
[1362027751000, 50], [1362027781000, 5], [1362027811000, 67], [1362027841000, 72], [1362027871000, 34], [1362027901000, 100], [1362027931000, 10], [1362027961000, 100], [1362027991000, 23], [1362028021000, 23]
]
You would need to send this in as 2 different series.data blocks.
for(i=0; i< data.length-2; i++) {
for(j=0; j<data[i].length; j++){
cpu.push([
data[i][j], // the date
data[1][j] // the cpu
]);
memory.push([
data[i][j], // the date
data[2][j] // the volume
])
}
}

Categories

Resources