how to add legend in pie chart - javascript

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

Related

Chart.js Chart Formatting - Legend & Y Axis & Title

SOLVED
Solution: Changed the spelling of axis to axes
I have just begun working with Chart.js as an alternative to the Python Plot.ly library.
So far I have been able to get the chart formatted the way I would like but there are still a couple of nuances I cant get right.
The first of which is that I cannot get any solution for adding a $ before Y-Axis values.
Here is my chart followed by the chart's code:
<script>
var ctx = document.getElementById("myChart").getContext('2d');
var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
var O1 = [1000,2000,3000,4000,5000,6000,7000,8000,9000,10000,11000,12000];
var O2 = [3000,6000,5000,3000,8000,6000,4000,7000,8000,0000,3000,1000];
var mychart = new Chart(ctx, {
type: 'line',
options: {
title:{
text: 'Test Chart',
display: true,
fontStyle: 'bold',
fontSize: 16,
},
legend:{
position: 'right',
},
scales:{
yAxis:[{
scaleLabel:{
display: true,
labelString: 'Tester',
},
ticks:{
callback: function(value, index, values) {
if(parseInt(value) >= 1000){
return '$' + value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
} else {
return '$' + value;
}
}
}
}]
},
tooltips:{
callbacks: {
label: function(tooltipItem, data){
var dataLabel = data.labels[tooltipItem.index];
var value = ': $ ' + data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index].toLocaleString();
if (Chart.helpers.isArray(dataLabel)) {
dataLabel = dataLabel.slice();
dataLabel[0] += value;
} else {
dataLabel += value;
}
return dataLabel1;
}
}
}
},
data: {
labels: months,
datasets: [
{
label: 'Officer1',
data: O1,
fill: false,
backgroundColor: 'rgba(255, 99, 132)',
borderColor: 'rgba(255, 99, 132)',
},
{
label: 'Officer2',
data: O2,
fill: false,
backgroundColor: 'rgba(0,0,255)',
borderColor: 'rgba(0,0,255)',
}
]
}
});
</script>
As you may be able to see I would simply like to add a $ before my Y-Axis data values. The last solution I tried also broke the data up by 1000s.
Additional:
The next few issues I've come across are very minor, which is why I chose to include them here.
First I would like a way to center my title over the chart itself, rather than centered over the whole chart+legend item.
Second is I would like to add some space to the left of my legend, as to separate it more from the chart.
Lastly, my Y-Axis title will not display. I would like it to display here while im testing in case I need it in the future.
This issue was solved by changing the spelling of axis to axes...subtle
Change the spelling of axis to axes

ECharts: change line color

This is my EChart init code:
var option = {
tooltip : {
trigger: 'axis'
},
calculable : true,
xAxis : [
{
type : 'category',
boundaryGap : false,
data : cat
}
],
yAxis : [
{
type : 'value'
}
],
series : [
{
name:'Series 1',
type:'line',
smooth:true,
itemStyle: {normal: {areaStyle: {type: 'default'}}},
data:val
}
]
};
The line appears with area (correct) and colored in red (I think by default, I haven't added anything to my code). How can I change the color of the chart's line?
I've tried with
itemStyle: {normal: {areaStyle: {type: 'default'}}, color: '#d5ceeb'},
but it doesn't work.
You are writing color inside itemStyle which changes color of your data points, not the line.
It should be written in lineStyle for the line color to change.
series : [
{
name:'Series 1',
type:'line',
smooth:true,
itemStyle: {normal: {areaStyle: {type: 'default'}}},
data:val
lineStyle: {color: '#d5ceeb'}
}
]
For more options on lineStyle refere here
As you can see on image below, if you don't neet to define details of line or item (in case scatter chart type) color can be specified on the same level as data, type ... etc

Saving pie chart as an image using database data

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>

Cannot get react-chartjs to update

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.

Highchart - Use a formatter on PlotLine labels

I'm using highchart to show some text next to a plot line on the xAxis. I would like to customize each label from a formatter function as it is possible on every other labels in the chart.
I've seen another topic on this matter but they're using TypeScript and I don't.
What I'm doing is :
vay chart = new HighChart({
...
xAxis: {
plotLines: [{
id: "plotLines",
zIndex: 15,
color: myColor,
width: 1,
value: theXvalue, //x value where to show the line
label: {
formatter: function () {
return " VAL > "+this.value;
}
},
}]
},
...
});
If I set the 'text' value in the label it shows up and it works like a charm.
Any help to use a formatter for those labels ?
Unfortunately you cannot use formatter, you should define content of label in text object, which can be wrapped in html elements, but then you need to set [useHTML(http://api.highcharts.com/highcharts#xAxis.plotLines.label.useHTML) parameter
Set the useHTML value to true and set your html content inside text. Here is an example of how to achieve it http://jsfiddle.net/9mvwpqf3/1/
yAxis: {
plotLines: [{
color: 'red',
width: 2,
value: 100,
label: {
useHTML: true,
text: '<button>Click Me</button>',
},
}]
},

Categories

Resources