Add Legend to Donut Chart - jqPlot - javascript

OK, this should be relatively simple :
I'm adding a donut chart, which does work
However, the 'legend' (like Head (+) along with the corresponding colour) does NOT show up.
Code :
$(document).ready(function(){
var s1 = [['Head (+)',<?php echo $headScore; ?>], ['Head (-)',<?php echo 6-$headScore; ?>]];
var s2 = [['Body (+)',<?php echo $totalScore-$headScore; ?>], ['Body (-)',<?php echo 7-$totalScore+$headScore; ?>]];
var plot3 = $.jqplot('linkchart', [s1,s2], {
title:"Score Profile",
seriesDefaults: {
// make this a donut chart.
renderer:$.jqplot.DonutRenderer,
rendererOptions:{
// Donut's can be cut into slices like pies.
sliceMargin: 3,
// Pies and donuts can start at any arbitrary angle.
startAngle: -90,
showDataLabels: false
},
legend: { show:true, location: 'e' }
}
});
});
What am I doing wrong?

Kameleon,
It looks like you have done a silly mistake. : )
First end the seriesDefaults property and then define the legend.
You have placed the legend inside the seriesDefaults.
var plot3 = $.jqplot('linkchart', [s1,s2], {
title:"Score Profile",
seriesDefaults: {
// make this a donut chart.
renderer:$.jqplot.DonutRenderer,
rendererOptions:{
// Donut's can be cut into slices like pies.
sliceMargin: 3,
// Pies and donuts can start at any arbitrary angle.
startAngle: -90,
showDataLabels: false
} // Not here...
},
//Place the legend here....
legend: { show:true, location: 'e' }
});
});
I have not tested it. But I think it should work.
Thank you.

Related

Morris Graph, round y-axis numbers

I made a Morris.js graph: http://thuis.xitro.nl/
I do not want to set a value in ymin, I have this on "auto".
I now have very long numbers because of that, example: 55.29999999999999
I want that to show just 55.
It would be even better if my graph just showed: 20, 30, 40, 50, 60, 70.
How can I achieve this? I know some HTML/PHP/MySQL but I'm pretty new to JavaScript.
EDIT: Fixed it myself by using: yLabelFormat: function(y) {return y = Math.round(y);},
Any idea how I can get my chart like this: 20,30,40,50,60,70?
Morris.Line({
// ID of the element in which to draw the chart.
element: 'morris-line-chart-dcr',
// Chart data records -- each entry in this array corresponds to a point on
// the chart.
data: [<?php echo $chart_data_dcr; ?>],
// The name of the data record attribute that contains x-visitss.
xkey: 'time',
// A list of names of data record attributes that contain y-visitss.
ykeys: ['eff', 'avg', 'rep'],
// Labels for the ykeys -- will be displayed when you hover over the
// chart.
labels: ['Decred Effective','Decred Average','Decred Reported'],
lineColors: ['#337ab7','#ffa500','#5cb85c'],
pointFillColors: ['#337ab7','#ffa500','#5cb85c'],
pointStrokeColors: ['#337ab7','#ffa500','#5cb85c'],
pointSize: 3,
hideHover: true,
ymax: "auto",
ymin: "auto",
// Disables line smoothing
smooth: false,
resize: true
});
yLabelFormat: function(y) {return y = Math.round(y);},
Fixed it for me.
Now I only would like to know how I can make them look like: 20,30,40,50,60,70.
Use the following code inside Morris.line Graph
yLabelFormat: function(y) {
return y = Math.round(y);
}
this will format the Y axis labels.

jQPlot charts- Pie chart disappears on passing high values

