I wanted to include the JavaScript framework Chartjs into my JSP project. I tried a very simple bar chart with just one date (an average number of points). But it doesn't seem to have worked correctly. Here is a screenshot of the canvas object where I created the chart: http://i43.tinypic.com/15wc6md.png
My code is:
<canvas id="chartjs"></canvas>
<script>
//Get context with jQuery - using jQuery's .get() method.
var ctx = $("#chartjs").get(0).getContext("2d");
//This will get the first returned node in the jQuery collection.
var myNewChart = new Chart(ctx);
var data = {
labels : ["Durchschnittsgesamtpunktzahl aller Teilnehmer"],
datasets : [
{
fillColor : "rgba(220,220,220,0.5)",
strokeColor : "rgba(220,220,220,1)",
data : [<%=examAveragePoints%>]
}
]
}
var options = {
//Boolean - If we show the scale above the chart data
scaleOverlay : false,
//Boolean - If we want to override with a hard coded scale
scaleOverride : false,
//** Required if scaleOverride is true **
//Number - The number of steps in a hard coded scale
scaleSteps : null,
//Number - The value jump in the hard coded scale
scaleStepWidth : null,
//Number - The scale starting value
scaleStartValue : null,
//String - Colour of the scale line
scaleLineColor : "rgba(0,0,0,.1)",
//Number - Pixel width of the scale line
scaleLineWidth : 1,
//Boolean - Whether to show labels on the scale
scaleShowLabels : true,
//Interpolated JS string - can access value
scaleLabel : true,
//String - Scale label font declaration for the scale label
scaleFontFamily : "'Arial'",
//Number - Scale label font size in pixels
scaleFontSize : 12,
//String - Scale label font weight style
scaleFontStyle : "normal",
//String - Scale label font colour
scaleFontColor : "#666",
///Boolean - Whether grid lines are shown across the chart
scaleShowGridLines : true,
//String - Colour of the grid lines
scaleGridLineColor : "rgba(0,0,0,.05)",
//Number - Width of the grid lines
scaleGridLineWidth : 1,
//Boolean - If there is a stroke on each bar
barShowStroke : true,
//Number - Pixel width of the bar stroke
barStrokeWidth : 2,
//Number - Spacing between each of the X value sets
barValueSpacing : 5,
//Number - Spacing between data sets within X values
barDatasetSpacing : 1,
//Boolean - Whether to animate the chart
animation : true,
//Number - Number of animation steps
animationSteps : 60,
//String - Animation easing effect
animationEasing : "easeOutQuart",
//Function - Fires when the animation is complete
onAnimationComplete : null
}
new Chart(ctx).Bar(data,options);
</script>
The problem is that you only have one object in your dataset.
Chart.js sets the object with the lowest number to 0 on the y-axis. I'm facing the same problem but I havent found a solution yet. It seems to be a common problem with Chart.js
https://github.com/nnnick/Chart.js/issues/252
Try to use a hardcoded scale.
Related
I am trying to use the Charts.js library in my android app inside a webview. I tried changing it to chartsnew.js library too, but I get the same error and the chart does not load in my app.
D/chromium: Unknown chromium error: -6
I have tried searching all forums and questions posted before, tried double checking that the URL to my file is correct and that the JavaScript is also enabled inside.
The app originally used an ajax request to pull data, but since things were not working I tried putting the static data. The graphs load and show if I open the file directly in chrome. But shows a blank canvas in android webview.
HTML File attached :
<html>
<head>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="../general/js/ChartNew.js"></script>
<script src="../general/js/shapesInChart.js"></script>
<style>
canvas {
-moz-user-select: none;
-webkit-user-select: none;
-ms-user-select: none;
}
</style>
</head>
<canvas id="myChart" width="400" height="400"></canvas>
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
options = {
//Boolean - If we show the scale above the chart data
scaleOverlay : false,
//Boolean - If we want to override with a hard coded scale
scaleOverride : false,
//** Required if scaleOverride is true **
//Number - The number of steps in a hard coded scale
scaleSteps : null,
//Number - The value jump in the hard coded scale
scaleStepWidth : null,
//Number - The scale starting value
scaleStartValue : null,
//String - Colour of the scale line
scaleLineColor : "rgba(0,0,0,.1)",
//Number - Pixel width of the scale line
scaleLineWidth : 1,
//Boolean - Whether to show labels on the scale
scaleShowLabels : false,
//Interpolated JS string - can access value
scaleLabel : "<%=value%>",
//String - Scale label font declaration for the scale label
scaleFontFamily : "'Arial'",
//Number - Scale label font size in pixels
scaleFontSize : 12,
//String - Scale label font weight style
scaleFontStyle : "normal",
//String - Scale label font colour
scaleFontColor : "#666",
///Boolean - Whether grid lines are shown across the chart
scaleShowGridLines : true,
//String - Colour of the grid lines
scaleGridLineColor : "rgba(0,0,0,.05)",
//Number - Width of the grid lines
scaleGridLineWidth : 1,
//Boolean - If there is a stroke on each bar
barShowStroke : true,
//Number - Pixel width of the bar stroke
barStrokeWidth : 2,
//Number - Spacing between each of the X value sets
barValueSpacing : 5,
//Number - Spacing between data sets within X values
barDatasetSpacing : 1,
//Boolean - Whether to animate the chart
animation : true,
//Number - Number of animation steps
animationSteps : 60,
//String - Animation easing effect
animationEasing : "easeOutQuart",
//Function - Fires when the animation is complete
onAnimationComplete : null
};
var data = {
labels : ["January","February","March","April","May","June","July"],
datasets : [
{
fillColor : "rgba(220,220,220,0.5)",
strokeColor : "rgba(220,220,220,1)",
data : [65,59,90,81,56,55,40]
},
{
fillColor : "rgba(151,187,205,0.5)",
strokeColor : "rgba(151,187,205,1)",
data : [28,48,40,19,96,27,100]
}
]
}
ctx = $("#myChart").get(0).getContext("2d");
myNewChart = new Chart(ctx).Bar(data, options);
});
</script>
</html>
EDIT 1 :
ok So I was not able to load the local HTML file inside the android web-view, no matter what I tried. But then I still moved ahead and tried to modify my code to get the dynamic data from an ajax request. Surprisingly, it has started working on the dynamic data
Here is my code for the dynamic pull :
<html>
<head>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="../general/js/Chart.js"></script>
<script src="../general/js/Chartjs.js"></script>
<style>
canvas {
-moz-user-select: none;
-webkit-user-select: none;
-ms-user-select: none;
}
</style>
</head>
<canvas id="myChart" width="350" height="350"></canvas>
<script type="text/javascript" charset="utf-8">
var id=replaceName;
var regDate = replaceDate;
$(document).ready(function() {
$.ajax({
url:"<serverurl>customer/betGetBloodPressure.jsp",
data:{"id":id,"regDate":regDate},
type:"post",
dataType:"jsonp",
jsonp: "callback",
success: function(res) {
options = {
//Boolean - If we show the scale above the chart data
scaleOverlay : false,
//Boolean - If we want to override with a hard coded scale
scaleOverride : true,
//** Required if scaleOverride is true **
//Number - The number of steps in a hard coded scale
scaleSteps : 3,
//Number - The value jump in the hard coded scale
scaleStepWidth : 50,
//Number - The scale starting value
scaleStartValue : 0,
//String - Colour of the scale line
scaleLineColor : "rgba(0,0,0,.1)",
//Number - Pixel width of the scale line
scaleLineWidth : 1,
//Boolean - Whether to show labels on the scale
scaleShowLabels : true,
//Interpolated JS string - can access value
scaleLabel : "<%=value%>",
//String - Scale label font declaration for the scale label
scaleFontFamily : "'sans-serif'",
//Number - Scale label font size in pixels
scaleFontSize : 12,
//String - Scale label font weight style
scaleFontStyle : "normal",
//String - Scale label font colour
scaleFontColor : "#666",
///Boolean - Whether grid lines are shown across the chart
scaleShowGridLines : true,
//String - Colour of the grid lines
scaleGridLineColor : "rgba(0,0,0,.05)",
//Number - Width of the grid lines
scaleGridLineWidth : 1,
//Boolean - If there is a stroke on each bar
barShowStroke : true,
//Number - Pixel width of the bar stroke
barStrokeWidth : 2,
//Number - Spacing between each of the X value sets
barValueSpacing : 5,
//Number - Spacing between data sets within X values
barDatasetSpacing : 0,
//Boolean - Whether to animate the chart
animation : true,
//Number - Number of animation steps
animationSteps : 60,
//String - Animation easing effect
animationEasing : "easeOutQuart",
//Function - Fires when the animation is complete
onAnimationComplete : null,
spaceBetweenBar : 0 ,
// String or array - fill color when hovered
hoverBackgroundColor: "rgba(255,99,132,0.4)",
// String or array - border color when hovered
hoverBorderColor: "rgba(255,99,132,1)"
};
var data = {
labels : ['MIN BP', 'AVERAGE BP', 'MAX BP'],
datasets :
[
{
label: 'Max Average Of Age #',
fillColor: '#a280ff',
data: [parseInt(res.aoa_lower_low),parseInt(res.aoa_avg_low),parseInt(res.aoa_higer_low)],
yAxisID: "y-axis-0"
},
{
label: 'My Info. #',
fillColor: '#7c4dff',
data: [parseInt(res.my_low),parseInt(res.my_avg),parseInt(res.my_high)]
},
{
label: 'Min Average Of Age #',
fillColor: '#6933ff',
data: [parseInt(res.aoa_lower_high),parseInt(res.aoa_avg_high),parseInt(res.aoa_higer_high)]
}
]
};
scaleSteps = 10;
ctx = $("#myChart").get(0).getContext("2d");
myNewChart = new Chart(ctx).Bar(data,options);
}
});
});
</script>
</html>
Now am struggling with one last problem, as seen in the screenshot my graph appears, but am not able to show the label values which can show me what each of my color indicates defined as the "label" parameter in the above code inside the datasets. Looks like I am missing something I need to define in my options, but not able to find out what. Please help
Graph pulled from AJAX Request
okay so I finally found the solution to the problem of my second EDIT in which label values descriptions for my color was not showing up.
Just added :
multiTooltipTemplate: "<%= datasetLabel %> - <%= value %>"
to my options. And awesome it works now. :)
Working Sample Image
I am using dojo to create a bar chart with multiple vertical axes (one for an actual count, the other for a percentage), and when I do, the title for the right axis always gets cut off (i.e., the half of it that's furthest from the chart gets cut off by the edge of the chart). I've already tried using chart.resize(w,h), but this only shrinks the data in the chart, while maintaining the same margins from the edge (and thus the same title cut as before). Does anyone know how to get the title to properly display? For reference, here's the code I'm using, both to create the div node and the chart.
chartNode = domConstruct.create("div", {
id : this.context.viewid + "_ChartNode",
}, this.context.element, "first");
domStyle.set(chartNode, {
width : "800px",
height : "400px"
});
var chart = new Chart(chartNode);
chart.addPlot("default", {
type : "Columns",
markers : true,
gap : 5
});
chart.addPlot("something", {
type : "Columns",
vAxis : "percent"
});
chart.addAxis("x", {
title : "Person",
titleOrientation : "away",
minorTicks : false,
majorTickStep : 1,
dropLabels : false
});
chart.addAxis("y", {
vertical : true,
fixLower : "includeZero",
title : "Count",
min : 0,
max : data[0].totalSubmitted
});
chart.addAxis("percent", {
title : "Percentage",
titleGap : 20,
vertical : true,
leftBottom : false,
fixLower : "includeZero",
min : 0,
max : 100,
})
chart.addSeries("y", data);
chart.render();
Edit: This is what my code is actually generating, with the cutoff being highlighted in red.
I am trying to use chartsjs to make a pie chart. I have followed the steps in the chartjs documentation and I have included chart.js and the canvas element. i added the script that should create the chart as the example provided in the chartjs documentation. I am getting the following error:
Uncaught TypeError: Cannot read property 'canvas' of undefined
Does anywhone know how to fix this? What am I doing wrong?
Thanx in advance!
HERE IS THE CODE:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="<?php echo base_url(); ?>media/js/chart.js"></script>
<script type="text/javascript" src="<?php echo base_url(); ?>media/js/jquery.js"></script>
</head>
<canvas id="myChart" width="400" height="400"></canvas>
<script type="text/javascript">
$(function() {
options = {
//Boolean - Show a backdrop to the scale label
scaleShowLabelBackdrop: true,
//String - The colour of the label backdrop
scaleBackdropColor: "rgba(255,255,255,0.75)",
// Boolean - Whether the scale should begin at zero
scaleBeginAtZero: true,
//Number - The backdrop padding above & below the label in pixels
scaleBackdropPaddingY: 2,
//Number - The backdrop padding to the side of the label in pixels
scaleBackdropPaddingX: 2,
//Boolean - Show line for each value in the scale
scaleShowLine: true,
//Boolean - Stroke a line around each segment in the chart
segmentShowStroke: true,
//String - The colour of the stroke on each segement.
segmentStrokeColor: "#fff",
//Number - The width of the stroke value in pixels
segmentStrokeWidth: 2,
//Number - Amount of animation steps
animationSteps: 100,
//String - Animation easing effect.
animationEasing: "easeOutBounce",
//Boolean - Whether to animate the rotation of the chart
animateRotate: true,
//Boolean - Whether to animate scaling the chart from the centre
animateScale: false,
//String - A legend template
legendTemplate: "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<segments.length; i++){%><li><span style=\"background-color:<%=segments[i].fillColor%>\"></span><%if(segments[i].label){%><%=segments[i].label%><%}%></li><%}%></ul>"
};
data = [
{
value: 300,
color: "#F7464A",
highlight: "#FF5A5E",
label: "Red"
},
{
value: 50,
color: "#46BFBD",
highlight: "#5AD3D1",
label: "Green"
},
{
value: 100,
color: "#FDB45C",
highlight: "#FFC870",
label: "Yellow"
}
];
ctx = $("#myChart").get(0).getContext("2d");
myNewChart = new Chart(ctx[0]).Pie(data, options);
});
</script>
</html>
The problem lies on this line here:
myNewChart = new Chart(ctx[0]).Pie(data, options);
And in specifically ctx[0]. When you defined ctx here:
ctx = $("#myChart").get(0).getContext("2d");
ctx is an object called CanvasRenderingContext2D, which haves properties. You are trying to treat it as an Array when it's not. ctx[0] is therefore undefined. So the solution is actually simple, as you have found out.
Change ctx[0] to ctx, and you have your nice animated pie chart.
ctx = $("#myChart").get(0).getContext("2d");
myNewChart = new Chart(ctx).Pie(data, options);
Fiddle Here
My solution is a little different, as I wanted to have the chart change dynamically (in my application, it's moving with a slider) but avoid the awful flickering.
After standard instantiation, I update on slider drag like so:
var chartData = getChartData();
for(var i=0; i<chartData.length; i++)
{
barChart.datasets[0].bars[i].value = chartData[i];
}
barChart.update();
This animates teh change nicely, but after the animation is finished, in order to keep the weird flickering from happening when the user hovers the mouse over (the tooltip is also essential for me), I destroy and recreate the chart on mouse up as follows:
if(barChart) {
barChart.clear();
barChart.destroy();
}
chartDataObject = getChartData();
var chartData = {
labels: getChartLabels(),
datasets: [
{
label: "label",
fillColor: "rgba(151,187,205,0.5)",
strokeColor: "rgba(151,187,205,0.8)",
highlightFill: "rgba(151,187,205,0.75)",
highlightStroke: "rgba(151,187,205,1)",
data: chartDataObject
}
]
};
var chartContext = $("#visualizeEfficacyBar").get(0).getContext("2d");
barChart = new Chart(chartContext).Bar(chartData, { tooltipTemplate: "<%if (label){%><%=label%>: <%}%><%= value %>", responsive : true , animate : false, animationSteps : 1 });
The important thing here is not to animate the recreation cause it leads to a very awkward visual effect, setting animate : false did not do the trick, but animationSteps : 1 did. Now no flickering, the chart is recreated and the user is none the wiser.
I'm pretty new to JavaScript and HTML5. I'm trying to print a normal line chart onto canvas using Chart.js. I followed the step by step guide on their website, but am unable to make the graph show.
This is the current code:
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>CHARTS</title>
<script src="../../../Downloads/Chart.js-master/Chart.js"></script>
</head>
<body>
<canvas id="myCanvas" width="800" height="500" style="border:dashed #FF0000">Aw Snap!</canvas>
<script>
context = document.getElementById('myCanvas').getContext('2d');
var data = {
labels : ["January","February","March","April","May","June","July"],
datasets : [
{
fillColor : "rgba(220,220,220,0.5)",
strokeColor : "rgba(220,220,220,1)",
pointColor : "rgba(220,220,220,1)",
pointStrokeColor : "#fff",
data : [65,59,90,81,56,55,40]
},
{
fillColor : "rgba(151,187,205,0.5)",
strokeColor : "rgba(151,187,205,1)",
pointColor : "rgba(151,187,205,1)",
pointStrokeColor : "#fff",
data : [28,48,40,19,96,27,100]
}
]
}
Line.defaults = {
//Boolean - If we show the scale above the chart data
scaleOverlay : false,
//Boolean - If we want to override with a hard coded scale
scaleOverride : false,
//** Required if scaleOverride is true **
//Number - The number of steps in a hard coded scale
scaleSteps : null,
//Number - The value jump in the hard coded scale
scaleStepWidth : null,
//Number - The scale starting value
scaleStartValue : null,
//String - Colour of the scale line
scaleLineColor : "rgba(0,0,0,.1)",
//Number - Pixel width of the scale line
scaleLineWidth : 1,
//Boolean - Whether to show labels on the scale
scaleShowLabels : true,
//Interpolated JS string - can access value
scaleLabel : "<%=value%>",
//String - Scale label font declaration for the scale label
scaleFontFamily : "'Arial'",
//Number - Scale label font size in pixels
scaleFontSize : 12,
//String - Scale label font weight style
scaleFontStyle : "normal",
//String - Scale label font colour
scaleFontColor : "#666",
///Boolean - Whether grid lines are shown across the chart
scaleShowGridLines : true,
//String - Colour of the grid lines
scaleGridLineColor : "rgba(0,0,0,.05)",
//Number - Width of the grid lines
scaleGridLineWidth : 1,
//Boolean - Whether the line is curved between points
bezierCurve : true,
//Boolean - Whether to show a dot for each point
pointDot : true,
//Number - Radius of each point dot in pixels
pointDotRadius : 3,
//Number - Pixel width of point dot stroke
pointDotStrokeWidth : 1,
//Boolean - Whether to show a stroke for datasets
datasetStroke : true,
//Number - Pixel width of dataset stroke
datasetStrokeWidth : 2,
//Boolean - Whether to fill the dataset with a colour
datasetFill : true,
//Boolean - Whether to animate the chart
animation : true,
//Number - Number of animation steps
animationSteps : 60,
//String - Animation easing effect
animationEasing : "easeOutQuart",
//Function - Fires when the animation is complete
onAnimationComplete : null
}
new Chart(context).Line(data,options);
</script>
</body>
What am I doing wrong that is causing my chart to not show?
Data variable is not yet initialized when you are calling "new Chart". Move the "new Chart" to end of JS block.
A tip - to check for errors use JS console.
Edit: The were two additional JavaScript errors - options variable was not intialized and Line was undefined variable. Please check my reply below for demo link.
You didn't declared the options variable either pass an empty array for options.
new Chart(context).Line(data,{});
Or declare the variable
var options = { ... }
new Chart(context).Line(data, options);
I think I have a solution to 'options' problem.
If you remove options from:
new Chart(context).Line(data,options);
so it looks like that:
new Chart(context).Line(data);
does it work?
It is because
Line.defaults = { ... }
is just a list of options you may change - you are not supposed to put the whole thing to your html file.
In other words instead of for example:
Line.defaults = { scaleOverlay : true, scaleOverride : true }
try:
var options = { scaleOverlay : true, scaleOverride : true }
The tutorial on the homepage of chartjs is confusing in this regard a little bit because it tells you to use an array of settings that are default in the main file. But you are supposed to just take the "insides" and use them, not the whole thing and it does not say to actually create options variable for it.
It took me an hour to figure out but only because I have made a mistake of not checking up JS Console immediatelly, as #Lauris hinted out in his answer :)
Also make sure that this:
<script src="../../../Downloads/Chart.js-master/Chart.js"></script>
points to a correct file. It looks like you just did that to hide the real path from StackOverflow community. In that case nevermind.
I hope this helps!
I want to draw some data using jqplot and I have a small issue.
The code I use is this (code on fiddle):
$.jqplot('chart1', [[202],[249],[148]], {
seriesColors : ['#ff0000', '#0f0', '#00f'],
seriesDefaults : {
renderer :$.jqplot.BarRenderer,
pointLabels : {
show : true
},
tickRenderer : $.jqplot.CanvasAxisTickRenderer,
rendererOptions : {
barDirection : 'horizontal'
}
},
axes: {
yaxis: {
renderer: $.jqplot.CategoryAxisRenderer,
ticks: ["some value", "other series", "third series"],
},
},
});
The graph has 3 horizontal regions, "some value", "other series" and "third series"
I need that each graph bar to be under corresponding region, and to keep the colors as now (red to "some value", green to "other series" and blue to "third series").
How do I need to format the data to get this?
As extra questions:
I want few pixels margin between yaxis and corresponding axe labels. How do I set this?
The graph has a bg color (fade yellow). How do I eliminate that color and to get as bg whatever color the container has?
You need to change your data to
data = [[[202,1],[248,2],[148,3]]];
See working example here.
PS1 : You can change width of the bar by setting barWidth = xx; where xx is in pixels (50px in given example).
PS2 : For your first extra question, you can add something like this :
$("#chart1 .jqplot-grid-canvas").offset({left:$("#chart1 .jqplot-grid-canvas").offset().left+5});
$("#chart1 .jqplot-series-shadowCanvas").offset({left:$("#chart1 .jqplot-series-shadowCanvas").offset().left+5});
$("#chart1 .jqplot-series-canvas").offset({left:$("#chart1 .jqplot-series-canvas").offset().left+5});
$("#chart1 .jqplot-point-label").offset({left:$("#chart1 .jqplot-point-label").offset().left+5});
$("#chart1 .jqplot-highlight-canvas").offset({left:$("#chart1 .jqplot-highlight-canvas").offset().left+5});
$("#chart1 .jqplot-highlighter-tooltip").offset({left:$("#chart1 .jqplot-highlighter-tooltip").offset().left+5});
$("#chart1 .jqplot-barRenderer-highlight-canvas").offset({left:$("#chart1 .jqplot-barRenderer-highlight-canvas").offset().left+5});
$("#chart1 .jqplot-event-canvas").offset({left:$("#chart1 .jqplot-event-canvas").offset().left+5});
I'm pretty sure you can make it a cleaner way but it works (change the +5 values to whatever you need in order to move the chart block). Please see an updated working example here