how to display labels at top of charts(chart.js) - javascript

in the below code the labels are appiles (that i can see the label name on hovering over the colors) but not displayed in the top of the chart (this.color->this.value)like,need labels at the top of chart as like below image. help to get those labels.
var p=[22,33,44,55,66];
firebase.firestore().collection("product_info").onSnapshot(
async function(querySnapshot){
querySnapshot.forEach(async function(doc){
var temp=await doc.data().name;
it.push(await temp);
console.log(it);
});
});
console.log(it);
Chart.defaults.global.defaultFontFamily = '-apple-system,system-ui,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,sans-serif';
Chart.defaults.global.defaultFontColor = '#292b2c';
var ctx = document.getElementById("myPieChart");
var myPieChart = new Chart(ctx, {
type: 'pie',
data: {
labels: it,
datasets: [{
data: p,
backgroundColor: ['#007bff', '#dc3545', '#ffc107', '#28a745'],
}],
}
,
});

Add a legend to your config:
{
type: 'pie',
data: {
...
},
options: {
legend: {
position: 'top'
}
}
...
}
Example:
var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
type: 'pie',
data: {
labels: [ "My", "Dataset", "Labels" ],
datasets: [{
data: [ 22, 33, 44 ],
backgroundColor: [ '#007bff', '#dc3545', '#9932CC' ]
}]
},
options: {
legend: {
position: 'top'
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.js"></script>
<div class="container">
<div>
<canvas id="myChart"></canvas>
</div>
</div>

Related

how can i get percentage of each pie slice in Chart.js

I wanted to get percentage of each slice of pie . I am using chart.js for visualizing feedback results. Below is the code i am using
<script>
var xValues = ["very satisfied", "satisfied", "neutral", "dissatisifed", "very dissatified"];
var yValues = {{ faculty_feedback_data }};
var barColors = [
"#b91d47",
"#00aba9",
"#2b5797",
"#e8c3b9",
"#1e7145"
];
faculty_questionnaire = [questions are inserted here ]
faculty_chart_ids = ["faculty-chart1", "faculty-chart2", "faculty-chart3", "faculty-chart4", "faculty-chart5", "faculty-chart6", "faculty-chart7", "faculty-chart8", "faculty-chart9", "faculty-chart10", "faculty-chart11", "faculty-chart12", "faculty-chart13"]
for (let i = 0; i < faculty_chart_ids.length; i++) {
new Chart(faculty_chart_ids[i], {
type: "pie",
data: {
labels: xValues,
datasets: [{
backgroundColor: barColors,
data: yValues[i]
}]
},
options: {
title: {
display: true,
text: faculty_questionnaire[i]
},
},
});
}
</script>

Chart js 2 bars with one customize label on top

I have few values like A and B now I have pair of them I am showing them on chart-js like this
Now for my use case, I am calculating the third value using A and B. E.g a=100 and b=50, and dividing them will give me c=2.0. Now I want to show this c value on top of A and B bar as a common label like this
"chart.js": "^3.3.0",
react-js
const newChartInstance = new Chart(chartContainer.current, {
type: "bar",
options: {
scales: {
yAxes: [
{
ticks: {
beginAtZero: true,
},
},
],
},
...config.options,
onClick: (e) => {
const points = newChartInstance.getElementsAtEventForMode(
e,
"nearest",
{ intersect: true },
true
);
if (points.length) {
const firstPoint = points[0];
var type =
newChartInstance.data.datasets[firstPoint.datasetIndex].label;
var label = newChartInstance.data.labels[firstPoint.index];
var value =
newChartInstance.data.datasets[firstPoint.datasetIndex].data[
firstPoint.index
];
// This is the result that you will use to breakdown the chart
//console.log(label, value, type);
dispatch(setClickedBar({ label, value, type, tile: props.tile }));
}
},
},
data: data,
});
You can use a custom plugin for that:
var options = {
type: 'bar',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
backgroundColor: 'red'
},
{
label: '# of Points',
data: [7, 11, 5, 8, 3, 7],
backgroundColor: 'blue'
}
]
},
options: {
plugins: {
customValue: {
name: 'ROI',
}
}
},
plugins: [{
id: 'customValue',
afterDraw: (chart, args, opts) => {
const {
ctx,
data: {
datasets
},
_metasets
} = chart;
datasets[0].data.forEach((dp, i) => {
let barValue = `${(datasets[1].data[i] + dp) / 2}%`;
const lineHeight = ctx.measureText('M').width;
const textVal = opts.name || 'fill'
ctx.textAlign = 'center';
ctx.fillText(barValue, _metasets[0].data[i].x, (_metasets[0].data[i].y - lineHeight * 1.5), _metasets[0].data[i].width);
ctx.fillText(textVal, _metasets[0].data[i].x, (_metasets[0].data[i].y - lineHeight * 3), _metasets[0].data[i].width);
});
}
}]
}
var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.4.1/chart.js"></script>
</body>

Group data from CSV (D3.js & Chart.js)

