Can't display api data to a chart (Chartjs) - javascript

The chart it is showing only the fell information and marking the data numbers in datasets in the donut. What I am looking for is that the chart shows the values ​​of found and fell (from the api). I have tried to delete those parameters and change it but it is not reflected. also above the chart there are many small rectangles with the values ​​of found and fell
async function getMeteor() {
const url = 'https://data.nasa.gov/resource/gh4g-9sfh.json'
const result = await fetch(url)
const barChartData = await result.json()
const falling = barChartData.map( (x) => x.fall)
return falling;
}
async function printChart() {
const fallData = await getMeteor();
const data = {
labels: fallData,
datasets: [{
label: 'Fell Meteors',
backgroundColor: 'rgb(255, 99, 132)',
borderColor: 'rgb(255, 99, 132)',
data: [0, 10, 5, 2, 20, 30, 45],
}]
};
const config = {
type: 'doughnut',
data: data,
options: {}
};
const myChart = new Chart(
document.getElementById('myChart'),
config
);
}
printChart();

Try changing document.getElementById('myChart') to
document.getElementById('myChart').getContext('2d');

Related

Set a limit / max number for legends

Lets say I have a Donut chart with 5 items in data like this
const data = {
labels: ['E-commerce', 'Enterprise', 'Green', 'Grey', 'Purple'],
datasets: [
{
label: '# of Votes',
data: [12, 19, 3, 5, 3],
backgroundColor: ['#C07CC3', '#9C3848', '#9DDBAD', '#ADA8B6', '#606EDA'],
borderWidth: 1,
},
],
}
I don't want it to show all the legends as I don't have space or whatever reason
How can I hide the Green and purple in this example?
I mean only from legends not from chart
I see two easy ways, how you could approach this problem:
(I personally I would use the second option below, it is more configurable, but it needs just abit of coding)
You can simply delete the labels you want to delete from the labels- array, and they won't show up in the legend.
But keep in mind you would have to change the order of the data and backgroundColor arrays, to match this change.
Here a short demo:
const data = {
labels: ['E-commerce', 'Enterprise', 'Grey'], // <-- just remove the unwanted labels
datasets: [{
data: [12, 19, 5, 3, 3], // <-- reorder
backgroundColor: ['#C07CC3', '#9C3848', '#ADA8B6', '#9DDBAD', '#606EDA'], // <-- reorder
borderWidth: 1,
}],
};
const config = {
type: 'doughnut',
data: data,
options: {
maintainAspectRatio: false,
plugins: {
legend: {
position: 'right',
labels: {
usePointStyle: true,
},
}
},
}
};
new Chart(
document.getElementById('chart'),
config
);
<script src="//cdn.jsdelivr.net/npm/chart.js"></script>
<div class="chart" style="height:184px; width:350px;">
<canvas id="chart" ></canvas>
</div>
Better and cleaner (but some coding is needed), you can filter out label-items, you don't want to display, with the function array filter. (details can be found in the documentation)
UPDATED Alternative Version Demo:
here only the Top 3 labels (limiting the amount of labels with the variable maxLabelsToShow) will be shown (sort order is descending, but changing this is would be easy)
function getLabelsOnlyTopX(num, data, labels){
let selectedLabels = []
//we don't want to alter the order
let helperData = [...data];
//sort in descending order
helperData.sort( (a,b) => b-a);
//get top X Values
helperData = helperData.slice(0, num);
//get index for the data
let indexes = data.map( (value, index) => ({value,index}) ).filter(item => helperData.some(n1 => n1 == item.value))
//slecet only labels with the correct index
selectedLabels = labels.filter((value, index) => indexes.some( n => n.index == index))
// just be sure that a maximum of num labels are sent
return selectedLabels.slice(0, num);
}
let maxLabelsToShow = 3;
let serverData = [12, 19, 3, 5, 3]
let labels = ['E-commerce', 'Enterprise', 'Green', 'Grey', 'Purple'];
// Calling the newly created function
let showOnly = getLabelsOnlyTopX(maxLabelsToShow, serverData, labels);
const data = {
labels: labels,
datasets: [{
data: serverData,
backgroundColor: ['#C07CC3', '#9C3848',
'#9DDBAD', '#ADA8B6', '#606EDA'],
borderWidth: 1,
}],
};
const config = {
type: 'doughnut',
data: data,
options: {
maintainAspectRatio: false,
plugins: {
legend: {
position: 'right',
labels: {
usePointStyle: true,
/* FILTER function */
filter: function(item, chart) {
return showOnly.indexOf( item.text) > -1;
}
},
}
},
}
};
new Chart(
document.getElementById('chart'),
config
);
<script src="//cdn.jsdelivr.net/npm/chart.js"></script>
<div class="chart" style="height:184px; width:350px;">
<canvas id="chart" ></canvas>
</div>

