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>
Related
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]
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>
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,
It doesn't work on all three browsers - IE, Chrome and Firefox.
Here's the source code for my HTML:
<html>
<head>
<script type ="text/javascript" src ="jquery-1.10.2.js" ></script>
<script type ="text/javascript" src ="highcharts.js" ></script>
<script type ="text/javascript" src ="exporting.js" ></script>
<script type ="text/javascript" src ="fruits.js" ></script>
</head>
<body>
<div id="container" style="min-width: 310px; height: 400px; margin: 0 auto"></div>
</body>
</html>
Here's the source code for what I have in the fruits.js script:
$(document).ready(function () {
var options = {
chart: {
renderTo: 'container',
type: 'column'
},
title: {
text: 'Fruit Consumption'
},
xAxis: {
categories: []
},
yAxis: {
title: {
text: 'Units'
}
},
series: []
};
$.get('data.csv', function (data) {
// Split the lines
var lines = data.split('\n');
// Iterate over the lines and add categories or series
$.each(lines, function (lineNo, line) {
var items = line.split(',');
// header line containes categories
if (lineNo == 0) {
$.each(items, function (itemNo, item) {
if (itemNo > 0) options.xAxis.categories.push(item);
});
}
// the rest of the lines contain data with their name in the first
// position
else {
var series = {
data: []
};
$.each(items, function (itemNo, item) {
if (itemNo == 0) {
series.name = item;
} else {
series.data.push(parseFloat(item));
}
});
options.series.push(series);
}
});
// Create the chart
var chart = new Highcharts.Chart(options);
});
});
So any idea why isn't the chart displays anything at all? It does works without the CSV data file though
This is what I have in my csv file:
Categories,Apples,Pears,Oranges,Bananas
John,8,4,6,5
Jane,3,4,2,3
Joe,86,76,79,77
Janet,3,16,13,15
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.