Get X-coordinates for bars in chart.js 4 - javascript

I use Chart.js v4.2.1
<html>
<head>
<meta charset="utf-8" />
<title>Bar chart</title>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body>
<div>
<canvas id="barchart"></canvas>
</div>
</body>
<script type="text/javascript">
var canvas = document.getElementById('barchart');
var chart = new Chart(canvas,
{
type: 'bar',
data:
{
labels: ["Audi", "VW", "KIA"],
datasets:
[
{
label: "Cars",
backgroundColor: ["#3e95cd", "#8e5ea2", "#3cba9f"],
data: [2601, 4769, 602],
},
],
},
});
</script>
</html>
To get number of bars I execute chart.data.datasets[0].data.length and get 3.
To get the Y-value for the first bar I do chart.data.datasets[0].data[0] and get 2601.
How do I get the X-values (X-coordinates) for the bars?
(I am not interested in using any plugin).
Added:
Here is a sample where chart.scales.x is defined but chart.scales.y is not.
This happen when I add yAxisID which I need in my complete work.
<html>
<head>
<meta charset="utf-8" />
<title>Bar chart</title>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body>
<div>
<canvas id="barchart"></canvas>
<div id="debug"></div>
</div>
<script type="text/javascript">
var canvas = document.getElementById('barchart');
var chart = new Chart(canvas,
{
type: 'bar',
data:
{
labels: ["Audi", "VW", "KIA"],
datasets:
[
{
label: "Cars",
backgroundColor: ["#3e95cd", "#8e5ea2", "#3cba9f"],
data: [2601, 4769, 602],
yAxisID: "cars",
},
],
},
options:
{
scales:
{
cars:
{
position: "left",
ticks:
{
color: "red",
},
grid:
{
display: true,
},
},
},
},
});
var dataSets = chart.data.datasets;
var xPos = chart.scales.x.getPixelForValue(dataSets[0].data[0]);
try
{
var yPos = chart.scales.cars.getPixelForValue(dataSets[0].data[0]); // --> here y is undefined
document.getElementById("debug").innerHTML = "xPos=" + xPos + ", yPos=" + yPos;
}
catch(e)
{
document.getElementById("debug").innerHTML = "xPos=" + xPos + "<br>" + e;
}
</script>
</body>
</html>