When i run the code the chart disappears
$(document).ready(function(){
var d1=${views};
var d2=${comoneviews};
var d3=${comtwoviews};
var plot1 = $.jqplot('piechart', [[['Your Organisation',d1],['Competitor#1',d2],['Competitor#2',d3]]], {
gridPadding: {top:0, bottom:38, left:0, right:0},
seriesDefaults:{
renderer:$.jqplot.PieRenderer,
trendline:{ show:false },
rendererOptions: { padding: 7, showDataLabels: true , dataLabels: 'value'}
},
legend:{
show:true,
placement: 'outside',
rendererOptions: {
numberRows: 1
},
location:'s',
marginTop: '15px'
}
});
});
the input values i am getting for d1 is 20700000 , d2 is 2300000, and d3 is 3040000. So does the chart does not appear because of higher values?
Per your comment, you just need to refer to the d1,d2 and d3 array values correctly. As you've mentioned, you are getting them as arrays - so the problem must be with your access to the actual values.
Access them as d1[0] d2[0] d3[0] (assuming you have a one sized array like you wrote)
var d1=[20700000];
var d2=[2300000];
var d3=[3040000];
var plot1 = $.jqplot('piechart', [[['Your Organisation',d1[0]],
['Competitor#1',d2[0]],['Competitor#2',d3[0]]]], {
...rest of plot code...
here is a working example with d1-d3 modified to arrays.

Fill Chart js with $http.get() data

Trying to get some data off of a webservice and display it in a chart. I figured chart js would be a good means to do so. (actually using tc-angular-chartjs). The $http.get( ) call I am using to test is:
$http.get('http://myjson.com/1chr1').success(function(data2) {
data2.forEach(function(r) {
$scope.labels.push(r.name);
$scope.scores.push(r.score);
});
});
and here is the whole js file for just the doughnut chart:
'use strict';
angular
.module( 'app.doughnut', [] )
.controller( 'DoughnutCtrl', function ( $scope ) {
$scope.labels = [];
$scope.scores = [];
$scope.data = [
{
value: 700,
color:'#F7464A',
highlight: '#FF5A5E',
label: 'Red'
},
{
value: 50,
color: '#46BFBD',
highlight: '#5AD3D1',
label: 'Green'
},
{
value: 100,
color: '#FDB45C',
highlight: '#FFC870',
label: 'Yellow'
}
];
$scope.options = {
// Sets the chart to be responsive
responsive: true,
//Boolean - Whether we should show a stroke on each segment
segmentShowStroke : true,
//String - The colour of each segment stroke
segmentStrokeColor : '#fff',
//Number - The width of each segment stroke
segmentStrokeWidth : 2,
//Number - The percentage of the chart that we cut out of the middle
percentageInnerCutout : 50, // This is 0 for Pie charts
//Number - Amount of animation steps
animationSteps : 100,
//String - Animation easing effect
animationEasing : 'easeOutBounce',
//Boolean - Whether we animate the rotation of the Doughnut
animateRotate : true,
//Boolean - Whether we animate scaling the Doughnut from the centre
animateScale : false,
//String - A legend template
legendTemplate : '<ul class="tc-chart-js-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>'
};
});
The issue I am running into is that most of these examples use the same format to supply the chart with data (static data with the same labels like value/label/color/highlight).
For my needs the colors or highlight dont really matter but I need the data pulled from a wesbervice where the value I need for the chart is called name and the label for the chart is called score.
So I was thinking I could do the $http.get( ) call and put the labels and scores into 2 different arrays and then the data portion in the js would look something like:
$scope.data = {
labels : ["option 1","option 2","option 3"],
values : [ 10, 20, 30 ],
datasets: [ value : values, color : #F7484A, highlight : #FF5A5E, label : labels]
};
I saw something like this done for a Chart.js bar graph, but not for a doughnut graph, and I cannot seem to get it to work. Maybe it isnt possible?
Are there any other alternatives? I mean I cannot be the only person who needs to display dynamic data into a nice responsive chart, but all of the examples use static data.
EDIT ANSWER I took dubhov's advice. Also found out my webservice link was messed up so I wasnt getting any data :p. Here is the new js for future reference:
'use strict';
angular
.module('app.doughnut', [])
.controller('DoughnutCtrl', function($scope, $http) {
$http.get('https://api.myjson.com/bins/1chr1').success(function(data2) {
$scope.data = [];
data2.forEach(function(r) {
$scope.data.push({
'value': r.score,
'color': '#F7464A',
'highlight': '#FF5A5E',
'label': r.name
});
});
});
$scope.options = {
// Sets the chart to be responsive
responsive: true,
//Boolean - Whether we should show a stroke on each segment
segmentShowStroke: true,
//String - The colour of each segment stroke
segmentStrokeColor: '#fff',
//Number - The width of each segment stroke
segmentStrokeWidth: 2,
//Number - The percentage of the chart that we cut out of the middle
percentageInnerCutout: 50, // This is 0 for Pie charts
//Number - Amount of animation steps
animationSteps: 100,
//String - Animation easing effect
animationEasing: 'easeOutBounce',
//Boolean - Whether we animate the rotation of the Doughnut
animateRotate: true,
//Boolean - Whether we animate scaling the Doughnut from the centre
animateScale: false,
//String - A legend template
legendTemplate: '<ul class="tc-chart-js-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>'
};
});
Chart.js expects the data to be formatted like it is with the static examples. Can't you just add an object to the data array with the data you need? Like this:
$scope.data.push({'value':r.score,
'label':r.name,
'color':'#RANDOMCOLOR',
'highlight':'#SLIGHTLYSHADEDRANDOMCOLOR'});
As far as the colors, which may or may not be required by the API (I think they will be), you can either go random, or if you know that your dataset is limited, you can select from a static list of colors. Here's some ideas on randoms: https://stackoverflow.com/a/25709983/769971

Google charts X-axis don't look so good

I draw a chart using google charts API. and i get this chart:
My problem in this chart is the X-axis. The labels are not in look so good.
if I have more Strings in X-axis it's look like this:
I think the problem is because the X column type is string and not DATETIME.
How i change the column type in google charts?
Or How i change the X-axis without changin the column type?
I add the script here below...
PHP code:
$connection = mysql_connect('127.0.0.1','root','123456');
mysql_select_db('db_statmarket',$connection);
$result2 = mysql_query('select sum(`How much read from customer`) as Leads, Date from monitor group by Date;',$connection) or die('cannot show tables');
$json = array();
while($row = mysql_fetch_assoc($result2)) {
$json[] = $row;
}
$str='[\'Date\', \'Leads\'],';
foreach($json as $key=>$value){
$str = $str.'['.'\''.$value["Date"].'\''.', '.$value["Leads"].'],';
}
$str = substr($str, 0, -1);
$str = '['.$str.']';
$result1 = mysql_query('SELECT * FROM monitor ORDER BY customer_id DESC LIMIT 1;',$connection) or die('cannot show tables');
$row = mysql_fetch_assoc($result1);
JS code:
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable(<?php echo $str?>);
var options = {
title: '',
curveType: 'function',
legend: { position: 'bottom' },
width: 1000,
backgroundColor: '#efeff0',
is3D: true,
chartArea: {
backgroundColor: {
stroke: '#efeff1',
strokeWidth: 1}},
height: 300
};
var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
chart.draw(data, options);
HTML code:
<div id="curve_chart" class="plot" style="width: 50% ; height: 400px ; float:left; margin-left:9%;"></div>
Thanks!
I found The answer.
I share It for all. so if somebody stuck, like me. will continue with this help quickly.
I create new variable: var showEvery = parseInt(data.getNumberOfRows() / 4);
And in the option attribute i add: hAxis: {showTextEvery: showEvery}
so the JS code seems like this:
var data = google.visualization.arrayToDataTable(<?php echo $str?>);
var showEvery = parseInt(data.getNumberOfRows() / 4);
var options = {
title: 'Title',
curveType: 'function',
legend: { position: 'bottom' },
width: 1000,
backgroundColor: '#efeff0',
is3D: true,
chartArea: {
backgroundColor: {
stroke: '#efeff1',
strokeWidth: 1}},
hAxis: {showTextEvery: showEvery},
height: 300
};
var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
chart.draw(data, options);
You can force the x-axis of a BarChart setting the hAxis.viewWindow.min and hAxis.viewWindow.max:
hAxis: {
viewWindow: {
min: 0,
max: 100
},
ticks: [0, 50, 100] // display labels every 50
}
This will work for numbers or percentages, to use with dates is a bit more complex: checking Customizing Axes in Google API, there are two solutions:
You can change your major X axis to discrete and date type
The major axis of a chart can be either discrete or continuous. When using a discrete axis, the data points of each series are evenly spaced across the axis, according to their row index. When using a continuous axis, the data points are positioned according to their domain value.
Read, in the Customizing Axes link part which starts with Help! My chart has gone wonky! where explains the steps how to change from date to string and then customize it...

JQPlot define x-axes as days, y-axes as views - way to do this?

So this is code where I want to define x-axes with value of views, and y-axes as value of
day, or tick. I have small knowledge with jqplot or javascript, so could you please give me examples of how I could draw such chart using this. PHP variable $daynumber is usually 1 (for one day, one row) but I can give date aswell, which variant could be better?
<script language="javascript" type="text/javascript">
$(document).ready(function(){
var line1 = [<?php echo ''.$views.','; ?>];
var ticks = [<?php echo ''.$daynumber.','; ?>];
var plot1 = $.jqplot('chartdiv', [line1], {
legend: {show:false},
axes:{
// here I define y-axes.
xaxis:{
ticks: ticks,
tickOptions:{
angle: -30
},
tickRenderer:$.jqplot.CanvasAxisTickRenderer,
label:'Days',
labelOptions:{
fontFamily:'Helvetica',
fontSize: '11pt'
},
labelRenderer: $.jqplot.CanvasAxisLabelRenderer
},
// here I define y-axes
yaxis:{
renderer:$.jqplot.LogAxisRenderer,
tickOptions:{
labelPosition: 'middle',
angle:-30
},
tickRenderer:$.jqplot.CanvasAxisTickRenderer,
labelRenderer: $.jqplot.CanvasAxisLabelRenderer,
labelOptions:{
fontFamily:'Helvetica',
fontSize: '11pt'
},
label:'Views'
}
}
});
});
</script>
Take a look in Date axes page for jqPlot.
It says that your line should look in format
line1=[ [date,value], [anotherdate,otherValue] ];
And dont forget to include date plugin for jqplugin
<script type="text/javascript" src="../src/plugins/jqplot.dateAxisRenderer.min.js"></script>

Categories

Resources