I am trying to plot a graph using chart.js where y-axis values are numbers and x-axis values are strings. I have given the code that i have written, but it does not plot the string values.
Appreciate your help.
window.onload = function() {
var dataPoints7 = [];
var chart7 = new CanvasJS.Chart("chartContainer7", {
animationEnabled: true,
theme: "light2",
title: {
text: "Cases in States"
},
axisY: {
title: "Cases",
titleFontSize: 24
},
data: [{
type: "line",
yValueFormatString: "#,### Cases",
dataPoints: dataPoints7
}]
});
fetch("https://api.covid19india.org/data.json", {
"method": "GET"
})
.then(function(response) {
return response.json();
})
.then(function(data) {
for (var i = 1; i < data.statewise.length; i++) {
dataPoints7.push({
x: data.statewise[i].state,
y: parseInt(data.statewise[i].confirmed)
});
}
chart7.render();
});
}
<!DOCTYPE html>
<html lang="en">
<div id="chartContainer7" style="height: 370px; width: 100%;"></div>
<script src="https://canvasjs.com/assets/script/jquery-1.11.1.min.js"></script>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
</html>
For your case you should supply label property not x value and also i believe you should use column charts for this purpose.
You might see some labels not showing up.You can either set the angle or increase the width of chart to make it visible.
Try running this snippet
window.onload = function() {
var dataPoints7 = [];
var chart7 = new CanvasJS.Chart("chartContainer7", {
animationEnabled: true,
theme: "light2",
title: {
text: "Cases in States"
},
axisY: {
title: "Cases",
titleFontSize: 24
},
axisX: {
labelAngle: 180
},
data: [{
type: "line",
yValueFormatString: "#,### Cases",
dataPoints: dataPoints7
}]
});
fetch("https://api.covid19india.org/data.json", {
"method": "GET"
})
.then(function(response) {
return response.json();
})
.then(function(data) {
for (var i = 1; i < data.statewise.length; i++) {
dataPoints7.push({
label: data.statewise[i].state,
y: parseInt(data.statewise[i].confirmed)
});
}
chart7.render();
});
}
<!DOCTYPE html>
<html lang="en">
<div id="chartContainer7" style="height: 370px; width: 100%;"></div>
<script src="https://canvasjs.com/assets/script/jquery-1.11.1.min.js"></script>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
</html>
Related
I want to that the Chart start at 0. But it takes always the lower value to start.
I already tried a few things but nothing works.
It never takes the settings done in de options Part of de javascript part. So i dont know what the issue is. It never starts at 0. But this is what i want to.
Please help. Thank you very much :)
Looks currently like this: https://school.luis-luescher.com/m242/moin/index.php
<!DOCTYPE html>
<html>
<head>
<title>Database</title>
<style type="text/css">
BODY {
width: 550PX;
}
#chart-container {
width: 100%;
height: auto;
}
</style>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.9.4/dist/Chart.min.js"></script>
</head>
<body>
<div id="chart-container">
<canvas id="graphCanvas"></canvas>
</div>
<script>
$(document).ready(function() {
showGraph();
});
function showGraph() {
{
$.post("https://school.luis-luescher.com/m242/moin/data.php",
function(data) {
console.log(data);
var trytime = [];
var count = [];
for (var i in data) {
trytime.push(data[i].trytime);
count.push(data[i].count);
}
var chartdata = {
labels: trytime,
datasets: [{
label: 'Erfolgreiche Authentifizerungen',
backgroundColor: '#8846f1',
borderColor: '#a446f1',
hoverBackgroundColor: '#CCCCCC',
hoverBorderColor: '#666666',
borderWidth: 1,
data: count,
}],
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
}
var graphTarget = $("#graphCanvas");
var barGraph = new Chart(graphTarget, {
type: 'bar',
data: chartdata
});
});
}
}
</script>
</body>
</html>
Your Options object must be outside chartData.
var barGraph = new Chart(graphTarget, {
type: 'bar',
data: chartdata,
options: options
});
I'm having a problem with C# asp.net mvc. The line in my chart is not getting displayed. I tried many different charts but it's not working. The objective is using my database values to draw the line.
My View: Estatisticas.cshtml
#model Estágio_TP.Models.Alerta
#{
ViewBag.Title = "Estatisticas";
}
<h2>Estatisticas de #Html.DisplayFor(model => model.nomeAlerta)</h2>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<script type="text/javascript" src="https://canvasjs.com/assets/script/jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<title>Doughnut Chart</title>
<meta name="viewport" content="width=device-width" />
<script type="text/javascript" src="https://canvasjs.com/assets/script/jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<title>Gráfico Chart</title>
<script src="~/Content/js/Chart_est.js"></script>
</head>
<body>
<div id="chartContainer1" style="width: 100%; height: 500px;display: inline-block;"></div>
<br /><br /><br />
<div id="chartContainer2" style="width: 100%; height: 500px;display: inline-block;"></div>
<!--<div class="card-body">
<div class="chart-area">
<canvas id="teste_est"style="width: 100%; height: 500px;display: inline-block;"></canvas>
</div>
</div>-->
<script type="text/javascript">
function chart1(){
var chart1 = new CanvasJS.Chart("chartContainer1", {
title: {
text: " #Html.DisplayFor(model => model.nomeTrigger)"
},
animationEnabled: true,
legend: {
fontSize: 20,
fontFamily: "Helvetica"
},
theme: "light2",
data: [
{
type: "doughnut",
indexLabelFontFamily: "Garamond",
indexLabelFontSize: 20,
indexLabel: "{label} {y}%",
startAngle: -20,
showInLegend: true,
toolTipContent: "{legendText} {y}%",
dataPoints: [
{ y: #ViewData["valor"], legendText: "Em Uso", label: "Em Uso"
},
{ y: 100 - #ViewData["valor"], legendText: "Livre", label: "Livre" },
],
//dataPoints: #Html.Raw(ViewBag.DataPoints),
}
]
});
chart1.render();
}
$(document).ready(function () {
showChart3();
});
function showChart3() {
$.get("/alertas/json/", function (data) {
var tempo = [];
var valor = [];
for (var i in data) {
tempo.push(data[i].tempo);
valor.push(data[i].valor);
}
var chart = new CanvasJS.Chart("chartContainer2", {
animationEnabled: true,
theme: "light2",//light1
title: {
text: "Gráfico ao Longo do Dia"
},
data: [
{
// Change type to "bar", "splineArea", "area", "spline", "pie",etc.
type: "line",
dataPoints: data
}
]
});
chart.render();
});
}
function start() {
chart1();
showChart3();
}
window.onload = start();
</script>
<!-- <script src="~/Content/js/teste_estatistica.js"></script>-->
</body>
</html>
Controller:
public ContentResult JSON(string id)
{
var teste_xx = db.Conteudos.Where(a => a.nomeAl == id)
.Where(a => a.Data_cont.Day == DateTime.Now.Day)
.OrderBy(a => a.Data_cont)
.Select(a => new
{
valor = a.max_valor,
tempo = a.Data_cont //.ToString("hh:mm")
});
List<DataPoint> dataPoints;
dataPoints = new List<DataPoint>();
foreach (var result in teste_xx)
{
//list2.Add(result.tempo.ToString());
//list2.Add(result.valor.ToString());
var tempo = result.tempo;
var valor = result.valor;
dataPoints.Add(new DataPoint(tempo, valor));
}
JsonSerializerSettings _jsonSetting = new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore };
return Content(JsonConvert.SerializeObject(dataPoints, _jsonSetting), "application/json");
}
}
DB: Only need the DateTime("hh:mm:ss") and the max_value
Database
There are many problems that they should be modified.
You import canvasjs.min.js twice... just import 1 time.
I only solve your Alertas/Json action, I have no Alertas/Estatisticas's model Estágio_TP.Models.Alerta so the page will not show chartContainer1's solution.
I modify the Json action to return JsonResult. Not ContentResult.
Your Alertas/Json should take one Id parameter, so I hard-code the parameter in the $.get("/alertas/json/1");
I assume some simple db data to show this chart will work.
Assign axisX's properties, including the time format/intervals
Assing dataPoints with x and y as keys, not your tempo and valor as keys.
My version works:
Estatisticas.cshtml
<div id="chartContainer2" style="width: 100%; height: 500px;display: inline-block;"></div>
#section scripts {
<script>
$(document).ready(function () {
showChart3();
});
function showChart3() {
$.get("/alertas/json/1", function (data) {
var dataPoints = [];
for (var i in data) {
dataPoints.push({
x: new Date(parseInt(data[i].tempo.replace("/Date(", "").replace(")/", ""), 10)),
y: data[i].valor
});
}
console.log(dataPoints);
var chart = new CanvasJS.Chart("chartContainer2", {
animationEnabled: true,
theme: "light2",
title: {
text: "Gráfico ao Longo do Dia"
},
axisX: {
interval: 10,
intervalType: "minute",
valueFormatString: "YYYY/MM/DD HH:mm"
},
data: [
{
type: "line",
dataPoints: dataPoints
}
]
});
chart.render();
});
}
</script>
}
Controller
public JsonResult JSON(string id)
{
var db = new List<Conteudos>()
{
new Conteudos()
{
Data_cont = DateTime.Now,
max_valor = 10,
nomeAl = "1"
},
new Conteudos()
{
Data_cont = DateTime.Now.AddHours(1),
max_valor = 40,
nomeAl = "1"
},
new Conteudos()
{
Data_cont = DateTime.Now.AddHours(2),
max_valor = 30,
nomeAl = "1"
},
new Conteudos()
{
Data_cont = DateTime.Now.AddHours(3),
max_valor = 50,
nomeAl = "1"
},
new Conteudos()
{
Data_cont = DateTime.Now.AddHours(4),
max_valor = 60,
nomeAl = "1"
}
};
var teste_xx = db.Where(a => a.nomeAl == id)
.Where(a => a.Data_cont.Day == DateTime.Now.Day)
.OrderBy(a => a.Data_cont)
.Select(a => new
{
valor = a.max_valor,
tempo = a.Data_cont //.ToString("hh:mm")
});
List<DataPoint> dataPoints;
dataPoints = new List<DataPoint>();
foreach (var result in teste_xx)
{
//list2.Add(result.tempo.ToString());
//list2.Add(result.valor.ToString());
var tempo = result.tempo;
var valor = result.valor;
dataPoints.Add(new DataPoint(tempo, valor));
}
return Json(dataPoints, JsonRequestBehavior.AllowGet);
}
This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 3 years ago.
I am new to Javascript and ran into a problem I can't resolve.
I wanted to rewrite an example with jquery into pure Javascript.
I don't understand why this doesn't work.
Why is the variable "vorlauf" empty outside the function?
Isn't it a global variable?
I attached a picture of the console output.
Not working as expected (tried to omit every clutter...):
<!DOCTYPE HTML>
<html>
<head>
<script>
let vorlauf = new Array();
let getJSON = function (name) {
fetch(name + ".json")
.then(response => response.json())
.then(parsed => {
console.log(parsed.length, parsed)
for (let i = 0; i < parsed.length; i++) {
vorlauf.push({
x: new Date(parsed[i].date + " " + parsed[i].time),
y: Number(parsed[i].temp) / 1000
})
}
});
}
getJSON("vorlauf")
console.log("Nach Aufruf getJSON " + vorlauf.length)
</script>
</head>
<body>
</body>
</html>
Works as expected (included everything):
!DOCTYPE HTML>
<html>
<head>
<script>
window.onload = function() {
let vorlauf = [];
let chart = new CanvasJS.Chart("chartContainer", {
animationEnabled: true,
theme: "light2",
title: {
text: "Vorlauf"
},
axisY: {
title: "Grad",
titleFontSize: 24
},
axisX:{
valueFormatString: "YYYY-MM-DD hh:mm:ss" ,
labelAngle: -50
},
data: [{
name: "Vorlauf",
showInLegend: true,
type: "spline",
dataPoints: vorlauf
}]
});
$.getJSON("http://localhost/vorlauf.json", function(data) {
for(let i = 0; i < data.length; i++) {
vorlauf.push({
x: new Date(data[i].date + " " + data[i].time),
y: Number(data[i].temp) / 1000
});
}
chart.render();
})
}
</script>
</head>
<body>
<div id="chartContainer" style="height: 70%; width: 100%;"></div>
<script src="https://canvasjs.com/assets/script/jquery-1.11.1.min.js"></script>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
</body>
</html>
The json data:
[{"date": "2020-02-22", "temp": "39937", "time": "09:28:59"}, {"date": "2020-02-22", "temp": "39937", "time": "09:29:21"}]
picture of the debug output of Firefox
Please place all javascript above .
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<div id="chartContainer" style="height: 70%; width: 100%;"></div>
<script src="https://canvasjs.com/assets/script/jquery-1.11.1.min.js"></script>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<script>
window.onload = function() {
let vorlauf = [];
let chart = new CanvasJS.Chart("chartContainer", {
animationEnabled: true,
theme: "light2",
title: {
text: "Vorlauf"
},
axisY: {
title: "Grad",
titleFontSize: 24
},
axisX: {
valueFormatString: "YYYY-MM-DD hh:mm:ss",
labelAngle: -50
},
data: [{
name: "Vorlauf",
showInLegend: true,
type: "spline",
dataPoints: vorlauf
}]
});
$.getJSON("http://localhost/vorlauf.json", function(data) {
for (let i = 0; i < data.length; i++) {
vorlauf.push({
x: new Date(data[i].date + " " + data[i].time),
y: Number(data[i].temp) / 1000
});
}
chart.render();
})
}
</script>
I'm building a flask app in python and i return 2 arrays using render_template, names and deals to my HTML file. I know these work because of the code beneath that I tried, giving the right values.
{% for deal in deals %}
<p>Value: {{ deal }}</p>
{% endfor %}
This shows that I've got access to them in HTML. What I want to do next is get some graphics and see the values on the y-axel and the names as labels of each bar on the chart. I found a graph example from Chart.js and started working with it. But I am not getting anywhere, and the only thing I truly want is to change the data points, so instead of hardcoding it like this:
{ y: 233244, label: "Venezuela" }
it could be:
{ y: deals[i], label: names[i] }
This is the whole chart function.
<script>
window.onload = function () {
var chart = new CanvasJS.Chart("chartContainer", {
animationEnabled: true,
theme: "light2",
title:{
text: "Top Oil Reserves"
},
axisY: {
title: "Reserves(MMbbl)"
},
labels: names,
data: [{
type: "column",
showInLegend: true,
legendMarkerColor: "grey",
legendText: "MMbbl = one million barrels",
dataPoints: [
{ y: 233244, label: "Venezuela" },
{ y: 266455, label: "Saudi" },
{ y: 169709, label: "Canada" },
{ y: 158400, label: "Iran" },
{ y: 142503, label: "Iraq" },
{ y: 101500, label: "Kuwait" },
{ y: 97800, label: "UAE" },
{ y: 80000, label: "Russia" }
]
}]
});
chart.render();
}
</script>
</head>
<body>
<div id="chartContainer" style="height: 370px; width: 100%;"></div>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
</body>
I SOLVED IT, this was the easiest and probably best way to achieve it in. I finally got through it and can claim both arrays in the graph. My solution looks like this:
var jsDeals = {{ deals|tojson }};
var jsNames = {{ names|tojson }};
var sum = {{ sum|tojson }};
var limit = jsDeals.length;
var dataP = [];
function parseDataPoints () {
for (var i = 0; i <= limit; i++)
dataP.push({y: jsDeals[i], label: jsNames[i]});
}
parseDataPoints();
its the tojson part that did the part. Thanks for your help!
You can create a script tag and declare the variables dynamically in the head of your HTML:
<script>
let chartData = { deals: [], names: [] };
{% for deal in deals %}
chartData.deals.push("{{ deal }}");
{% endfor %}
{% for name in names %}
chartData.names.push("{{ name }}");
{% endfor %}
chartData.dataPoints = chartData.deals.map((deal, index) => ({
y: deal,
label: chartData.names[index]
}));
</script>
Then change your existing code to simply use the created variables.
var chart = new CanvasJS.Chart("chartContainer", {
animationEnabled: true,
theme: "light2",
title:{
text: "Top Oil Reserves"
},
axisY: {
title: "Reserves(MMbbl)"
},
labels: names,
data: [{
type: "column",
showInLegend: true,
legendMarkerColor: "grey",
legendText: "MMbbl = one million barrels",
dataPoints: chartData.dataPoints
}]
});
chart.render();
}
Make your own function to do this. First, initialize the chart:
var chart = new CanvasJS.Chart("chartContainer", {
animationEnabled: true,
theme: "light2",
title:{
text: "Your title"
},
axisY: {
title: "Deals"
},
labels: names,
data: [{
type: "column",
showInLegend: true,
legendMarkerColor: "grey",
legendText: "MMbbl = one million barrels",
dataPoints: []
}]
});
Then, you could have a function to initialize your data:
function initData(deals, names, chart) {
var n = deals.length;
for(var i = 0; i < n; i++) {
chart.data[0].dataPoints.push({y: deals[i], label: names[i]})
}
chart.render();
}
After creating the new chart, simply call initData(deals,names,chart);
If you want to add more data to the chart after initializing it, use this function:
function addNewDeal(deal, name, chart) {
chart.data[0].dataPoints.push({y: deal, label: name});
chart.render();
}
Hope this answered your question. Remember, every time that you want to change the data, to see the change you must call chart.render().
edit:
The final result, including the html, should look something like:
<!DOCTYPE html>
<html>
<head>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<script>
function initData(deals, names, chart) {
var n = deals.length;
for(var i = 0; i < n; i++) {
chart.data[0].dataPoints
.push({ y: deals[i], label: names[i]});
}
chart.render();
}
window.onload = () => {
var chart = new CanvasJS.Chart("chartContainer", {
animationEnabled: true,
theme: "light2",
title:{
text: "Your title"
},
axisY: {
title: "Deals"
},
labels: names,
data: [{
type: "column",
showInLegend: true,
legendMarkerColor: "grey",
legendText: "MMbbl = one million barrels",
dataPoints: []
}]
});
chart.render()
var names = ["name1", "name2", "name3"];
var deals = [1,2,3];
initData(deals, names, chart);
}
</script>
</head>
<body>
<div id="chartContainer"></div>
</body>
</html>
I am trying to draw CanvasJs chart using data from json file but for some reason it does not work.
The data which I am trying to display are data which is in json file represented as number "####" and value "#"
Please take a look at the code below.
<!DOCTYPE HTML>
<html>
<head>
<script>
window.onload = function() {
var dataPoints = [];
var chart = new CanvasJS.Chart("chartContainer", {
animationEnabled: true,
theme: "light2",
title: {
text: "Years"
},
axisY: {
title: "Value",
titleFontSize: 24
},
data: [{
type: "column",
yValueFormatString: "# Value",
dataPoints: dataPoints
}]
});
function addData(data) {
for (var i = 0; i < data.length; i++) {
dataPoints.push({
x: new Year(data[i].date),
y: data[i].value
});
}
chart.render();
}
$.getJSON("https://api.worldbank.org/v2/countries/gbr/indicators/UIS.FOSEP.56.F600?format=json", addData);
}
</script>
</head>
<body>
<div id="chartContainer" style="height: 370px; width: 100%;"></div>
<script src="https://canvasjs.com/assets/script/jquery-1.11.1.min.js"></script>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
</body>
</html>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
First you need to call the json, $.getJson gives a callback, so once the api gives the data you need to create the dataPoints, once its created create the chart.
I hope the below solution will solve the issue.
Note: If required you can add a loader for the mean time while its loading , so the user will know that some thing is loading
const chartCreation = (data) => {
$("#chartContainer").CanvasJSChart({
animationEnabled: true,
theme: "light2",
title: {
text: "Years"
},
axisY: {
title: "Value",
titleFontSize: 24
},
data: [{
type: "column",
yValueFormatString: "# Value",
dataPoints: dataPoints
}]
});
}
let dataPoints = [];
const addData = (data) => {
dataPoints = data[1].filter(obj => +(obj.date) >= 2010 && +(obj.date) <=2018
).map(obj => ({x: +(obj.date),
y: obj.value ? obj.value : 0}))
// once we have the data pass it to chart creation
// function
chartCreation(dataPoints);
}
$.getJSON("https://api.worldbank.org/v2/countries/gbr/indicators/UIS.FOSEP.56.F600?format=json", (data) =>{
// pass the data to function
addData(data);
});
return{
}
<script type="text/javascript" src="https://canvasjs.com/assets/script/jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="https://canvasjs.com/assets/script/jquery.canvasjs.min.js"></script>
<div id="chartContainer" style="height: 370px; width: 100%;"></div>
Updated
As per the comment, first you can array.filter , once you filter you will get a new array where you can return the properties whatever that you want. using array.map to return what ever the properties.