You can use the following code: chartInstance.scales.x.getPixelForValue(chart instance.data.labels[labelIndex]

Related

How to display the value from textfield to column chart

I want to display the value from text field to column chart, I downloaded the code for the chart in this website(https://canvasjs.com/javascript-charts/).
I used this code below but nothing happens. please help me!
<script>
window.onload = function () {
var n1 = document.getElementById('FE');
var n2 = document.getElementById('SE');
var chart = new CanvasJS.Chart("chartContainer", {
animationEnabled: true,
theme: "light2", // "light1", "light2", "dark1", "dark2"
title:{
text: "Average score per Evaluation"
},
axisY: {
title: "FM performance score"
},
data: [{
type: "column",
dataPoints: [
{ y: n1.value, label: "Faculty Self-Evaluation" },
{ y: n2.value, label: "Students' Evaluation" }
]
}]
});
chart.render();
}
</script>
<html>
<head>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
</head>
<body>
<input name="FE" id="FE" type="text" value="4.06" >
<input name="SE" id="SE" type="text" value="5.05" >
<div id="chartContainer"></div>
</body>
</html>
The value need to be passed as a float
Use this in your dataPoints object
dataPoints: [
{ y: parseFloat(n1.value), label: "Faculty Self-Evaluation" },
{ y: parseFloat(n2.value), label: "Students' Evaluation" }
]

Gap between bars C3.js

I want to put gaps between bars.
I tried ;
...
bar:{
width: {
ratio: 0.5
}
},
...
The code above didn't work for me.
The question is: why doesn't it work or how can I make it work?
Try some thing like:
var colors = ['#1f77b4', '#aec7e8', '#ff7f0e'];
var chart = c3.generate({
bindto: '#chart',
data: {
columns: [
['value: ', 20, 14, 3]
],
type: 'bar',
labels: true,
color: function(color, d) {
return colors[d.index];
}
},
axis: {
x: {
type: 'category',
categories: ['cat1', 'cat2', 'cat3']
}
},
bar: {
width: {
ratio: 0.5,
}
},
grid: {
focus: {
show: false
}
}
});
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/c3/0.4.5/c3.min.css" />
</head>
<body>
<div id="chart"></div>
<script src="//cdnjs.cloudflare.com/ajax/libs/d3/3.4.6/d3.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/c3/0.4.5/c3.min.js"></script>
</body>
</html>

How can I show JSON data in Chart.js with Javascript if static values are working but dynamic from mySQL are not?

I have JSON data in the following form:
{
"labels": ["12.11.2016", "13.11.2016", "14.11.2016", ...],
"temperature": ["12", "35", "27", ...],
"humidity": ["56", "70", "87", ...]
}
and want to show it in Chart.js.
I already found this example but it somehow isn't working...
My code for Chart.js is the following:
<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="/node_modules/chart.js/dist/Chart.bundle.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<style>
canvas{
-moz-user-select: none;
-webkit-user-select: none;
-ms-user-select: none;
}
</style>
<title>Temperatur und Feuchtigkeit</title>
</head>
<body>
<div style="width: 100%;">
<canvas id="canvas"></canvas>
</div>
<script>
var data;
$.get('GetTestData.php', function(dataGet) {
data = JSON.parse(dataGet);
//console.log(data['labels']);
});
var randomScalingFactor = function() {
return Math.round(Math.random() * 100);
};
var randomColorFactor = function() {
return Math.round(Math.random() * 255);
};
var randomColor = function(opacity) {
return 'rgba(' + randomColorFactor() + ',' + randomColorFactor() + ',' + randomColorFactor() + ',' + (opacity || '.9') + ')';
};
var config = {
type: 'line',
data: {
//labels: ["11.11.2016", "12.11.2016", "13.11.2016", "14.11.2016", "15.11.2016", "16.11.2016", "17.11.2016"],
labels: labels
datasets: [{
label: "Temperatur",
//data: [randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor()],
data: temperature
fill: false
}//,
//{
// label: "Feuchtigkeit",
// data: [randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor()],
// fill: false
//}]
},
options: {
responsive: true,
title:{
display:true,
text:'Temperatur und Feuchtigkeit'
},
tooltips: {
mode: 'label'
},
hover: {
mode: 'dataset'
},
scales: {
xAxes: [{
display: true,
scaleLabel: {
display: true,
labelString: 'Datum'
}
}],
yAxes: [{
display: true,
scaleLabel: {
display: true,
labelString: 'Wert'
},
ticks: {
suggestedMin: -20,
suggestedMax: 250,
}
}],
}
}
};
var labels = [], temperature=[], humidity=[];
data['labels'].forEach(function(singleResult) {
labels.push(singleResult);
});
data['temperature'].forEach(function(singleResult) {
temperature.push(singleResult);
});
data['humidity'].forEach(function(singleResult) {
humidity.push(singleResult);
});
$.each(config.data.datasets, function(i, dataset) {
dataset.borderColor = randomColor(1.0);
dataset.backgroundColor = randomColor(1.0);
dataset.pointBorderColor = randomColor(1.0);
dataset.pointBackgroundColor = randomColor(1.0);
dataset.pointBorderWidth = 1;
});
window.onload = function() {
var ctx = document.getElementById("canvas").getContext("2d");
window.myLine = new Chart(ctx, config);
};
</script>
</body>
</html>
With static values I get an very nice graph like this:
But the dynamic data load (like in the above code) is not working :/ Does anyone have an idea here?
The error I'm getting is:
SyntaxError: missing } after property list[Weitere Informationen]
I now managed to resolve this on my own, code is below:
<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="/node_modules/chart.js/dist/Chart.bundle.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<style>
canvas{
-moz-user-select: none;
-webkit-user-select: none;
-ms-user-select: none;
}
</style>
<title>Temperatur und Feuchtigkeit</title>
</head>
<body>
<div style="width: 100%;">
<canvas id="canvas"></canvas>
</div>
<script>
var data = [], labels = [], temperature=[], humidity=[];
$.get('GetTestData.php', function(dataGet) {
data = JSON.parse(dataGet);
data['labels'].forEach(function(singleResult) {
labels.push(singleResult);
});
data['temperature'].forEach(function(singleResult) {
temperature.push(singleResult);
});
data['humidity'].forEach(function(singleResult) {
humidity.push(singleResult);
});
var ctx = document.getElementById("canvas").getContext("2d");
window.myLine = new Chart(ctx, config);
});
var randomScalingFactor = function() {
return Math.round(Math.random() * 100);
};
var randomColorFactor = function() {
return Math.round(Math.random() * 255);
};
var randomColor = function(opacity) {
return 'rgba(' + randomColorFactor() + ',' + randomColorFactor() + ',' + randomColorFactor() + ',' + (opacity || '.9') + ')';
};
var config = {
type: 'line',
data: {
labels: labels,
datasets: [{
label: "Temperatur",
data: temperature,
fill: false
},
{
label: "Feuchtigkeit",
data: humidity,
fill: false
}]
},
options: {
responsive: true,
title:{
display:true,
text:'Temperatur und Feuchtigkeit'
},
tooltips: {
mode: 'label'
},
hover: {
mode: 'dataset'
},
scales: {
xAxes: [{
display: true,
scaleLabel: {
display: true,
labelString: 'Datum'
}
}],
yAxes: [{
display: true,
scaleLabel: {
display: true,
labelString: 'Wert'
},
ticks: {
suggestedMin: -20,
suggestedMax: 250,
}
}],
}
}
};
$.each(config.data.datasets, function(i, dataset) {
dataset.borderColor = randomColor(1.0);
dataset.backgroundColor = randomColor(1.0);
dataset.pointBorderColor = randomColor(1.0);
dataset.pointBackgroundColor = randomColor(1.0);
dataset.pointBorderWidth = 1;
});
window.onload = function() {
var ctx = document.getElementById("canvas").getContext("2d");
window.myLine = new Chart(ctx, config);
};
</script>
</body>
</html>
Result looks as following:

displaying funnel chart using flot.js and data source as external json file

i am trying to plot a funnel chart using flot.js library ,taking an external json file as input but although the json is fetched it is not working as a datasource and the chart is not being plotted.
guys i have a json file SAMPLE.JSON
[
{
"data": 10,
"label": "a"
},
{
"data": 81,
"label": "b"
},
{
"data": 20,
"label": "c"
},
{
"data": 90,
"label": "d"
}
]
but it not working as a datasource for the Plot function of the folt.js library
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Flot Examples: Funnel Charts</title>
<link href="css/examples.css" rel="stylesheet" type="text/css">
<script language="javascript" type="text/javascript" src="js/jquery.js"></script>
<script language="javascript" type="text/javascript" src="js/jquery.flot.js"></script>
<script language="javascript" type="text/javascript" src="js/jquery.flot.funnel.js"></script>
<script type="text/javascript">
$(function() {
var data;
$.getJSON("sample.json", function(json) {
data=json;
console.log(data);
});
var placeholder = $("#placeholder");
$.plot('#placeholder', data, {
series:{
funnel: {
show: true,
stem: {
height: 0.2,
width: 0.4
},
margin: {
//right: 0.15
},
label:{
show: true,
align: "center",
threshold: 0.05,
formatter: labelFormatter
},
highlight: {
opacity: 0.2
}
},
},
grid: {
hoverable: true,
clickable: true
}
});
placeholder.bind("plotclick", function(event, pos, obj) {
if (!obj) {
return;
}
alert(obj.series.label + ": " + obj.series.value);
});
function labelFormatter(label, series) {
return "<div style='font-size:11pt; text-align:center; padding:2px; color:#fff;'>"+series.value+"</div>";
}
});
</script>
</head>
<body>
<div id="header">
<h2 style='text-align:center'>Funnel Charts</h2>
</div>
<div id="content">
<h3 id="title"></h3>
<div class="demo-container">
<div id="placeholder" class="demo-placeholder" style="length:250px,width:250px"></div>
</div>
</div>
</body>
</html>
Your data is in the wrong format. From the plugin documentation, the expected data format is (your data isn't in an array of arrays):
var data = [
{
label: "a",
data: [ [ 1, 10 ] ]
},
{
label: "b",
data: [ [ 1, 81 ] ]
},
{
label: "c",
data: [ [ 1, 20 ] ]
},
{
label: "d",
data: [ [ 1, 90 ] ]
}
];
This JS Fiddle has a working example of a funnel chart with your data.

Highcharts - how to display multiple graphs on one page using multiple xml files

Is there a way to list let's say 2 charts on the same page where each chart has its data xml file? What I'm doing is generating xml files from rrdtool and I would like to view all charts for the same device on one page.
Here's the code I have that works for one chart:
test.html:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/data.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<script src="js/test.js" type="text/javascript"></script>
<script type="text/javascript">
$.ajax({
type: "GET",
url: "xml/test.xml",
dataType: "xml",
success: function(xml) {
var series = []
//define series
$(xml).find("entry").each(function() {
var seriesOptions = {
name: $(this).text(),
data: []
};
options.series.push(seriesOptions);
});
//populate with data
$(xml).find("row").each(function() {
var t = parseInt($(this).find("t").text()) * 1000
$(this).find("v").each(function(index) {
var v = parseFloat($(this).text())
v = v || null
if (v != null) {
options.series[index].data.push([t, v])
};
});
});
options.title.text = "CPU - Last 3 hours"
$.each(series, function(index) {
options.series.push(series[index]);
});
chart = new Highcharts.Chart(options);
}
})
</script>
</head>
<body>
<div id="cpu" style="width: 800px; height: 400px; margin: 0 auto; padding: 20px"></div>
</body>
</html>
test.js
Highcharts.setOptions({
global: {
useUTC: false
}
});
options = {
chart: {
renderTo: 'cpu',
type: 'area',
},
title: {
text: 'CPU'
},
subtitle: {
text: ''
},
xAxis: {
type: 'datetime',
dateTimeLabelFormats: {
hour: '%H. %M',
}
},
yAxis: {
title: {
text: 'Utilization %'
}
},
tooltip: {
formatter: function() {
return '<b>' + this.series.name + '</b><br/>' + Highcharts.dateFormat('%H:%M', this.x) + ': ' + Highcharts.numberFormat(this.y, 2) + ' %';
}
},
plotOptions: {
area: {
fillColor: {
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1},
stops: [
[0, Highcharts.getOptions().colors[1]],
[1, Highcharts.Color(Highcharts.getOptions().colors[0]).setOpacity(0).get('rgba')]
]
},
lineWidth: 1,
marker: {
enabled: false
},
shadow: true,
states: {
hover: {
lineWidth: 1
}
},
threshold: null
}
},
series: []
}
And XML file - test.xml:
<?xml version="1.0" encoding="ISO-8859-1"?>
<xport>
<meta>
<start>1396030800</start>
<step>300</step>
<end>1396030800</end>
<rows>4</rows>
<columns>1</columns>
<legend>
<entry>cpu</entry>
</legend>
</meta>
<data>
<row><t>1396030800</t><v>2.8000000000e+01</v></row>
<row><t>1396031100</t><v>2.9780000000e+01</v></row>
<row><t>1396031400</t><v>3.1596666667e+01</v></row>
<row><t>1396041600</t><v>NaN</v></row>
</data>
</xport>
I encountered the same problem and just solved it!
Before the ready() function:
var chart;
var chart1;
$( document ).ready(function() {
your code....
I created two options, each options render to a different container
options = {
chart: {
renderTo: 'container',
type: 'area',
},
options2 = {
chart: {
renderTo: 'container2',
type: 'area',
},
and use the code below to add to different container:
chart = new Highcharts.Chart(options);
chart1 = new Highcharts.Chart(options2);
then in your html:
<div id="container">
<div id="container2">
Hope this brief explanation helps. Feel free to ask me if anything is not clear to you.
Cheers,

Categories

Resources