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>
Related
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>
I'm trying to show weight_id retrieved from mysql data in a chart.js tooltip (shown as (weight_ids[index]) in the image). And later, I intend to show a modal instead of a tooltip to let users update or delete that data. I presume I cannot achieve that without linking the linechart's point data with id stored in mysql. How can I incorporate this id data?
I would appreciate any help very much.
enter image description here
My code is as follows:
<canvas id="myChart"></canvas>
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.9.4/dist/Chart.min.js"></script>
{{-- グラフを描画--}}
<script>
//ラベル
const labels = #json($date_labels);
// id
const weight_ids = #json($weight_ids);
//体重ログ
const weight_logs = #json($weight_logs);
const aryMax = function(a, b) {
return Math.max(a, b);
};
const aryMin = function(a, b) {
return Math.min(a, b);
};
let min_label = Math.floor((weight_logs).reduce(aryMin) - 0.5);
let max_label = Math.ceil((weight_logs).reduce(aryMax) + 0.5);
console.log(weight_ids);
console.log(weight_logs);
console.log(min_label, max_label);
//グラフを描画
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'line',
data : {
labels: labels, // x軸ラベル
datasets: [
{
label: `Weight (weight_ids[index])`,
data: weight_logs,
tension: 0,
borderColor: "rgba(37,78,255,1)",
backgroundColor: "rgba(0,0,0,0)",
pointRadius: 3
}
]
},
options: {
title: {
display: false,
text: ''
},
legend: {
display: false,
},
scales: {
yAxes: [
{
ticks: {
min: min_label, // ラベル最小値
max: max_label, // ラベル最大値
},
scaleLabel: {
display: true,
fontSize: 16,
labelString: '体重 (kg)'
}
}
],
},
hover: {
mode: 'point'
},
onClick: function clickHandler(evt) {
var firstPoint = myChart.getElementAtEvent(evt)[0];
if (firstPoint) {
var label = myChart.data.labels[firstPoint._index];
var value = myChart.data.datasets[firstPoint._datasetIndex].data[firstPoint._index];
console.log(label);
console.log(value);
if (value) {
$('#weidhtModal').modal('show');
}
}
}
}
});
</script>
Thank you!
I found a way to retrieve weight_id using the following function.
onClick: function clickHandler(evt, activeElements) {
if (activeElements.length) {
var element = this.getElementAtEvent(evt);
var index = element[0]._index;
var _datasetIndex = element[0]._datasetIndex;
var weightId = weight_ids[index];
var weightLog = weight_logs[index];
console.log(index);
console.log(weightId);
console.log(this.data.labels[index]);
console.log(weightLog);
}
}
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>
I am using Chart.js to draw a simple line chart. Everything looks fine, I get data from API but I can't able to show on the line chart :
$.ajax({
url: "https://api.thevirustracker.com/free-api?countryTimeline=PK",
dataType: 'json',
success: function(result) {
const datachart = []
console.log("datachart", datachart)
for (var i = 0, l = result.timelineitems.length; i < l; i++) {
const entries = result.timelineitems[i]
const x = Object.keys(entries);
const y = Object.values(entries)
// const y = [2,2,4,7,5,4,7,4,1,0,7,4,8,5,44,1,44,111,44,1,11,1,77,88,55,22,99,66,55,77,44,55,22,00,44,77,8,9,5,7,4,1]
datachart.push({
y: y,
x: x
})
}
var ctx = document.getElementById('myChart').getContext('2d');
var chart = new Chart(ctx, {
// The type of chart we want to create
type: 'line',
// The data for our dataset
data: {
datasets: [{
data: datachart,
label: ["datachart[1]"],
borderColor: "#18bc9c",
fill: false
}]
},
// Configuration options go here
options: {}
});
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<canvas id="myChart" width="200" height="200"></canvas>
I want to add an array of x variable as a label and data is to add Object.values(entries).new_daily_cases as a data to be shown
The data property of individual datasets for a line chart can be passed in two formats, number[] or Point[]. Point[] is useful in the following cases:
If the number of data points from individual datasets is different.
if x-values of data points from different datasets are different.
In your case, if you specify data.labels, there's no need to define the data of individual datasets as an array of Point.
Please have a look at your amended code below:
$.ajax({
url: "https://api.thevirustracker.com/free-api?countryTimeline=PK",
dataType: 'json',
success: result => {
const rawData = result.timelineitems[0];
delete rawData.stat;
const labels = Object.keys(rawData);
const data = Object.values(rawData);
var chart = new Chart(document.getElementById('myChart'), {
type: 'line',
data: {
labels: labels,
datasets: [{
label: 'New Daily Cases',
data: data.map(o => o.new_daily_cases),
borderColor: "violet",
fill: false
},
{
label: 'New Daily Deaths',
data: data.map(o => o.new_daily_deaths),
borderColor: "orange",
fill: false
},
{
label: 'Total Cases',
data: data.map(o => o.total_cases),
borderColor: "blue",
fill: false
},
{
label: 'Total recoveries',
data: data.map(o => o.total_recoveries),
borderColor: "green",
fill: false
},
{
label: 'Total Deaths',
data: data.map(o => o.total_deaths),
borderColor: "red",
fill: false
}]
},
options: {}
});
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.min.js"></script>
<canvas id="myChart" height="90"></canvas>
I want to crate a graph using chart.js and show it in my view. But after parsing the data to the view, it always come with undefined variable (in my case, bulan and pendapatan is undefined).
This is my controller to parse the data
$query = DB::table("transaksipenjualan")->select(DB::raw('EXTRACT(MONTH FROM tanggaltransaksi) AS Bulan, SUM(total) as Pendapatan'))
->where('tanggalTransaksi', 'LIKE', '%'.$request->tahun.'%')
->groupBy(DB::raw('EXTRACT(MONTH FROM tanggaltransaksi)'))
->get();
$count=count($query);
$label = [];
$data = [];
for($i=0;$i<$count;$i++)
{
$label[$i] = $query[$i]->Bulan;
$data[$i] = $query[$i]->Pendapatan;
}
return view('printPreview/pendapatanBulanan', ['data'=>$query, 'bulan'=>$label, 'pendapatan'=>$data]);
And this is my script to get the data
var ctx = document.getElementById("canvas").getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: bulan,
datasets: [{
label: 'Nilai Pendapatan',
data: pendapatan,
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
});
I don't know very well how to pass the data to a script, so I need some advice. Thanks!
Have you tried using {{ json_encode($php_variable) }}? For example:
var ctx = document.getElementById("canvas").getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: {{ json_encode($bulan) }},
datasets: [{
label: 'Nilai Pendapatan',
data: {{ json_encode($pendapatan) }},
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
});