CanvasJS stock chart axisY doesn't update automatically with my data - javascript

I have tried the stock chart with sample data present on the CanvasJS site and it updates the Y axis everytime I scroll through it, but when I pass my data to that function it scrolls but without updating the Y-axis.
First I was trying to fetch data from array of arrays but the sample chart was using array of JSON so I converted my data to be of the exact similar manner but to no avail. I would be very thankful if you can help me on this.
My data
window.onload = function () {
CanvasJS.addColorSet("greenShades",
[//colorSet Array
"red",
"#008080",
"#2E8B57",
"#3CB371",
"#90EE90"
]);
var dataPoints = [];
var stockChart = new CanvasJS.StockChart("stockChartContainer",{
zoomEnabled: true,
theme: "light2",
colorSet: "greenShades",
exportEnabled: true, //false
title:{
text:""
},
subtitles: [{
text: ""
}],
rangeSelector: {
buttons: [
{
range: 10, //Change it to 6
rangeType: "day",
label: "10D"
},
{
range: 1, //Change it to 6
rangeType: "month",
label: "1M"
},
{
range: 6, //Change it to 6
rangeType: "month",
label: "6M"
},
{
range: 1, //Change it to 6
rangeType: "year",
label: "1Y"
},
{
rangeType: "all",
label: "All" //Change it to "All"
}
]
},
charts: [{
axisX: {
},
axisY: {
prefix: "",
suffix: "",
title: "",
viewportMinimum: 20,
viewportMaximum: 200,
titleFontSize: 14
},
data: [{
type: "area",
xValueFormatString: "MMM YYYY",
yValueFormatString: "#,###.##M",
dataPoints : dataPoints
}]
}],
navigator: {
// slider: {
// minimum: new Date(2010, 00, 01),
// maximum: new Date(2014, 00, 01)
// }
}
});
$.getJSON("https://financialmodelingprep.com/api/v3/historical-price-full/AAPL?apikey=API_KEY", function(data) {
for(var i = 0; i < data.historical.length; i++){
dataPoints.push({x: new Date(data.historical[i].date), y: Number(data.historical[i].close)});
}
console.log(dataPoints)
stockChart.render();
});
}

Related

Charts.js display two combined line charts for last 7 days

I have 2 set of datasets I want to display in single line chart for last 7 days, and if possible only show single Y axis with max value from all data sets. I try to use time as xAxes but it is not showing up.
here is my code https://jsfiddle.net/e6trkxL0/
You have to place the labels for datapoints.
let start = new Date(),
end = new Date();
start.setDate(start.getDate() - 7); // set to 'now' minus 7 days.
start.setHours(0, 0, 0, 0); // set to midnight.
let chart = new Chart(document.getElementById("lastSevenDaysOverview"), {
type: "line",
data: {
labels: [],
datasets: [{
label: 'Dataset 1',
data: [1, 4, 66, 7, 12, 3, 8],
borderColor: '#ff3366',
backgroundColor: '#ff3366',
},
{
label: 'Dataset 2',
data: [31, 14, 6, 71, 1, 35, 9],
borderColor: '#880000',
backgroundColor: '#880000',
}
]
},
options: {
interaction: {
mode: 'index',
intersect: true,
},
stacked: false,
responsive: true,
scales: {
y: {
type: 'linear',
display: true,
position: 'left',
},
xAxes: [{
type: "time",
// this is not doing much
// time: {
// min: start,
// max: end,
// unit: "day"
//}
}]
}
}
});
chart.render();
for (let i = 0; i < 7; i++) {
var labelDate = start;
labelDate.setDate(start.getDate() + 1);
chart.data.labels.push(labelDate.toLocaleString())
}
chart.update();
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.1/chart.min.js"></script>
<canvas id="lastSevenDaysOverview"></canvas>
2 things, for a time axis in chart.js you need according to the documentation a time adapter. Also you defined you x axis scales as a array which is incorrect. You need to define all scales as an object where the key of the object is the scale ID, you can read more about it in the migration guide
For points to be mapped in the chart you also need to provide a x place which in this case needs to be the date for which the datapoint is valid.
To just show a single axis with the highest values you can let both datasets be mapped to the same y axis:
let start = new Date(),
end = new Date();
start.setDate(start.getDate() - 7); // set to 'now' minus 7 days.
start.setHours(0, 0, 0, 0); // set to midnight.
new Chart(document.getElementById("lastSevenDaysOverview"), {
type: "line",
data: {
datasets: [{
label: 'Dataset 1',
data: [{
x: new Date('10-16-2021'),
y: 1
}, {
x: new Date('10-18-2021'),
y: 4
}, {
x: new Date('10-19-2021'),
y: 66
}],
borderColor: '#ff3366',
backgroundColor: '#ff3366',
},
{
label: 'Dataset 2',
data: [{
x: new Date('10-14-2021'),
y: 31
}, {
x: new Date('10-18-2021'),
y: 14
}, {
x: new Date('10-19-2021'),
y: 6
}],
borderColor: '#880000',
backgroundColor: '#880000'
}
]
},
options: {
interaction: {
mode: 'index',
intersect: true,
},
responsive: true,
scales: {
y: {
type: 'linear',
display: true,
position: 'left',
},
x: {
type: "time",
min: start,
max: end,
time: {
unit: "day"
}
}
},
}
});
<canvas id="lastSevenDaysOverview"></canvas>
<script src="https://cdn.jsdelivr.net/npm/chart.js/dist/chart.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-date-fns/dist/chartjs-adapter-date-fns.bundle.min.js"></script>