I have a csv file like that:
id,Annee,Origine,Pax_Total
1,2014,AJACCIO,27494
2,2019,AJACCIO,57525
3,2014,ANGERS,1724
4,2019,ANGERS,4725
...
And I want to group per Origine and have the sum of Pax_Total.
The aim is to create a bar chart with Chart.js.
There is my code:
d3.csv("https://raw.githubusercontent.com/gflowiz/mapathon/master/DGAC_flux.csv")
.then(makeChart);
function makeChart(ville) {
var sumPaxTotal = d3.rollups(ville, v => d3.sum(v, d => d.Pax_Total), d => d.Origine)
var villeOrigine = d3.groups(ville, d => d.Origine)
var ctx = document.getElementById('chart').getContext('2d');
var chart = new Chart(ctx, {
type: 'horizontalBar',
option:{
maintainAspectRatio: true,
legend: {
display: false
}
},
data: {
labels: villeOrigine,
datasets: [
{
data: sumPaxTotal,
backgroundColor: '#F15F36'
}
]
}
});
console.log(sumPaxTotal)
}
Here is the console log for sumPaxTotal.
I think there is an "array" problem and after lot of research, it's not clear for me...
Thanks for your help.
Using Arrays.map(), this could be done as follows:
data: {
labels: sumPaxTotal.map(v => v[0]),
datasets: [{
label: 'DGAC-Flux',
data: sumPaxTotal.map(v => v[1]),
backgroundColor: '#F15F36'
}]
}
Please take a look at your amended code below:
d3.csv("https://raw.githubusercontent.com/gflowiz/mapathon/master/DGAC_flux.csv").then(makeChart);
function makeChart(ville) {
let sumPaxTotal = d3.rollups(ville, v => d3.sum(v, d => d.Pax_Total), d => d.Origine);
let chart = new Chart('chart', {
type: 'horizontalBar',
data: {
labels: sumPaxTotal.map(v => v[0]),
datasets: [{
label: 'DGAC-Flux',
data: sumPaxTotal.map(v => v[1]),
backgroundColor: '#F15F36'
}]
},
options: {
legend: {
display: false
}
}
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/6.2.0/d3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"></script>
<canvas id="chart" height="250"></canvas>

How to put dynamic colors for pie chart - chart js

I have a pie chart like this:
this.canvas = document.getElementById('chart');
this.ctx = this.canvas.getContext('2d');
const myChart = new Chart(this.ctx, {
type: 'pie',
data: {
labels: names,
datasets: [{
label: '# of dogs',
data: data,
backgroundColor: color???,
borderWidth: 1
}]
},
options: {
responsive: false,
display: true
}
});
data is not a fixed data. It is an array and can contain different data. How can I make that each piece of the pie chart has a different color?
Thanks!
this is my suggestion :
Step 1
colors=[];
Step 2
for(let i=0;i<this.data.length;i++){
this.colors.push('#'+Math.floor(Math.random()*16777215).toString(16));
}
Stap 3
data: data,
backgroundColor: this.colors
.....
Generate a random color
function getRandomColor() {
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++ ) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
this.canvas = document.getElementById('chart');
this.ctx = this.canvas.getContext('2d');
const myChart = new Chart(this.ctx, {
type: 'pie',
data: {
labels: names,
datasets: [{
label: '# of dogs',
data: data,
backgroundColor: getRandomColor(),
borderWidth: 1
}]
},
options: {
responsive: false,
display: true
}
});

chart.js ajax pushing another dataset always "undefined"

Following is my javascript Code, but the only thing really relevant is the last function. I want to update the Chart to add another dataset, without reloading the Page. But for reason the added dataset is always undefined. The commented-out line, which uses the exact same array of data, on the other hand works. Since I'm new to javascript I'm not sure, if I missed something obvious, or if chart.js just doesn't support this kind of thing at all.
const CHART = document.getElementById("lineChart");
var dts1 = [
{
label: "Abfall gesamt",
data: Abfall_gesamt,
}
];
var dts2 = [
{
label: "Abfall schadstoffhaltiger",
data: Abfall_schadstoff,
}
];
var lineChart = new Chart(CHART, {
type: 'line',
data: {
labels: Jahr,
datasets: dts1
}
});
function myFunction(){
//lineChart.data.datasets[0].data = Abfall_schadstoff;
lineChart.data.datasets.push(dts2);
lineChart.update();
}
The issue is, you are defining your datasets (dts1 and dts2) as an array. They should be an object, like so ...
var dts1 = {
label: "Abfall gesamt",
data: Abfall_gesamt,
};
var dts2 = {
label: "Abfall schadstoffhaltiger",
data: Abfall_schadstoff,
};
and then, when generating the chart, set datasets value as ...
datasets: [dts1]
ᴅᴇᴍᴏ
const CHART = document.getElementById("lineChart");
var Abfall_gesamt = [1, 2, 3];
var Abfall_schadstoff = [4, 5, 6]
var dts1 = {
label: "Abfall gesamt",
data: Abfall_gesamt,
backgroundColor: 'rgba(255, 0, 0, 0.2)'
};
var dts2 = {
label: "Abfall schadstoffhaltiger",
data: Abfall_schadstoff,
backgroundColor: 'rgba(0, 0, 255, 0.2)'
};
var lineChart = new Chart(CHART, {
type: 'line',
data: {
labels: ['Jahr', 'Mahr', 'Kadr'],
datasets: [dts1]
},
options: {
responsive: false,
scales: {
yAxes: [{
ticks: {
beginAtZero: true,
stepSize: 1
}
}]
}
}
});
function myFunction() {
//lineChart.data.datasets[0].data = Abfall_schadstoff;
lineChart.data.datasets.push(dts2);
lineChart.update();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
<button id="add" onclick="myFunction()">Add Dataset</button>
<canvas id="lineChart" height="190"></canvas>

Categories

Resources