Require some help when trying to save chart as an image. Sorry just started this new chart.js.
Issue:
How do I add my database data inside the chart? I keep try to add in $user but it keep giving me undefined user.
Here is the data that I want to add in from my database,
$users = DB::table('personal_infos')
->join('evaluations','evaluations.user_id', '=', 'personal_infos.id')
->select('evaluations.recommendation','evaluations.created_at' )
->where('evaluations.recommendation', '=', 'Yes')
->get();
For now I just used something like this to generate the pie chart:
<script type="text/javascript">
$("#save-btn").click(function() {
$("#canvas").get(0).toBlob(function(blob) {
saveAs(blob, "chart_1.png");
});
});
var 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"
}
];
var ctx = $("#canvas").get(0).getContext("2d");
var mychart = new Chart(ctx).Pie(data,
{
//Boolean - Whether we should show a stroke on each segment
segmentShowStroke : false,
//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 : 0, // This is 0 for Pie charts
//Number - Amount of animation steps
animationSteps : 10,
//String - Animation easing effect
animationEasing : "linear",
//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=\"<%=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>"
}
);
</script>
Related
Hello there stack overflow programmers, i have a question related to getting data from my database using ajax and display it in piechart from chartjs library. Now i am trying to make dynamic data to be accepted by format within piechart format.
Here is my ajax and its response: ( still it doesn't show my piegraph. i dont know why)
function getpieclinic() {
$.ajax({
type: "POST",
url: siteurl+"patients_report/piedataclinic",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess_,
error: OnErrorCall_
});
function OnSuccess_(response) {
// alert("hi");
var aData = response.d;
var arr = [];
$.each(aData, function (inx, val) {
var obj = {};
obj.color = val.color;
obj.value = val.value;
obj.label = val.label;
arr.push(obj);
});
var ctx = $("#myChart").get(0).getContext("2d");
var myPieChart = new Chart(ctx).Pie(arr);
}
function OnErrorCall_(response) {}
}
the response of my ajax is these:
[{"clinic_name":"Clinic 1","total_checked_up":"4"},{"clinic_name":"Clinic 2","total_checked_up":"0"},{"clinic_name":"Clinic 3","total_checked_up":"0"},{"clinic_name":"Clinic 4","total_checked_up":"0"}]
now, i want to make a dynamic format of piechart chartjs data format to be able to display it. this is the default format from the example:
var pieChartCanvas = $("#pieChart").get(0).getContext("2d");
var pieChart = new Chart(pieChartCanvas);
var PieData = [
{
value: 700,
color: "#f56954",
highlight: "#f56954",
label: "Chrome"
},
{
value: 500,
color: "#00a65a",
highlight: "#00a65a",
label: "IE"
},
{
value: 400,
color: "#f39c12",
highlight: "#f39c12",
label: "FireFox"
},
{
value: 600,
color: "#00c0ef",
highlight: "#00c0ef",
label: "Safari"
},
{
value: 300,
color: "#3c8dbc",
highlight: "#3c8dbc",
label: "Opera"
},
{
value: 100,
color: "#d2d6de",
highlight: "#d2d6de",
label: "Navigator"
}
];
var pieOptions = {
//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,
//Boolean - whether to make the chart responsive to window resizing
responsive: true,
// Boolean - whether to maintain the starting aspect ratio or not when responsive, if set to false, will take up entire container
maintainAspectRatio: true,
//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>"
};
//Create pie or douhnut chart
// You can switch between pie and douhnut using the method below.
pieChart.Doughnut(PieData, pieOptions);
You could accomplish this in the following way ...
// for demonstration purposes only
// use response.d in real case scenario
var response = [{ "clinic_name": "Clinic 1", "total_checked_up": "10" }, { "clinic_name": "Clinic 2", "total_checked_up": "20" }, { "clinic_name": "Clinic 3", "total_checked_up": "30" }, { "clinic_name": "Clinic 4", "total_checked_up": "40" }]; // response from ajax request
OnSuccess_(response);
function OnSuccess_(response) {
var pieChartCanvas = $("#pieChart").get(0).getContext("2d");
var pieChart = new Chart(pieChartCanvas);
var PieData = [];
// create PieData dynamically
response.forEach(function(e) {
var random_color = '#' + Math.floor(Math.random() * 16777215).toString(16);
PieData.push({
value: e.total_checked_up,
color: random_color,
highlight: random_color,
label: e.clinic_name
});
});
var pieOptions = {
//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: 0, // 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,
//Boolean - whether to make the chart responsive to window resizing
responsive: true,
// Boolean - whether to maintain the starting aspect ratio or not when responsive, if set to false, will take up entire container
maintainAspectRatio: true,
//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>"
};
//Create pie or douhnut chart
// You can switch between pie and douhnut using the method below.
pieChart.Doughnut(PieData, pieOptions);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.2/Chart.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="pieChart"></canvas>
I use Zingchart to plot some log Data therefore I need to display every single point in the graph. I activated the points attribute in the json(see
$scope.graphoptions = {
theme:"dark",
"gui":{
behaviors:[]
},
globals: {
shadow: false,
fontFamily: "Helvetica"
},
type: "line",
plot: {
aspect: "segmented",
marker: {}
},
"legend":{
margin :"5% 88%",
layout: "float",
fontSize : "10px",
backgroundColor: "#888888",
borderColor : "#000000",
shadowColor : "transparent",
toggleAction: "hide",
item: {
markerStyle : "circle",
fontColor: "#ffffff"
},
},
scaleX: {
zooming: true,
item: {
fontColor: "white"
},
guide: {
visible: false
},
"transform": {
"type": "date",
"all": "%G:%i",
}
},
"scaleY": {
zooming:true,
lineColor : "#DDD",
tick : {
lineColor : "#DDD"
},
item : {
fontColor : "#DDD"
},
refLine : {
lineColor : "#DDD"
},
},
tooltip : {
//we have to store the tooltip fkt globally so its ouside angulars
//scope thatswhy we have to pass the data to the function
jsRule : "applyTooltip("+$scope.fileName+")",
shadow:false
},
plotarea: {
"adjust-layout":true,
backgroundColor : '#272822'
},
}
for full json).
As you can see in this screenshot
Some points of the read Graph are drawn but none of the blue one.
When I zoom in:
Some markers of the Blue graph are displayed.
Is this a bug or do I have to activate an other attribute in the json I am not aware of.
Thanks in advance!
Assuming that your data is supposed to plot on those points, then you would need to increase the number of default markers drawn on the plot. By default, ZingChart calculates this number based upon the number of points, and the width of a chart.
maxNodes: N where N is the maximum amount of nodes you want displayed at a given point. e.g. maxNodes: 1000
If tooltips are important at a fine resolution, you would need to also change maxTrackers: N, where N is the amount of nodes to track for a tooltip. Do note that this will decrease performance heavily depending on the number of nodes to track. e.g. maxTrackers: 1000
Angular JS chart is awesome, But i need to implement click event in the piechart which i have created.. Here is the coding..
This is the JavaScript Coding...
$scope.pied = [{
value: 4,
color: "#FF5A5E",
highlight: "#FF5A5E",
label: "Prospective"
}, {
value: 0,
color: "#46BFBD",
highlight: "#46BFBD",
label: "Pending"
}, {
value: 0,
color: "#FDB45C",
highlight: "#FDB45C",
label: "CallBacks"
}, {
value: 4,
color: "#e6e6fa",
highlight: "#e6e6fa",
label: "FollowUp"
}, {
value: 1,
color: "#cc5229",
highlight: "#cc5229",
label: "Not Interested"
}, {
value: 0,
color: "#556b2f",
highlight: "#556b2f",
label: "Close"
}]
var pieOptions = {
//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,
//Boolean - Whether we should animate the chart
animation: true,
//Number - Amount of animation steps
animationSteps: 100,
//String - Animation easing effect
animationEasing: "easeOutBounce",
//Boolean - Whether we animate the rotation of the Pie
animateRotate: true,
//Boolean - Whether we animate scaling the Pie from the centre
animateScale: false,
//Function - Will fire on animation completion.
onAnimationComplete: null
}
var ctx = document.getElementById("pieChart").getContext("2d");
var myPieChart = new Chart(ctx).Pie($scope.pied, pieOptions);
ctx.onclick = function(evt){
var activePoints = myPieChart.getPointsAtEvent(evt);
console.log("active: "+activePoints);
// => activePoints is an array of points on the canvas that are at the same position as the click event.
};
document.getElementById('js-legend').innerHTML = myPieChart.generateLegend();
This is the HTML Coding..
<canvas id="pieChart" width="440" height="200" ></canvas>
<div id="js-legend" class="chart-legend"></div>
This is the image of the above program.. i have wrote coding that when i click on The FollowUP it must the datas related to it.. But the click event is not working..??
Please see to the above code and picture and guide me to get the exact output what i expect. Thanks in advance guys...
I have Used angular-chart.js instead this chart.js Angular JS Documentation is here . Angular Chart is little bit easy than chart.js..
Thanks for the support guys.. :)
I am trying to follow the "Example usage" code from react-chartjs github page
I am new to javascript and react and probably just being naive. How can I get the new chartData from "_onChange" to update my PolarAreaChart? I tried something more direct by calling element.getDocumentById("polarChart"), but that returns nothing and then I cannot call .update on it... the whole "insert redraw in the xml" and it will magically call update seems magical to me :(
PolarPlot.jsx
var React = require ('react');
var PolarAreaChart = require ('react-chartjs').PolarArea;
var FilterStore = require ('FilterStore')
var PolarPlot = React.createClass ({
componentWillMount: function () {
FilterStore.addChangeListener (this._onChange);
},
_onChange: function () {
console.log("time to update")
chartData = [
{
value: 300,
color:"#F7464A",
highlight: "#FF5A5E",
label: "Red"
}]
},
render: function () {
return (
<PolarAreaChart id="polarChart" data={chartData} options={chartOptions} redraw/>
);
}
});
var chartData = [
{
value: 300,
color:"#F7464A",
highlight: "#FF5A5E",
label: "Red"
},
{
value: 50,
color: "#46BFBD",
highlight: "#5AD3D1",
label: "Green"
},
{
value: 100,
color: "#FDB45C",
highlight: "#FFC870",
label: "Yellow"
},
{
value: 40,
color: "#949FB1",
highlight: "#A8B3C5",
label: "Grey"
},
{
value: 120,
color: "#4D5360",
highlight: "#616774",
label: "Dark Grey"
}
];
var chartOptions = [
{
//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>"
}
];
module.exports = PolarPlot;
Your PolarPlot component is not rendered unless you explicitly change the state. Your chartData is not part of the component state. So assigning a new array to that variable does nothing more than that. Move this chartData to the component state. Then, whenever you update this state variable you are going to force the re-render. Something like this:
var PolarPlot = React.createClass ({
componentWillMount: function () {
FilterStore.addChangeListener (this._onChange);
},
getInitialState: function() {
return {chartData: chartData};
},
_onChange: function () {
console.log("time to update")
this.setState({
chartData: [{
value: 300,
color:"#F7464A",
highlight: "#FF5A5E",
label: "Red"
}]
});
},
render: function () {
return (
<PolarAreaChart id="polarChart" data={this.state.chartData} options={chartOptions} redraw/>
);
}
});
If you want to know more about how components rendering reacts to state changes check Reactive state section from the React Tutorial.
I use php codeigniter and I create pie chart using javascript. and database data pass using json encode. My problem is how I use legend. for pie chart and title.
javascript
var pieData = [
{
value: sales_data[i].ans,
color:"#FF0000"
},
{
value : sales_data[i].noans,
color : "#006400"
},
{
value : sales_data[i].reans,
color : "#191970"
}
,
{
value : sales_data[i].noreans,
color : "#FFEA88"
}
];
// get pie chart canvas
var countries=document.getElementById("countries").getContext("2d");
// draw pie chart
new Chart(countries).Pie(pieData, pieOptions);
}
}
});
Give this a shot -
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>"
Include this as part of your pieOptions.
Refer this documentation of chart.js for more details on how to use chart.js. For legends there dosent seem to be a simple way but you have an option to give label to each segment in your piechart which will act as your legend.
var myPieChart = new Chart(ctx[0]).Pie(data,options);
var data = [
{
value: 300,
color:"#F7464A",
highlight: "#FF5A5E",
label: "Red",
labelColor : 'white',
},
{
value: 50,
color: "#46BFBD",
highlight: "#5AD3D1",
label: "Green",
labelColor : 'white',
},
{
value: 100,
color: "#FDB45C",
highlight: "#FFC870",
label: "Yellow",
labelColor : 'white',
}
]
In this the label acts as your map legend and it looks like the example fiddle piechart using chart.js