include two series from database in a highchart chart - ajax

I would like to include a series to my existing chart.
daytime = new Highcharts.Chart({
chart: {
renderTo: 'daytime_div',
defaultSeriesType: 'areaspline',
events: {
load: getData()
}
},
plotOptions: {
series: {
fillOpacity: 0.1,
lineWidth: 4,
marker: {
radius: 5,
lineWidth: 1,
lineColor: "#FFFFFF"
}
}
},
tooltip: {
formatter: function () {
var s = [];
$.each(this.points, function (i, point) {
s.push('<span style="font-size:10px;">' + point.key + '</span><br/><strong>' + point.series.name + '</strong> : ' + point.y + '</span>');
});
return s.join('<br/>');
},
shared: true,
useHTML: true
},
credits: false,
title: false,
exporting: false,
legend: {
itemDistance: 50,
itemStyle: {
color: '#333'
}
},
xAxis: {
labels: {
staggerLines: 2
}
},
yAxis: {
gridLineColor: "#e7e7e7",
title: {
text: ''
},
labels: {
x: 15,
y: 15,
style: {
color: "#999999",
fontSize: "10px"
}
},
},
series: [{
name: 'Daily',
color: "#b18eda",
data: ddata
}]
});
function getData() {
$.ajax({
url: '...',
type: "POST",
contentType: "application/json; charset=utf-8",
data: data,
success: function (f) {
var categories = [];
var series_data = [];
$.each(f.d, function (i, e) {
categories.push(e.hour);
series_data.push(parseInt(e.numa));
});
daytime.xAxis[0].setCategories(categories);
daytime.series[0].setData(series_data);
},
cache: false
});
}
The data I get from my database looks like this:
hour, numa
12 AM 1
1 AM 0
2 AM 0
3 AM 0
4 AM 0
This shows one line in the chart which is fine. I would like to add a second line that will come from a different query. The second line data will look like:
hour, numa
12 AM 0
1 AM 12
2 AM 3
3 AM 2
4 AM 2
Does anyone knows how could I include this into my second series? I have seen the sample in high charts on how to add more series. Static is pretty simple but getting the data dynamically make it more complicated to figure it out.
I am trying to find a way to add 2 series to my getData() function. Any idea will be appreciate it thanks.

It is explained clearly in the fiddle of the document which you shared on how to add multiple series.
series: [{
name: 'Tokyo',
data: [7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6]
}, {
name: 'New York',
data: [-0.2, 0.8, 5.7, 11.3, 17.0, 22.0, 24.8, 24.1, 20.1, 14.1, 8.6, 2.5]
}, {
name: 'Berlin',
data: [-0.9, 0.6, 3.5, 8.4, 13.5, 17.0, 18.6, 17.9, 14.3, 9.0, 3.9, 1.0]
}, {
name: 'London',
data: [3.9, 4.2, 5.7, 8.5, 11.9, 15.2, 17.0, 16.6, 14.2, 10.3, 6.6, 4.8]
}]
You can pass multiple series in array and the chart can be generated.
EDIT-1
If data from different series use this fiddle.
var myComments=["First input","second comment","another comment","last comment"]
var dataValues = [29.9, 71.5, 194.1, 129.2];
var dataValues2 = [194.1, 95.6, 194.1, 29.9];
var categories = ['Jan', 'Feb', 'Mar', 'Apr'];
var n=['tooltip1','tooltip2','tooltip3','tooltip4'];
$(function () {
$('#container').highcharts({
chart: {},
tooltip: {
formatter: function () {
var serieI = this.series.index;
var index = categories.indexOf(this.x);
var comment = myComments[index];
return '-->'+comment;
}
},
xAxis: {
categories: categories
},
series: [{
data: dataValues
}, {
data: dataValues2
}]
});
});
which results in the below graph

Well you can use $.when() and load there all your ajax and in $.then() initialise chart. Second solution is prepare your query to database and return all data in single json.

Related

How to configure linear labels in Time Cartesian Chartjs?

