cannot display the line chart - javascript

I want to add a js line chart for my JSP page. But it does not display on the page. Can't figure out the error also. This is my code. Any help on this is appreciated.
window.onload = function() {
var chart = new CanvasJS.Chart("chartContainer", {
animationEnabled: true,
theme: "light2",
title: {
text: "Title"
},
axisX: {
title: "Year"
},
axisY: {
title: "Value",
includeZero: true,
},
data: [{
name: "A",
type: "spline",
showInLegend: true,
dataPoints: <%out.write(dataPoints);%>
}]
});
chart.render();
}
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%# page import="java.util.*" %>
<%# page import="com.google.gson.Gson"%>
<%# page import="com.google.gson.JsonObject"%>
<%
Gson gsonObj = new Gson();
Map<Object,Object> map = null;
List<Map<Object,Object>> list = new ArrayList<Map<Object,Object>>();
map = new HashMap<Object,Object>();
map.put("x","2017");
map.put("y", 188);
list.add(map);
map = new HashMap<Object,Object>();
map.put("x","2018");
map.put("y", 200);
list.add(map);
map = new HashMap<Object,Object>();
map.put("x","2019");
map.put("y", 202);
list.add(map);
String dataPoints = gsonObj.toJson(list);
%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<div>
<div id="chartContainer" style="height: 370px; width: 100%;"></div>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
</div>
</body>

Related

Get X-coordinates for bars in chart.js 4

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]

JointJS:Hello World example doesn't work

Hello I'm trying to execute Hello world application using JointJS library as given in: http://www.jointjs.com/tutorial#hello-world
I have downloaded joint.js(1.0.2) and joint.css files, copied the code given in HelloWorld tutorial in html file, and accessed it from the Chrome browser but it's not working as shown in the tutorial.
Console.error: Uncaught TypeError: this.addCell is not a function
html is:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<meta name="description" content=""/>
<meta name="author" content=""/>
<title>diagram</title>
<link rel="stylesheet" href="node_modules/joint/joint.min.css">
<body>
<div id="diaHolder">
</div>
<script src="node_modules/jquery/dist/jquery.min.js"></script>
<script src="node_modules/lodash/lodash.min.js"></script>
<script src="node_modules/backbone/backbone-min.js"></script>
<script src="node_modules/joint/joint.min.js"></script>
<script>
var graph = new joint.dia.Graph;
var paper = new joint.dia.Paper({
el: $('#diaHolder'),
width: 600,
height: 200,
model: graph,
gridSize: 1
});
var rect = new joint.shapes.basic.Rect({
position: { x: 100, y: 30 },
size: { width: 100, height: 30 },
attrs: { rect: { fill: 'blue' }, text: { text: 'my box', fill: 'white' } }
});
var rect2 = rect.clone();
rect2.translate(300);
var link = new joint.dia.Link({
source: { id: rect.id },
target: { id: rect2.id }
});
graph.addCells([rect, rect2, link]);
</script>
</body>
</html>
check versions of dependencies, especial Lodash. JointJS it's not compatible with version 4.x
jQuery: 2.2.4
Lodash: 3.10.1
Backbone: 1.3.3
Just throwing this out there but do you have a starting html tag?

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.

How to pass JSP array to Javascript of highchart to generate a column chart