How to make dynamic charts in Javascript with a JSON File

So, I am new to Javascript, but I have a code to make a stable bar chart, but I need to make it dynamic.
MY JSON File format is:
"valid_columns_counts": {
"Sr no.": 0,
"Domain": 37,
"Company Name": 0,
"Address": 36,
"Industry": 38,
"Phone Number": 30,
"Zipcode": 33,
"email": 14}
I ran this code:
window.onload = function () {
var dataPoints = [];
var chart = new CanvasJS.Chart("chartContainer", {
animationEnabled: true,
title:{
},
axisY: {
title: "Percentage",
titleFontColor: "#4F81BC",
},
toolTip: {
shared: true
},
legend: {
cursor:"pointer",
itemclick: toggleDataSeries
},
data:
{
type: "column",
name: "Consistency",
legendText: "Consistency",
axisYType: "secondary",
showInLegend: true,
dataPoints: dataPoints
}
});
function addData(data) {
for (var i = 0; i < data.length; i++) {
dataPoints.push({
x: data[i].valid_columns_counts
y: data[i].valid_columns_counts
});
}
}
chart.render();
$.getJSON("localhost/sample_output.json", addData);
}
But this code shows blank page when runned.Please if someone can help me.

chart.js display even intervals between two dates and adding label to y axes