I need to show labels on the x-axis every 2 hours (0h, 2h, 4h...). What am I missing?
<script>
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'line',
data: {
//labels: ['0h', '2h', '4h', '6h', '8h', '10h', '12h', '14h', '16h', '18h', '20h', '22h', '0h'],
datasets: [{
label: 'AAA1111',
//xAxisID: 'Hora',
//yAxisID: 'Velocidade',
data: [{
t: new Date("2015-3-15 12:30"),
y: 12
},
{
t: new Date("2015-3-15 14:40"),
y: 45
},
{
t: new Date("2015-3-15 17:50"),
y: 77
}
],
borderColor: 'rgba(255, 0, 0, 1)',
borderWidth: 4,
fill: false,
lineTension: 0,
lineJoint: "round",
spanGaps: true
}]
},
options: {
scales: {
xAxes: [{
type: 'time',
distribution: 'linear',
time: {
unit: 'hour',
//stepSize: 24??
},
ticks: {
source: 'data'
}
}]
}
}
});
</script>
The chart plots Time x Velocity.
Two small changes will achieve the desired result:
set stepSize: 2 to 'show labels on X axis every 2 hours (0h, 2h, 4h...)'
remove ticks: { source: 'data' } as that:
generates ticks from data (including labels from data {t|x|y} objects)"
Here's a working example based on the posted code:
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'line',
data: {
//labels: ['0h', '2h', '4h', '6h', '8h', '10h', '12h', '14h', '16h', '18h', '20h', '22h', '0h'],
datasets: [{
label: 'AAA1111',
//xAxisID: 'Hora',
//yAxisID: 'Velocidade',
data: [{
t: new Date("2015-3-15 12:30"),
y: 12
},
{
t: new Date("2015-3-15 14:40"),
y: 45
},
{
t: new Date("2015-3-15 17:50"),
y: 77
}
],
borderColor: 'rgba(255, 0, 0, 1)',
borderWidth: 4,
fill: false,
lineTension: 0,
lineJoint: "round",
spanGaps: true
}]
},
options: {
scales: {
xAxes: [{
type: 'time',
distribution: 'linear',
time: {
unit: 'hour',
stepSize: 2
}
}]
}
}
});
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.9.3/dist/Chart.bundle.min.js"></script>
<canvas id="myChart"></canvas>

Update chart.js after form submission and page reload

I have a chart.js bar chart that pulls data via an ajax call to a Django APIView. The ajax call returns one dictionary with a stack of data inside I use to customize the chart. Here's the chart.js code:
var current_year = '{% url "saveskore:api-current-year-savings" %}'
$.ajax({
url: current_year,
type: 'GET',
cache: false,
dataType: 'json',
success: function(data) {
var ctx = document.getElementById('current-year-chart');
var chart = new Chart(ctx, {
type: 'bar',
data: {
labels: data['dates'],
datasets: [
{
label: data['income_label'],
backgroundColor: "#8e5ea2",
data: data['income'],
},
{
label: data['expense_label'],
backgroundColor: 'green',
data: data['expenses'],
},
{
label: data['savings_label'],
backgroundColor: "#3e95cd",
data: data['savings_goal'],
},
{
label: data['avail_label'],
backgroundColor: "#pink",
data: data['avail_to_spend'],
},
]
},
options: {
legend: { display: false },
title: {
display: true,
text: 'Savings for ' + data['year']
}
}
});
}
});
Works great. Looks great.
But! I have a django formset on a separate page that updates the table data that the chart pulls from.
When I update the data in the formset and submit, redirecting to the chart page ... NO UPDATE OCCURS.
If I make some code change or otherwise reload the browser, VOILA, the chart updates.
I have read about either cache=false and chart.update(), but find i have not been able to make either work, mainly because the exact details on their use are not clear.
I would really appreciate input on this.
Have you tried chart.destroy() method ? and then build again the chart with the new data .. that works for me.. take a look at my example
let flag = 0;
var xChart = "";
function dibujar(valor, meses) {
try {
if (valor.length > 0) {
$('#grafico').fadeIn('fast');
var canvas = document.getElementById('chart');
let tipGra = $('#slcTipGra').val();
if (flag !== 0) {
xChart.destroy();
}
//rgba(54, 162, 235, 0.2)
if (tipGra === "bar" || tipGra === "horizontalBar") {
var data = {
labels: meses,
datasets: [
{
label: "Dólares($)",
backgroundColor: "#3e95cd",
borderColor: "#3e95cd",
borderWidth: 2,
hoverBackgroundColor: "#3e95cd",
hoverBorderColor: "#3e95cd",
data: valor,
}
]
};
var option = {
title: {
display: true,
fontSize: 20,
fontFamily: 'Helvetica',
text: 'Reporte Mensual de Ventas'
},
plugins: {
datalabels: {
color: 'white',
anchor: 'end',
align: 'start',
font:
{
weight: 'bold'
}
}
},
scales: {
yAxes: [{
stacked: true,
gridLines:
{
display: true,
color: "rgba(255,99,132,0.2)"
}
}],
xAxes: [{
gridLines: {
display: true
}
}]
}
};
}
if (tipGra === 'line') {
var data = {
labels: meses,
datasets: [
{
label: "Dólares($)",
fill: false,
lineTension: 0.1,
backgroundColor: "rgba(75,192,192,0.4)",
borderColor: "rgba(75,192,192,1)",
borderCapStyle: 'butt',
borderDash: [],
borderDashOffset: 0.0,
borderJoinStyle: 'miter',
pointBorderColor: "rgba(75,192,192,1)",
pointBackgroundColor: "#fff",
pointBorderWidth: 1,
pointHoverRadius: 5,
pointHoverBackgroundColor: "rgba(75,192,192,1)",
pointHoverBorderColor: "rgba(220,220,220,1)",
pointHoverBorderWidth: 2,
pointRadius: 5,
pointHitRadius: 10,
data: valor,
}
]
};
var option = {
title: {
display: true,
fontSize: 20,
fontFamily: 'Helvetica',
text: 'Reporte Mensual de Ventas'
},
plugins: {
datalabels: {
backgroundColor: function (context) {
return context.dataset.borderColor;
},
borderRadius: 4,
color: 'white',
anchor: 'end',
align: 'end',
}
},
showLines: true
};
}
xChart = new Chart(canvas,
{
type: tipGra,
data: data,
options: option
});
flag = 1;
}
else {
$('#grafico').fadeOut('fast');
$('#graficoMessage').fadeIn('slow');
}
} catch (err) {
console.log(err);
}
}
I declare "xChart" as a global variable and a flag to know if it's the first chart to build. The example build 3 different types of charts (Vertical Bar, Horizontal Bar and Line) depending on the selection of the chart type "let tipGra = "$('#slcTipGra').val();"