Using Numeral.js to round JSON numbers in %

I am fetching json data from a API and I have to display some of the numbers as %. The json data displays them as 0.00. I tried this method, but it didn't work. I want to use a url to fetch my data, and then use Numeral.js to make the filtered data I got in %. What am I doing wrong? I create a template for my graph. I then make a fetch request to get my data and filter it, so I get the values I need. Then I take that value and try to format it. The new value I want to put on the graph.
const data = {
labels: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
datasets: [
{
label: "ADOPTION",
data: [18, 12, 6, 9, 12, 3, 9],
backgroundColor: "rgba(73, 117, 197, 1)",
borderColor: "rgba(73, 117, 197, 1)"
},
{
label: "Target",
data: [0.654, 0.654, 0.751],
backgroundColor: "rgba(236, 123, 46, 1)",
borderColor: "rgba(236, 123, 46, 1)"
}
]
};
// config for graph
const config = {
type: "line",
data: data,
options: {
plugins: {
title: {
display: true,
text: 'data'
},
},
scales: {
y: {
beginAtZero: true
}
}
}
};
// render init block
const myChart = new Chart(
document.getElementById("data"),
config
);
// Fethc block for the graph
async function fetchJSON() {
const url="link";
const response = await fetch(url);
//* loads waiting to complete the request
const datapoints = await response.json();
return datapoints;
}
fetchJSON().then((datapoints) => {
const month = datapoints.map(function (index) {
return index.PERIOD_NAME; //*reffers to jSon word from file
});
console.log(month);
myChart.config.data.labels = month;
myChart.update();
});
fetchJSON().then((datapoints) => {
const total = datapoints.map(function (index) {
return index.ADOPTION //*reffers to jSon word from file
});
var string = numeral(datapoints).format('0.000%');
console.log(string);
myChart.config.data.datasets[0].data = total;
myChart.update();
});
<div class="col-sm-12 col-md-4 col-lg-4">
<canvas id="data"></canvas>
</div>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/chart.js"></script>
I'm guessing datapoints is an array. Numeral takes numbers or strings that it trys to convert into a number. You can use datapoints.map(val => numeral(val).format('0.00%')) to format the datapoints elements.

vue3 chart-js showing previous data on hover

vue3 chart-js showing previous data on hover.
I updated my chart data filed using API data but after updating the chat data, chart is showing previous API data on hover
i also tried using distory()
here are my codes
methods: {
barChart() {
var Chart = require("chart.js");
let options = new Chart(document.getElementById("bar-chart-grouped"), {
type: "bar",
data: {
labels: this.llabels,
datasets: [
{
label: "पुरुष जनसंख्या",
backgroundColor: "rgba(0, 143, 251, 0.8)",
data: this.mdata,
},
{
label: "महिला जनसंख्या",
backgroundColor: "rgba(0, 227, 150, 0.8)",
data: this.Fdata,
},
{
label: "पअन्य जनसंख्या",
backgroundColor: "rgb(254, 176, 25,0.8)",
data: this.Odata,
},
],
},
});
if (!this.chart) {
this.chart = options;
} else {
this.chart.options = options;
this.chart.update();
}
},
}
Instead of this.chart.options = options;, use this.chart.options = options.options;
The variable options is holding your chart, not only the options.
A better approach would be to only create the chart on the first run of that method (=> place the new Chart inside the if)

Chart.js with Django - Using REST