I am a novice in Highcharts, JSP and Javascript and need your input and suggestion on the issue, I have been struggling since 4-5 days. Please help me.
The issue is I am able to get the 2 output arrays from JSP that I need to pass in the highchart JS for generate a column graph.
[99, 90, 87, 82, 80, 77, 70, 65, 65, 60] and
['orcl2','orcl2','orcl2','orcl2','orcl1','orcl1','orcl3','orcl2','orcl3','orcl1']
But I am not able to pass the value to the JS to generate the column graph. Following is the entire code that I am using. Please suggest me where I am going wrong.
<%# page language="java" import="java.sql.*, java.io.*, java.util.Date, java.util.*,javax.servlet.*, java.text.SimpleDateFormat, java.util.Calendar " %>
<% Class.forName("oracle.jdbc.driver.OracleDriver"); %>
<%
Connection connection=DriverManager.getConnection ("jdbc:oracle:thin:#RAC1.dinu.com:1521:orcl2","cog","cog123");
Statement statement12 = connection.createStatement();
ResultSet resultset12 =
statement12.executeQuery("select * from(select HOST_NAME,INSTANCE_NAME,PID,PCPU, to_char(TIME, 'yyyy-mm-dd hh24:mi:ss') from ORA_CPU_STATUS where trunc(TIME)=trunc(sysdate) order by PCPU desc) where rownum<=10");
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Highcharts Example</title>
<script type="text/javascript" src="/DBdashboard/1.js"></script>
<script type="text/javascript" src="/DBdashboard/2a.js"></script>
<script type="text/javascript" src="/DBdashboard/3a.js"></script>
<script type="text/javascript" src="/DBdashboard/highcharts-more.js"></script>
<script type="text/javascript" src="/DBdashboard/json2.js"></script>
<script>
$(function () {
var chart;
<%
List<String> list = new ArrayList<String>();
List<String> list2 = new ArrayList<String>();
while(resultset12.next())
{
String val = resultset12.getString(1);
list.add(val);
String val2 = resultset12.getString(2);
list2.add(val2);
String csv = list2.toString().replace("[", "").replace("]", "");
String csvWithQuote = list.toString().replace("[", "'").replace("]", "'").replace(", ", "','");
%>
var dincpu = '<%=csv%>';
var dinpcat = '<%=csvWithQuote%>';
var input = JSON.parse("[" + dincpu + "]"),
data = [],
categories = JSON.parse("[" + dinpcat + "]");
$.each(input, function(index, value){
var color;
if (value > 80) color = 'red';
else if (value > 60) color = 'Orange';
else color = 'green';
data.push({y:value, color: color, url:'https://www.google.com'});
});
$(document).ready(function() {
chart = new Highcharts.Chart({
chart: {
renderTo: 'COL',
type: 'column'
},
title: {
text: 'Current Top 10 CPU Consumers',
style: {fontSize: '10px'}
},
xAxis: {
categories: categories,
labels: {
rotation: -35,
align: 'center'
}
},
yAxis: {
title: {
text: 'Percentage',
style: {fontSize: '11px'}
}
},
exporting: { enabled: false },
legend: {
enabled: false,
},
tooltip: {
formatter: function() {
return '<b>'+ this.x +'</b>' +'- Oracle User Process CPU Consumed :'+'<b>'+ this.y +' % ' +'</b>' ;
}
},
plotOptions: {
series: {
cursor: 'pointer',
point: {
events: {
click: function() {
location.href = this.options.url;
}
}
}
}
},
series: [{
name: 'CPU Consumed',
pointWidth: 28,
data: data
}]
});
});
});
</script>
</head>
<body>
<div id="COL" style="min-width: 100px; height: 300px; margin: 0 auto"></div>
</body>
</html>
Thanks in Advance...
I'm not really sure where you're going with this code
String csv = list2.toString().replace("[", "").replace("]", "");
String csvWithQuote = list.toString().replace("[", "'").replace("]", "'").replace(", ", "','");
%>
var dincpu = '<%=csv%>';
var dinpcat = '<%=csvWithQuote%>';
var input = JSON.parse("[" + dincpu + "]"),
data = [],
categories = JSON.parse("[" + dinpcat + "]");
If you have your data in this format:
[99, 90, 87, 82, 80, 77, 70, 65, 65, 60] and
['orcl2','orcl2','orcl2','orcl2','orcl1','orcl1','orcl3','orcl2','orcl3','orcl1']
Why not do this (remove the 's and get rid of the JSON.parse)?
var dincpu = <%=csv%>;
var dinpcat = <%=csvWithQuote%>;
http://jsfiddle.net/VYLTW/
#Barbara,
it worked finally with
var dincpu = <%=csv%>;
var dinpcat = <%=csvWithQuote%>;
along with the fiddle that you gave http://jsfiddle.net/VYLTW/ .
I am putting the entire code in Answer that actually worked.
<%# page language="java" import="java.sql.*, java.io.*, java.util.Date, java.util.*,javax.servlet.*, java.text.SimpleDateFormat, java.util.Calendar " %>
<% Class.forName("oracle.jdbc.driver.OracleDriver"); %>
<%
Connection connection=DriverManager.getConnection ("jdbc:oracle:thin:#RAC1.dinu.com:1521:orcl2","cog","cog123");
Statement statement12 = connection.createStatement();
ResultSet resultset12 =
statement12.executeQuery("select * from(select INSTANCE_NAME,PCPU from ORA_CPU_STATUS order by PCPU desc) where rownum<=10");
List<String> list = new ArrayList<String>();
List<String> list2 = new ArrayList<String>();
while(resultset12.next())
{
String val = resultset12.getString(1);
list.add(val);
String val2 = resultset12.getString(2);
list2.add(val2);
}
String csv = list2.toString();
String csvWithQuote = list.toString().replace("[", "['").replace("]", "']").replace(", ", "','");
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Highcharts Example</title>
<script type="text/javascript" src="/DBdashboard/1.js"></script>
<script type="text/javascript" src="/DBdashboard/2a.js"></script>
<script type="text/javascript" src="/DBdashboard/3a.js"></script>
<script type="text/javascript" src="/DBdashboard/highcharts-more.js"></script>
<script type="text/javascript" src="/DBdashboard/json2.js"></script>
<script>
$(function () {
var dincpu=<%=csv%>;
var dinpcat = <%=csvWithQuote%>;
var input = dincpu,
data = [],
categories =dinpcat;
$.each(input, function(index, value){
var color;
if (value > 80) color = 'red';
else if (value > 60) color = 'Orange';
else color = 'green';
data.push({y:value, color: color, url:'https://www.google.com'});
});
chart = new Highcharts.Chart({
chart: {
renderTo: 'COL',
type: 'column'
},
title: {
text: 'Current Top 10 CPU Consumers',
style: {fontSize: '10px'}
},
xAxis: {
categories: categories,
labels: {
rotation: -35,
align: 'center'
}
},
yAxis: {
title: {
text: 'Percentage',
style: {fontSize: '11px'}
}
},
exporting: { enabled: false },
legend: {
enabled: false,
},
tooltip: {
formatter: function() {
return '<b>'+ this.x +'</b>' +'- Oracle User Process CPU Consumed :'+'<b>'+ this.y +' % ' +'</b>' ;
}
},
plotOptions: {
series: {
cursor: 'pointer',
point: {
events: {
click: function() {
location.href = this.options.url;
}
}
}
}
},
series: [{
name: 'CPU Consumed',
pointWidth: 28,
data: data
}]
});
});
</script>
</head>
<body>
<div id="COL" style="min-width: 100px; height: 300px; margin: 0 auto"></div>
</body>
</html>
#Barbara,
1) If you see the latest code I have put all the JSP scriptlet "<% %>" at the top and then called the
var dincpu = <%=csv%>;
var dinpcat = <%=csvWithQuote%>;
After which I could see in view source of the webpage that the values are getting passed to the JS variables in the JS function.
2) Then put the same JS code that you have put in the fiddle.
3) I felt that the function $(document).ready(function() was causing problem which I removed.
And another important thing is that since I was putting all my code in a virtual linux box, there might be some hidden characters thats getting copied while I was coping from windows text editor (Editplus).
I found all those 3 things were responsible for the issue.

Reading a CSV with Highchart

I'm struggling to output a line chart from my CSV file, I get the graph but not data in the graph, could someone please tell me what is wrong with the code below?
The data in the CSV is formatted like so:
26-04-2012 09:10,0
26-04-2012 09:20,0
26-04-2012 09:30,0
26-04-2012 09:40,0
26-04-2012 09:50,0
26-04-2012 10:00,1
26-04-2012 10:10,1
HTML code:
<!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>Test</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script src="../../js/highcharts.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
var c = [];
var d = [];
$.get('test.csv', function(data) {
var lines = data.split('\n');
$.each(lines, function(lineNo, line) {
var items = line.split(',');
c.push(items[0]);
d.push(parseInt(items[1]));
});
});
var options = {
chart: {
renderTo: 'chart',
defaultSeriesType: 'line'
},
title: {
text: 'reading'
},
xAxis: {
title: {
text: 'Date Measurement'
},
categories: c
},
yAxis: {
title: {
text: 'reading'
}
},
series: [{
data: d
}]
};
var chart = new Highcharts.Chart(options);
});
</script>
</head>
<body>
<div id="chart" style="width: 800px; height: 400px; margin: 0 auto"></div>
</body>
</html>
The problem is that the $.get call will return immediately and as a result you will create the chart before the test.csv is downloaded (containing no data at all).
The callback function that you pass to $.get will run when the file is downloaded so placing the creation of the chart there would solve the problem.
The chart is loaded with no data because the csv file is loaded after the chart, because the get request takes time to receive a response. The following will load the data from your file and display the chart after the file loads.
<!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>Test</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script src="../../js/highcharts.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
var c = [];
var d = [];
var options = {
chart: {
renderTo: 'chart',
defaultSeriesType: 'line'
},
title: {
text: 'reading'
},
xAxis: {
title: {
text: 'Date Measurement'
},
categories: c
},
yAxis: {
title: {
text: 'reading'
}
},
series: [{
data: d
}]
};
var jqxhr = $.get('test.csv', function(data) {
var lines = data.split('\n');
$.each(lines, function(lineNo, line) {
var items = line.split(',');
c.push(items[0]);
d.push(parseInt(items[1]));
})
var chart = new Highcharts.Chart(options);
});
});
</script>
</head>
<body>
<div id="chart" style="width: 800px; height: 400px; margin: 0 auto"></div>
</body>
</html>

Categories

Resources