How to add a second series in highcharts [duplicate] - javascript

This question already has an answer here:
Retrieving JSON data for Highcharts with multiple series?
(1 answer)
Closed 2 years ago.
I have been trying to display the second value of my json file in highcharts for two days.
my json file:
[[1591518187000,17.3,12.7],[1591518135000,17.2,12.7]...[1591518074000,17.2,12.6],[1591518020000,17.2,12.7]]
The time and the first value are displayed correctly.
my script in php file:
<script type="text/javascript">
var chart;
function requestData() {
$.getJSON('../****json.php',
function (data) {
var series = chart.series[0];
series.setData(data);
}
);
}
(document).ready(function() {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
defaultSeriesType: 'line',
marginRight: 10,
marginBottom: 25,
events: { load: requestData }
},
.....
series: [{
name: 'Temperatur',
data: []
},
{
name: "Taupunkt",
data: []
......
</script>
Does anyone happen to have a way of drawing the second values ​​as a line?

You could process your data and make two data sets for both series. Both data sets will have the same x values, but different y values. The code could look something like this:
$.getJSON('../****json.php',
function (data) {
var dataSetOne = [],
dataSetTwo = [];
data.forEach(function(point) {
dataSetOne.push([point[0], point[1]);
dataSetTwo.push([point[0], point[2]);
});
chart.series[0].setData(dataSetOne);
chart.series[1].setData(dataSetTwo);
}
);

Related

Create Multiple charts using c3

I have an API where am sourcing the data from.
Html snippet:
<div id='chart'></div>
And the JavaScript:
function PlotChart(chart_name,type,columns){
var chart = c3.generate({
bindto: chart_name,
data: {
columns:columns,
type: type
},
size: {
width: 355.05
}
});
}
Using the above JavaScript as a skeleton for the charts, how do i pass in the API data into another function so that i can call the PlotChart() to create the multiple charts.
Create chart here:
function FirstOfTheManyCharts(){
//Consume api data here
plotChart('#chart', 'pie', columns);
}
function FirstOfTheManyCharts(){
//Consume api data here
function PlotChart(chart_name,type,columns){
var chart = c3.generate({
bindto: chart_name,
data: {
columns:columns,
type: type
},
size: {
width: 355.05
}
});
}
plotChart('#chart', 'pie', columns);
}

Chart js old chart data not clearing

This question has been asked many times and I went through most of them but non of them helped me finding a solution.
I am generating couple of bar charts using a for loop as a part of reporting functionality.
I am using node.js with Express Handlebars.
My page looks like:
<div class="row report-charts">
<div class="col-md-12">
{{#buildings}}
<div class="col-md-6">
<h4>{{Name}}</h4>
<canvas id="{{idBuildings}}" width="200" height="80"></canvas>
</div>
{{/buildings}}
</div>
</div>
My js code looks like:
$('.case-report-btn').click(function(){
$.ajax({
type: 'post',
url: '/reports/cases/filter',
data : {
StartDate : $('.start-ms-time-hidden').val(),
EndDate : $('.end-ms-time-hidden').val(),
ReportKey : $('.cases-filter-type').val()
},
dataType: 'json',
success: function(res) {
$('.report-charts').show();
for(key in res) {
var innerObj = res[key]; //gives the inner obj
var ctx = document.getElementById(key); //the idBuildings
var labels = [];
var data = [];
var buildingName = innerObj.Name;
for(innerKey in innerObj) {
if(innerKey != 'Name' && innerKey != 'Total') {
labels.push(innerKey);
data.push(innerObj[innerKey]);
}
}
var options = {
type: 'bar',
data: {
labels: labels,
datasets: [{
label: buildingName,
data: data,
backgroundColor: 'rgba(255, 99, 132, 0.2)',
borderColor: 'rgba(255,99,132,1)',
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true,
fixedStepSize: 1
}
}]
}
}
}
var myChart = new Chart(ctx, options);
}
$('#pleaseWaitDialog').modal('hide');
},
error: function(err) {
$('#pleaseWaitDialog').modal('hide');
bootbox.alert('Error: ' + err);
}
});
});
So basically, I am using for loop to generate multiple charts on the page. Inside the loop I declared the chart variable, every time I change the report parameters and hit the button, the new chart is generated. But when I hover over it, the old one still shows up.
Now I am not sure where I should be putting the myChart.destroy() or myChart.clear() methods. I also tried moving the myChart declaration outside the for loop but it didn't help either.
Any suggestions on how to handle this?
I think there are a few ways to do it. You can update your chart data if the chart already exist. Here two functions you can use:
function removeData(chart) {
chart.data.labels.pop();
chart.data.datasets.forEach((dataset) => {
dataset.data.pop();
});
chart.update();
}
function addData(chart, label, data) {
chart.data.labels.push(label);
chart.data.datasets.forEach((dataset) => {
dataset.data.push(data);
});
chart.update();
}
First you have to remove all your data and then add the new data.
If you want to destroy the chart and create it again you have to save your variable as global. To do this you have yo declare your variable like window.myChart and then before create the new chart, something like this:
if (window.myChart) window.myChart.destroy();
window.myChart = new Chart(ctx, options);
Another way you can try is removing your canvas and creating another one. Something like this:
$('#your_canvas').remove();
$('#your_canvas_father').append('<canvas id="your_canvas"></canvas>');

how do i set json data set as labels for graph plot with c3.js

I have a line graph generated with c3.js with json data
the current chart is very simple
var chart = c3.generate({
bindto: '.balanceChart',
data: {
url: '/data',
mimeType:'json'
}
});
json data:
{
data1: [1000,1240,1270,1250,1280]
data2: [1000,240,30,-20,30]
}
chart looks good and is there
but it is currently plotting both sets of data
what i would like is for data2 to be the tooltip value of the plot
You can hide data2 from displaying like so
data: {
...
hide: ['data2']
}
From http://c3js.org/reference.html#data-hide
And use tooltip.format.value to change the tooltip display
tooltip: {
format: {
value: function (value, ratio, id, index) {
// return chart.data.values("data2")[index]; // if still wanting to use data2
// or get rid of data2 completely using this
var vals = chart.data.values(id); // id will be 'data1', vals will then be data1 array
return vals[index] - (index === 0 ? 0 : vals[index - 1]);
}
}
}
http://c3js.org/reference.html#tooltip-format-value
tooltip.format.title and tooltip.format.name will also be useful here to communicate to a user the value isn't actually that of data1 (maybe just changing the title to "Delta Data1")

Update HighCharts chart when AJAX Updates my data on my page

I have a Page where I have some Project Stats based on different Project Task Statuses. On this page I use AJAX to update my Stat values as they change.
I am now trying to integrate a Highcharts bar chart/graph and I need to update it;s chart when my data changes.
There is a JSFiddle here showing the chart I am experimenting with now http://jsfiddle.net/jasondavis/9dr345og/1/
$(function () {
$('#container').highcharts({
data: {
table: document.getElementById('datatable')
},
chart: {
type: 'column'
},
title: {
text: 'Project Stats'
},
yAxis: {
allowDecimals: false,
title: {
text: 'Total'
}
},
tooltip: {
formatter: function () {
return '<b>' + this.series.name + '</b><br/>' +
this.point.y + ' ' + this.point.name.toLowerCase();
}
},
subtitle: {
enabled: true,
text: 'Project Stats'
},
legend: {
enabled: false
},
exporting: {
enabled: false
},
credits: {
enabled: false
}
});
// Button Click to Simulate my Data updating. This increments the Completed Tasks bar by 1 on each click.
$(".update").click(function() {
var completedVal = $('#completed').text();
++completedVal
$('#completed').text(completedVal)
});
});
So this example is getting the data from a Table but I do not have to use this method, I could also set it with JavaScript if needed.
I just need to figure out how I can update all these values on the fly as my real live page updates my task stat values using AJAX so I would like this chart to update live as well.
Any help on how to make it update? When my AJAX code is ran, I could call some JavaScript at that point if there is a function that rebuilds the chart?
I would drop the use of the table, especially since it looks like you are building it just for highcharts to consume it. Instead return your data via AJAX as a Highcharts series object. and then use the Series.setData method to update your plot. This would be the right way to do it.
If you really want to use the table, you could query out the data and still use setData (this is what Highcharts is doing for you under the hood). Updated fiddle.
$(".update").click(function() {
var completedVal = $('#completed').text();
++completedVal;
$('#completed').text(completedVal);
// get y values
var yValues = $.map($('#datatable tr td'),function(i){return parseFloat($(i).text());});
// set data
Highcharts.charts[0].series[0].setData(yValues);
});

Using Angular.JS to bind a JSON value to a Syncfusion Circular gauge

I am working on a project using Syncfusion Javascript gauge control to display a weekly pay bonus. The data is stored on a SharePoint list. I wrote a javascript to convert the sharepoint list from XML to JSON.
<script type="text/javascript">
$ajax({
url: "/_api/web/lists/GetByTitle('bonusEntry')/items?$orderby=Date desc&$filter=Department eq 'Meltshop'&$top=1",
type: "GET",
headers: {
"accept":"application/json;odata=verbose",
},
success: function (data) {
var newMsBonus = "";
for(i=0; i < data.d.results.length; i++){
newMsBonus = newMsBonus + "<div>" + data.d.results[i].ACrew + "</div>";
}
$('#oDataanalysisScoreBoard').html(newMsBonus);
},
error: function (error) {
alert("error: " + JSON.stringify(error));
}
})
Then the value is placed in this Div.
<div id="oDataanalysisScoreBoard"></div>
Basically what I would like to do is bind the data to the Syncfusion control which is set up like this:
$("#CircularGauge1").ejCircularGauge({
width: 500,
height: 500,
backgroundColor: "#3D3F3D",
readOnly: false,
scales: [{
ticks: [{
type: "major",
distanceFromScale: 70,
height: 20,
width: 3,
color: "#ffffff"
}, {
type: "minor",
height: 12,
width: 1,
distanceFromScale: 70,
color: "#ffffff"
}],
}]
});
Then the gauge is created inside this:
<div id="CircularGauge1"></div>
The gauge will build but I cannot get the gauge to recieve the value.
If anyone has any ideas on how I can make this work or things I'm doing I would greatly appreciate any input! Thanks everyone!
EDIT:
The synfusion software creates a gauge and changes the needle based on a number value thats given to it. My ajax call pulls a number entered into a Sharepoint list and then displays that in a div.
In the above code snippet you mentioned the passing value as “String”. If you pass the string value to the loop it will concatenate as string value only. But we need to pass the integer value to the Circular Gauge properties(width, height, distancefromscale) to take effect. Hence, change the code snippet with the following.
$.ajax({
url: "/Gauge/GetData",
type: "POST",
success: function (data) {
var newMsBonus = 0;
for (i = 0; i < data.length; i++) {
newMsBonus = newMsBonus + data[i].MajorDistanceFromScale; // Here i have used the MajorScale distanceFromScale value for the demo
}
$('#oDataanalysisScoreBoard').html(newMsBonus);
},
failure: function (error) {
alert("no data available");
}
});
And we have prepared the sample to meet your requirement with the MVC application including the “.mdf” database. We have created the table called “GaugeData” and added the two record. And using the “$.ajax” called the action method “GetData” and received the “JSON” data from the controller. Refer the following code snippet.
View Page:
$.ajax({
url: "/Gauge/GetData",
type: "POST",
success: function (data) {},
failure: function (error) {
}
});
Controller Page:
public class GaugeController : Controller
{
GaugeDataDataContext db = new GaugeDataDataContext();
public JsonResult GetData()
{
IEnumerable data = db.GaugeDatas.Take(500);
return Json(data, JsonRequestBehavior.AllowGet);
}
}
And then assigned the calculated value to the gauge property. Here, I have used the “MajorDistanceFromScale” value read from the database record and assigned to the gauge properties. Refer the following coding snippet.
var distanceValue = parseInt($("#oDataanalysisScoreBoard")[0].innerHTML);
$("#CircularGauge1").ejCircularGauge({
width: 500,
height: 500,
backgroundColor: "#3D3F3D",
readOnly: false,
scales: [{
ticks: [{
type: "major",
distanceFromScale: distanceValue,
height: 20,
width: 3,
color: "#ffffff"
}, {
type: "minor",
height: 12,
width: 1,
distanceFromScale: 70,
color: "#ffffff"
}],
}]
});
And also please refer the below attached sample for more reference.
GaugeListSample

Categories