Using Django rest frame work i have my query set-up and pulling my data to a url like below. I'm trying to get the data in to chart.js. I can manage to get it to the console or plot the first result, but no further any assistance would be greatly appreciated
"comp_history_data": [
[
"(2017, 01, 20)",
256.0
],
[
"(2018, 01, 20)",
456.0
],
[
"(2018, 02, 20)",
568.0
],
[
"(2018, 03, 20)",
683.0
]
],
Here is what i have in my HTML, works fine with dummy data, just not too sure how to plot with the data above
<script>
var endpoint = '/api/chart/data/'
var defaultData = []
var labels = [];
$.ajax({
method: "GET",
url: endpoint,
success: function(data){
labels = data.labels
defaultData = data.comp_history_data.forEach(functoin(entry){
console.log(entry)
setChart()
},
error: function(error_data){
console.log("error")
console.log(error_data)
}
})
function setChart(){
var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx2, {
type: 'line',
data: {
labels: labels,
datasets: [{
label: '# of Computers',
data: defaultData,
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
],
borderColor: [
'rgba(255,99,132,1)',
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
});
}
</script>
Small Edit: I can get one item onto the graph with the code below, so looks like the data is coming through OK, just need to separate
<script>
var endpoint = '/api/chart/data/'
var defaultData = []
var labels = [];
$.ajax({
method: "GET",
url: endpoint,
success: function(data){
labels = data.labels
defaultData = data.comp_history_data.forEach(functoin(entry){
console.log(entry)
setChart()
},
error: function(error_data){
console.log("error")
console.log(error_data)
}
})
function setChart(){
var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx2, {
type: 'line',
data: {
labels: labels,
datasets: [{
label: '# of Computers',
data: defaultData[0],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
],
borderColor: [
'rgba(255,99,132,1)',
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
});
}
</script>
Any thoughts on how i use the data array i have with chart.js I would like the 0 the data to be along the bottom with the numbers plotted on the graph
Thanks again
Remember to include <canvas id="myChart"></canvas> within your html file.
That might be all you need. If not, this is a working function I have - I've not changed my variable names to match your's but I think it easy to understand.
success : function(json) {
// Add graph
var chartLabels = json.categories.map(function(e) {
return e.name;
})
var chartValues = json.values.map(function(e) {
return e;
})
var ctx = document.getElementById("myChart");
var data = {
labels: chartLabels,
datasets: [{
"label" : json.startRegulation[0].name,
"data" : chartValues,
"fill" : true,
"backgroundColor":"rgba(255, 99, 132, 0.2)",
"borderColor":"rgb(255, 99, 132)",
"pointBackgroundColor":"rgb(255, 99, 132)",
"pointBorderColor":"#fff",
"pointHoverBackgroundColor":"#fff",
"pointHoverBorderColor":"rgb(255, 99, 132)"
}]
}
var options = {
"elements":
{"line":{"tension":0,"borderWidth":3}
},
scale : {
ticks : {
min : 0,
}
}
}
var myChart = new Chart(ctx, {
type: 'radar',
data: data,
options : options,
});
Try to change :
defaultData = data.comp_history_data.forEach(functoin(entry){
to :
defaultData = data.comp_history_data.forEach(function(entry)){
Also, read the usage of template filters (Django) maybe you will find them helpful.
For instance, from your views.py file send data :
def MyView(request):
comp_history_data: ['1', '2', '3']
return render(request, 'chart.html', {'comp_history_data':comp_history_data})
and then in your HTML file print the vars :
{% for var in comp_history_data %}
{{ var }}
{% endfor %}
Hope it helps
It looks like you have an error in your success function, as below
defaultData = data.comp_history_data.forEach(functoin(entry){
to:
defaultData = data.comp_history_data.forEach(function(entry){

How to get the dataset value in table using Jquery

I was trying to get the label and data value from the following
var barChartData = {
labels: Months,
datasets: [{
label: 'Dataset 1',
backgroundColor: "#09a",
data: [5, 10, 15, 20, 25, 30, 35]
}]
};
I tried using alert(JSON.stringify(barChartData.datasets.data)); but I got output as undefined. Please help me to find out this .
Like Sachin K wrote in the comment.
You forget that datasets is an array containing an object.
Therefor you need
alert(JSON.stringify(barChartData.datasets[0].data))
With the [0] you specify that you want the value from the first element in the array (array's are zero based)
Try this approach..
var barChartData = {
labels: 'Months',
datasets: [{
label: 'Dataset 1',
backgroundColor: "#09a",
data: [5, 10, 15, 20, 25, 30, 35]
}]
};
//For multiple dataset
var data = []; label = [];
barChartData.datasets.map(function(dt) {
data.push(dt.data);
label.push(dt.label);
})
//Single datasets
var data1 = barChartData.datasets[0].data;
var label1 = barChartData.datasets[0].label;
console.log(data, label, data1, label1);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Categories

Resources