I am converting Jqplot chart to ChartJs and I want them both to look the same.
I have the following chart using the chart.js library.
var myChart = new Chart(ctxr, {
type: 'line',
data: {
datasets: [{
label: "Estimated cost",
data: [{
x: new Date("09/24/2020 10:26:20"),
//x: new Date(),
y: 8
}, {
x: new Date("09/24/2020 10:27:56"),
//x: new Date(),
y: 8
}],
borderColor: [
'rgba(196, 217, 45, 1)',
]
},
{
label: "Actual cost",
data: [{
x: new Date("09/24/2020 10:27:56"),
//x: new Date(),
y: 23
}, {
x: new Date("09/24/2020 10:26:20"),
//x: new Date(),
y: 24
}],
borderColor: [
'rgba(75, 178, 197, 1)',
]
}],
labels: [new Date("09/24/2020 10:26:20").toLocaleString(), new Date("09/24/2020 10:27:56").toLocaleString()]
},
options: {
responsive: true,
responsiveAnimationDuration: 1,
maintainAspectRatio: false,
aspectRatio: 1,
title: {
display: true,
text: 'Auction Overview'
},
tooltips: {
mode: 'index',
intersect: true
},
scales: {
yAxes: [{
ticks: {
// Include a GBP in the ticks
callback: function (value, index, values) {
return 'GBP' + value;
}
}
}],
xAxes: [{
type: 'time',
}]
}
}
});
that gives me this chart
I would like to make it have intervals of time between the start date and the end date(like the x axis on the Jqplot chart) and also add string "GBP" in front of each y-value (like y-axis of Jqplot chart).
Both graphs are generated with the same identical data. so they should look the same.
So far everything i have tried from the chart.js docs has failed.
Below is a snipped of my js console:
There is something else wrong with your implementation that you have not told us about, because copy and pasting your code results in a working chart with GBP labels and time span. See below.
Please check your console for errors and also make sure that you are including moment.js, a dependency of Chart.js when work with dates.
I've also set options.yAxes[0].ticks.beginAtZero to true to more closely match the example you gave.
var ctxr = document.getElementById('chart').getContext('2d');
var myChart = new Chart(ctxr, {
type: 'line',
data: {
datasets: [{
label: "Estimated cost",
data: [{
x: new Date("09/24/2020 10:26:20"),
//x: new Date(),
y: 8
}, {
x: new Date("09/24/2020 10:27:56"),
//x: new Date(),
y: 8
}],
borderColor: [
'rgba(196, 217, 45, 1)',
]
},
{
label: "Actual cost",
data: [{
x: new Date("09/24/2020 10:27:56"),
//x: new Date(),
y: 23
}, {
x: new Date("09/24/2020 10:26:20"),
//x: new Date(),
y: 24
}],
borderColor: [
'rgba(75, 178, 197, 1)',
]
}
],
labels: [new Date("09/24/2020 10:26:20").toLocaleString(), new Date("09/24/2020 10:27:56").toLocaleString()]
},
options: {
responsive: true,
responsiveAnimationDuration: 1,
maintainAspectRatio: false,
aspectRatio: 1,
title: {
display: true,
text: 'Auction Overview'
},
tooltips: {
mode: 'index',
intersect: true
},
scales: {
yAxes: [{
ticks: {
beginAtZero: true,
// Include a GBP in the ticks
callback: function(value, index, values) {
return 'GBP' + value;
}
}
}],
xAxes: [{
type: 'time',
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.0/moment.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.9.3"></script>
<canvas id="chart"></canvas>

Working with multiple axis with highcharts.js

I’m working with highcharts.js and I have a scatter plot example I found, fiddle here. With this example I can break down the X-axis into two categories which is ideal for my situation. However, I would like to rotate the labels for each ‘Vendor’ variable 90 degrees while keeping the ‘date’ variable horizontal. I can’t figure this out, of even know if it’s possible. I know how to rotate both variables but that doesn’t look good. Is it even possible to achieve this effect with highcharts.js?
var cates = [{
name: "1/1/2014",
categories: ["Vendor 1", "Vendor 2", "Vendor 3"]
}, {
name: "1/2/2014",
categories: ["Vendor 1", "Vendor 2", "Vendor 3"]
}, {
name: "1/3/2014",
categories: ["Vendor 1", "Vendor 2", "Vendor 3"]
}];
console.log("here: ", cates);
$(function () {
var chart = new Highcharts.Chart({
chart: {
renderTo: "container",
type: "scatter",
borderWidth: 5,
borderColor: '#e8eaeb',
borderRadius: 0,
backgroundColor: '#f7f7f7'
},
title: {
text: "title"
},
yAxis: [{ // Primary yAxis
labels: {
format: '${value}',
style: {
color: Highcharts.getOptions().colors[0]
}
},
title: {
text: 'Daily Tickets',
style: {
color: Highcharts.getOptions().colors[0]
}
}
}, { // Secondary yAxis
title: {
text: 'Invoices',
style: {
color: Highcharts.getOptions().colors[0]
}
},
labels: {
format: '${value}',
style: {
color: Highcharts.getOptions().colors[0]
}
},
opposite: true
}]
,
series: [{
name: 'Daily',
type: 'scatter',
yAxis: 1,
data: [4, 14, 18, 5, 6, 5, 14, 15, 18],
tooltip: {
valueSuffix: ' mm'
}
}],
xAxis: {
categories: cates,
/** UNCOMMENT BELOW **/
// labels: {
// rotation:-90,
// style: {
// fontSize:'10px',
// fontWeight:'normal',
// color:'#333'
// },
//}
}
});
});
UPDATE: I figured it out, the labels object should look like this
labels: {
groupedOptions: [{
y: 90,
rotation: 0
}],
rotation:-90,
style: {
fontSize:'10px',
fontWeight:'normal',
color:'#333'
},
}

How to get all json values in line chart

I have many Json values, using them I am going to create a line chart but it shows only one value in the chart. I am a newbie to javascript and have an idea to plot all values in chart. please anybody give jsfiddle example for this issue.
HTML code
<div id="chartContainer" class="chart">
Script
$.getJSON('dashboard_summary.php?', function(data) {
var len = data.length
$.each(data, function(i, v) {
chart(v.Date,v.Tip,v.Revenue,len);
});
});
function chart (dates,Tip,Rev,len) {
var chart = new CanvasJS.Chart("chartContainer", {
title: {
text: "Revenue",
fontSize: 15
},
axisX: {
gridColor: "Silver",
tickColor: "silver",
valueFormatString: "DD/MMM"
},
toolTip: {
shared:true
},
theme: "theme2",
axisY: {
gridColor: "Silver",
tickColor: "silver"
},
legend: {
verticalAlign: "center",
horizontalAlign: "right"
},
data: [
{
type: "line",
showInLegend: true,
lineThickness: 2,
name: "Tip",
markerType: "square",
color: "#F08080",
dataPoints: [
{
x: new Date(dates),
y: parseInt(Tip)
}
]
},
{
type: "line",
showInLegend: true,
name: "Revenue",
color: "#20B2AA",
lineThickness: 2,
dataPoints: [
{
x: new Date(dates),
y: parseInt(Rev)
}
]
}
],
legend: {
cursor: "pointer",
itemclick: function(e) {
if (typeof(e.dataSeries.visible) === "undefined" || e.dataSeries.visible) {
e.dataSeries.visible = false;
} else {
e.dataSeries.visible = true;
}
chart.render();
}
}
});
chart.render();
};
Json data
{
"Date": "2014-01-30",
"CarsParked": "1",
"RevenueWithTip": "0",
"Revenue": "0",
"Tip": "0",
},
{
"Date": "2014-01-31",
"CarsParked": "10",
"RevenueWithTip": "10",
"Revenue": "7",
"Tip": "3",
},
{
"Date": "2014-02-28",
"CarsParked": "28",
"RevenueWithTip": "55",
"Revenue": "47",
"Tip": "8",
}
Based on your code, I can see why the chart shows only one point, which is the last data point of those points expected to be shown on the chart. Here is the problem:
var len = data.length;
/* Loop through each item in the data */
$.each(data, function(i, v) {
chart(v.Date,v.Tip,v.Revenue,len); /* Draw a chart with one point */
});
So you end up drawing many charts with the last chart which has the last data point to replace all the previous charts.
Instead, you should adjust the foreach block as follow and draw the chart once you've converted the data into an array of points.
$.getJSON('dashboard_summary.php?', function(data) {
var Tips = [];
var Revs = [];
$.each(data, function(i, v) {
Tips.push({ x: new Date(v.Date), y: parseInt(v.Tip) });
Revs.push({ x: new Date(v.Date), y: parseInt(v.Revenue) });
});
chart(Tips, Revs);
});
Also, you can format the x-axis to make the chart look prettier (The format of the x-axis here is designed for the data given above. In your application, you may have to use another format style depending on the actual data):
function chart (Tips, Revs) {
var chart = new CanvasJS.Chart("chartContainer", {
title: {
text: "Revenue",
fontSize: 15
},
axisX: {
gridColor: "Silver",
tickColor: "silver",
valueFormatString: "DD/MMM",
interval:14,
intervalType: "day"
},
toolTip: {
shared:true
},
theme: "theme2",
axisY: {
gridColor: "Silver",
tickColor: "silver"
},
legend: {
verticalAlign: "center",
horizontalAlign: "right"
},
data: [
{
type: "line",
showInLegend: true,
lineThickness: 2,
name: "Tip",
markerType: "square",
color: "#F08080",
dataPoints: Tips
},
{
type: "line",
showInLegend: true,
name: "Revenue",
color: "#20B2AA",
lineThickness: 2,
dataPoints: Revs
}
],
legend: {
cursor: "pointer",
itemclick: function(e) {
if (typeof(e.dataSeries.visible) === "undefined" || e.dataSeries.visible) {
e.dataSeries.visible = false;
} else {
e.dataSeries.visible = true;
}
chart.render();
}
}
});
chart.render();
}
A jsFiddle is made here for your review.
Updated codes. it Works >> Pastebin
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript" src = "http://canvasjs.com/wp-content/themes/bootstrap_child/assets/js/jquery-1.8.3.min.js"> </script>
<script type="text/javascript" src="http://canvasjs.com/assets/script/canvasjs.min.js"></script>
</head>
<body>
<div id="chartContainer" class="chart">
<script type="text/javascript">
data=[
{
"Date": "2014-01-30",
"CarsParked": "1",
"RevenueWithTip": "0",
"Revenue": "0",
"Tip": "0",
},
{
"Date": "2014-01-31",
"CarsParked": "10",
"RevenueWithTip": "10",
"Revenue": "7",
"Tip": "3",
},
{
"Date": "2014-02-28",
"CarsParked": "28",
"RevenueWithTip": "55",
"Revenue": "47",
"Tip": "8",
}];
var len = data.length;
$.each(data, function(i, v) {
chart(v.Date,v.Tip,v.Revenue,len);
});
function chart (dates,Tip,Rev,len) {
var chart = new CanvasJS.Chart("chartContainer", {
title: {
text: "Revenue",
fontSize: 15
},
axisX: {
gridColor: "Silver",
tickColor: "silver",
valueFormatString: "DD/MMM"
},
toolTip: {
shared:true
},
theme: "theme2",
axisY: {
gridColor: "Silver",
tickColor: "silver"
},
legend: {
verticalAlign: "center",
horizontalAlign: "right"
},
data: [
{
type: "line",
showInLegend: true,
lineThickness: 2,
name: "Tip",
markerType: "square",
color: "#F08080",
dataPoints: [
{
x: new Date(dates),
y: parseInt(Tip)
}
]
},
{
type: "line",
showInLegend: true,
name: "Revenue",
color: "#20B2AA",
lineThickness: 2,
dataPoints: [
{
x: new Date(dates),
y: parseInt(Rev)
}
]
}
],
legend: {
cursor: "pointer",
itemclick: function(e) {
if (typeof(e.dataSeries.visible) === "undefined" || e.dataSeries.visible) {
e.dataSeries.visible = false;
} else {
e.dataSeries.visible = true;
}
chart.render();
}
}
});
chart.render();
}
</script>
</body>
</html>
jsFiddle
Update Code:
dataRevenue=
[
{ x: new Date(2014, 00,30), y: 0 },
{ x: new Date(2014, 01,31), y: 7},
{ x: new Date(2014, 02,28), y: 47}
];
dataTip =[
{ x: new Date(2014, 00,30), y: 0 },
{ x: new Date(2014, 01,31), y: 3},
{ x: new Date(2014, 02,28), y: 8}
];
var chart = new CanvasJS.Chart("chartContainer",
{
theme: "theme2",
title:{
text: "line chart"
},
axisX: {
valueFormatString: "MMM",
interval:1,
intervalType: "month"
},
axisY:{
includeZero: false
},
data: [
{
type: "line",
//lineThickness: 3,
dataPoints: dataTip
},
{
type: "line",
//lineThickness: 3,
dataPoints: dataRevenue
}
]
});
chart.render();

Categories

Resources