Can't change color line with chart.js

I use chart.js to make a line chart but I can't change the color line of my chart, I saw it grey.
My code is...
$(document).ready(function(){
$.ajax({
url: "chart/maderas_Chart.php",
method: "GET",
success: function(data) {
console.log(data);
var hora = [];
var valor = [];
for(var i in data) {
hora.push("Hora " + data[i].hora_nueva);
valor.push(data[i].valor);
}
var chartdata = {
labels: hora,
datasets : [
{
label: 'Dique Las Maderas',
fill: false,
boderColor: "#bae755",
borderDash: [5, 5],
strokeColor: "#e755ba",
pointColor: "#55bae7",
pointStrokeColor: "#55bae7",
pointHighlightFill: "#55bae7",
pointHighlightStroke:"#55bae7",
data: valor
}
]
};
var ctx = document.getElementById("maderas_Chart");
var LineGraph = new Chart(ctx, {
type: 'line',
data: chartdata,
options: {
responsive: true,
title:{
display:true,
text:'Dique Las Maderas'
},
tooltips: {
mode: 'index',
intersect: false
},
hover: {
mode: 'nearest',
intersect: true
},
scales: {
xAxes: [{
display: true,
scaleLabel: {
display: true,
labelString: 'Hora'
}
}],
yAxes: [{
display: true,
scaleLabel: {
display: true,
labelString: 'Valor'
}
}]
}
}
});
},
error: function(data) {
console.log(data);
}
});
});
When I first confgure the chart I can change the colors but when I add more code I can't anymore, I delete all code and still can't change the line color.
I'm using chart.js version 2.7, and jquery.
Thanks in advance...
This is because, you are using deprecated properties (used in ChartJS 1.x) for setting colors. Use the following properties instead (which is applicable for ChartJS 2.7) :
datasets: [{
label: 'Dique Las Maderas',
fill: false,
borderColor: "#bae755",
borderDash: [5, 5],
backgroundColor: "#e755ba",
pointBackgroundColor: "#55bae7",
pointBorderColor: "#55bae7",
pointHoverBackgroundColor: "#55bae7",
pointHoverBorderColor: "#55bae7",
data: valor
}]

Populate three highchart graphics with one ajax call

I am trying to figure out how to combine 3 ajax call into 1 but so far I didn't find out the correct way to do it. I have the following three highcharts:
chart1 = new Highcharts.Chart({
chart: {
height: 155,
renderTo: 'chart1_div',
defaultSeriesType: 'spline',
events: {
load: GetData1(date)
}
},
plotOptions: {
series: {
fillOpacity: 0.1
}
},
xAxis: {
categories: c,
labels: {
staggerLines: 2
}
},
yAxis: {
gridLineColor: "#ffffcc",
title: {
text: ''
},
labels: {
x: 15,
y: 15,
style: {
color: "#999999",
//fontWeight: "bold",
fontSize: "10px"
}
},
},
series: [{
name: 'Chart1',
color: "#6bd9ec", //37f312
data: chart1_data
}]
});
chart2 = new Highcharts.Chart({
chart: {
height: 155,
renderTo: 'chart2_div',
defaultSeriesType: 'spline',
events: {
load: GetData2(date)
}
},
plotOptions: {
series: {
fillOpacity: 0.1
}
},
xAxis: {
categories: c,
labels: {
staggerLines: 2
}
},
yAxis: {
gridLineColor: "#ffffcc",
title: {
text: ''
},
labels: {
x: 15,
y: 15,
style: {
color: "#999999",
//fontWeight: "bold",
fontSize: "10px"
}
},
},
series: [{
name: 'Chart2',
color: "#6bd9ec", //37f312
data: chart2_data
}]
});
chart3 = new Highcharts.Chart({
chart: {
height: 155,
renderTo: 'chart3_div',
defaultSeriesType: 'spline',
events: {
load: GetData3(date)
}
},
plotOptions: {
series: {
fillOpacity: 0.1
}
},
xAxis: {
categories: c,
labels: {
staggerLines: 2
}
},
yAxis: {
gridLineColor: "#ffffcc",
title: {
text: ''
},
labels: {
x: 15,
y: 15,
style: {
color: "#999999",
//fontWeight: "bold",
fontSize: "10px"
}
},
},
series: [{
name: 'Chart3',
color: "#6bd9ec", //37f312
data: chart3_data
}]
});
At the moment I am making three different ajax calls:
function GetData1(date) {
$.ajax({
url: '/GetAjaxCall',
type: "POST",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ date: date }),
success: function (f) {
var cat= [];
var ser= [];
$.each(f.d, function (i, e) {
cat.push(e.date);
ser.push(parseInt(e.val1));
});
chart1_div.xAxis[0].setCategories(cat);
chart1_div.series[0].setData(ser);
},
error: function (e) {
alert(e.statusText);
},
cache: false
});
}
function GetData2(date) {
$.ajax({
url: '/GetAjaxCall',
type: "POST",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ date: date }),
success: function (f) {
var cat= [];
var ser= [];
$.each(f.d, function (i, e) {
cat.push(e.date);
ser.push(parseInt(e.val2));
});
chart2_div.xAxis[0].setCategories(cat);
chart2_div.series[0].setData(ser);
},
error: function (e) {
alert(e.statusText);
},
cache: false
});
}
function GetData3(date) {
$.ajax({
url: '/GetAjaxCall',
type: "POST",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ date: date }),
success: function (f) {
var cat= [];
var ser= [];
$.each(f.d, function (i, e) {
cat.push(e.date);
ser.push(parseInt(e.val3));
});
chart3_div.xAxis[0].setCategories(cat);
chart3_div.series[0].setData(ser);
},
error: function (e) {
alert(e.statusText);
},
cache: false
});
}
As you can see, I am right now making the same ajax call 3 times just to be able to populate the 3 charts differently. Does anyone know how could I generate exactly the same 3 charts but only make 1 ajax call? Thanks a lot
Something like:
function GetDataAll(date) {
$.ajax({
url: '/GetAjaxCall',
type: "POST",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ date: date }),
success: function (f) {
var cat1= [];
var ser1= [];
var cat2= [];
var ser2= [];
var cat3= [];
var ser3= [];
$.each(f.d, function (i, e) {
cat1.push(e.date);
ser1.push(parseInt(e.val1));
});
chart1_div.xAxis[0].setCategories(cat1);
chart1_div.series[0].setData(ser1);
chart2_div.xAxis[0].setCategories(cat2);
chart2_div.series[0].setData(ser2);
chart3_div.xAxis[0].setCategories(cat3);
chart3_div.series[0].setData(ser3);
},
error: function (e) {
alert(e.statusText);
},
cache: false
});
}
Under the load event I could call GetData1(date) for the 3 charts but this way I will be hitting the ajax call 3 times. I am probably doing this the wrong way and must be a more efficient way. I will appreciate any thoughts, thank you so much
EDITED - LATEST UPDATE THAT WORKS BASED ON #WERGELD HELP
var chart1_options = {
chart: {
renderTo: 'chart1_div',
xAxis: {
categories: []
},
series: [{
name: 'Chart1',
color: "#6bd9ec"
}]
};
var chart2_options = {
chart: {
renderTo: 'chart2_div',
xAxis: {
categories: []
},
series: [{
name: 'Chart2',
color: "#6bd9ec"
}]
};
var chart3_options = {
chart: {
renderTo: 'chart3_div',
xAxis: {
categories: []
},
series: [{
name: 'Chart3',
color: "#6bd9ec"
}]
};
function GetDataAll(date) {
$ajax({..
chart1_options.xAxis.categories = cat1;
chart1_options.series[0].data = ser1;
chart2_options.xAxis.categories = cat2;
chart2_options.series[0].data = ser2;
chart3_options.xAxis.categories = cat3;
chart3_options.series[0].data = ser3;
var chart1 = new Highcharts.Chart(Highcharts.merge(options, chart1_options));
var chart2 = new Highcharts.Chart(Highcharts.merge(options, chart2_options));
var chart3 = new Highcharts.Chart(Highcharts.merge(options, chart3_options));
});
}
Here is some psuedo code to get you going. What you need to do is setup a chart option object that contains all the constant items among your charts:
var options = {
chart: {
height: 155,
defaultSeriesType: 'spline'
},
plotOptions: {
series: {
fillOpacity: 0.1
}
},
xAxis: {
categories: c,
labels: {
staggerLines: 2
}
},
yAxis: {
gridLineColor: "#ffffcc",
title: {
text: ''
},
labels: {
x: 15,
y: 15,
style: {
color: "#999999",
//fontWeight: "bold",
fontSize: "10px"
}
},
}
};
Next you do your ajax call and assign your series' data and title (and any other items) and create an object for each chart you want to create:
var chartOptions1 = {
chart: { renderTo: 'container1' },
series: []
};
var chartOptions2 = {
chart: { renderTo: 'container1' },
series: []
};
Next you do your code to get the chart data/name/etc that you want to have for each chart which I will not go into here. The next step is to then create your chart from the merged options:
var chart1 = new Highcharts.Chart(Highcharts.merge(options, chartOptions1));
var chart2 = new Highcharts.Chart(Highcharts.merge(options, chartOptions2));
This should do it. Again, it is psuedocode but you get the idea. Global options + merge are you friends. Full psuedocode here.

How to process json object in highchart

I receive an array json object. And now I don't know how I can process it in javascript code to series section data. I use this example of highchart column-rotated-labels. In this object has two columns AVG and other title, and length of this object might 20.
This is my codes:
$('#showresult').click(function() {
$.ajax({
url : "../../coursestatus",
type : "get",
data : {
major : $('#get').val(),
year : $('#yearlist').val(),
semester : $('#semester').val()
},
success : function(data) {
alert(data.length);
$(function () {
$('#container').highcharts({
chart: { type: 'column'
},
title: { text: 'World\'s largest cities per 2014' },
xAxis: {
type: 'category',
labels: {
rotation: -45,
}
},
yAxis: { min: 0,
title: {
text: 'Population (millions)'
} },
legend: { enabled: false },
tooltip: { pointFormat: 'Population in 2008: <b>{point.y:.1f} millions</b>' },
series: [{ // I don't know how I can process data object to set that's elements to this
name: 'Population',
data: [
JSON.parse("[" + data + "]")
],
dataLabels: { enabled: true,
rotation: -90,
color: '#FFFFFF',
align: 'right',
x: 4,
y: 10,
style: { fontSize: '13px',
fontFamily: 'Verdana, sans-serif', textShadow: '0 0 3px black'
}
}
}]
});
});
And this object include this elements:
title columns includes course name and avg columns includes mark for that course.
And this is data is in data object:
[{"title":"Math","avg":20},{"title":"Network","avg":18},{"title":"Operating system","avg":16}]
And above data is has 3 length and it is simple, in fact this object maybe that's length is >10.
Thank u!
I founded similar problem in this page and I solved my problem.
Populate Highcharts with JSON data using jQuery

Resources