Label is too long in Doughnut Chart - javascript

I try to display a Doughnut Chart with the chart.js library.
Here is the code that I am using:
var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
type: 'doughnut',
data: {
labels: ['long long long long long long title', 'title', 'title', 'title', 'title'],
datasets: [{
data: [54,36,12,4,20],
backgroundColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
}]
},
options: {
legend: {
display: true,
position: 'bottom',
labels: {
fontColor: 'rgb(0, 0, 0)',
fontFamily: 'Open Sans',
fontSize: 16,
fullWidth: true,
padding:15
}
}
}
});
I have the problem that for a certain page width the long long ... long title is not correctly displayed.
In some situations it looks like this:
Is there anything I can do so that the long label will be shown in multiple lines instead of leaving the box?
Here is a jsfiddle
https://jsfiddle.net/9fc5evjk/

This is not supported "out of the box" by chart.js. You will need to determine what solution works best for you and implement it yourself. You will need to provide modified strings to the instantiation of myChart.
You could automatically truncate a title after X number of characters, maybe add a '...' to the end when it happens to make it obvious when a title has been shortened.

Related

Multiple Charts in one page with Laravel & Chartjs

I'm trying to display two charts in one page. I'm expecting like 1 doughnut and 1 pie.
Here's my view snippets:
First Chart
<div class="card-body d-flex flex-center flex-column" style="width: 381px; height:350px;">
<!-- Find the JS file for the following chart at: src/js/charts/echarts/bandwidth-saved.js-->
<!-- If you are not using gulp based workflow, you can find the transpiled code at: public/assets/js/theme.js-->
<canvas id="pengeluaran" width="350"></canvas>
</div>
Second Chart
<div class="card-body d-flex flex-center flex-column" style="width: 381px; height:350px;">
<!-- Find the JS file for the following chart at: src/js/charts/echarts/bandwidth-saved.js-->
<!-- If you are not using gulp based workflow, you can find the transpiled code at: public/assets/js/theme.js-->
<canvas id="sponsorship" width="350"></canvas>
</div>
I tried the solution at Two charts in a page not working, using Chart.js 3.1.1 cdn in Laravel 8.x framework & Multiple charts in one page - Chartjs, but it's seems doesn't work for me. I tried to implement it, but only the first chart is displaying on the page.
It's displays the error "Failed to create chart: can't acquire context from the given item", I double check everything and I can't find what's cause of the error.
Here's the javascript file:
<script>
const ctx1 = document.getElementById('pengeluaran');
const ExpensesLabel = ['Rewards', 'Bantuan', 'Others'];
const ExpensesData = {
labels :ExpensesLabel,
datasets: [{
label: 'Sebaran Pengeluaran untuk Anak',
data: [300, 50, 100],
backgroundColor: [
"rgb(255, 99, 132, 0.2)", "rgb(54, 162, 235, 0.2)",
"rgb(255, 206, 86, 0.2)",
],
borderColor: [
"rgb(255, 99, 132, 1)", "rgb(54, 162, 235, 1)",
"rgb(255, 206, 86, 1)",
],
hoverOffset: 4,
borderWidth: 1,
}]};
const options1 = {
responsive: true,
maintainAspectRatio: true,
layout: {
padding: 10
}
};
new Chart(ctx1, {
type: 'doughnut',
data: ExpensesData,
options: options1
});
</script>
Second Charts
<script>
const ctx2 = document.getElementById('sponsorship');
const SponsorLabel = ['TK','SD','SMP','SMA-K / Kuliah'];
const SponsorData = {
labels : SponsorLabel,
datasets: [{
label: 'Sebaran Penerimaan Hadiah Sponsor',
data: [300, 50, 100, 90],
backgroundColor: [
"rgb(255, 99, 132, 0.2)", "rgb(54, 162, 235, 0.2)",
"rgb(255, 206, 86, 0.2)", "rgb(75, 192, 192, 0.2)",
],
borderColor: [
"rgb(255, 99, 132, 1)", "rgb(54, 162, 235, 1)",
"rgb(255, 206, 86, 1)", "rgb(75, 192, 192, 1)",
],
hoverOffset: 4,
borderWidth: 1
}]
};
const options2 = {
responsive: true,
maintainAspectRatio: true,
layout: {
padding: 10
}
};
new Chart(ctx2, {
type: 'pie',
data: SponsorData,
options: options2,
});
</script>
Is there anything I missed? Any help would be appreciated! Thanks
Sorry for late reply. The fix was it was conflicting id naming with other div in the blade file. So I had to rename the second chart canvas id to different name. The code above works perfectly though, as explained and tested by FiddlingAway in the comment section.
<canvas id="sponsorship-charts" width="350"></canvas>

chart.js random weird problems

this to me makes absolutely no logical sense.
my graph.js was working until it randomly just stopped after passing local storage as a prop. i refactored to make the prop passed in completely unrelated to the local storage... which still shouldn't matter.
for some reason every single number i put into the data field works EXCEPT when i put in props.score/number or ANYTHING reassigned that number. ive never seen anything like it. when i console log number is is 82. it is a number (it is blue in the console) yet when i put it into chart.js it just won't appear.
what the heck is going on?!
this feels like typing 2+2 into a calculator and getting 5. i literally have no idea i have now been trying to figure this out for maybe 4 hours with absolutely no answer. once again...
this error just happened randomly today my app was working fine prior to this...?!
did chart.js change something as of yesterday?
is this a random bug ?
i have never run into such a problem after backtracking for so long. makes no sense.
import {useEffect} from 'react'
import Chart from 'chart.js';
import './BreakDown.css'
const LineChart = (props) => {
const number=props.score ***i am trying to get props.score into the chart js data point.
console.log(number) ****this console logs 82
const newNumber=10+number
console.log(newNumber) ***this console logs 92
useEffect(()=>{
var ctx = document.getElementById('myLineChart');
var myChart = new Chart(ctx, {
type: 'line',
responsive:true,
data: {
labels: ['X', 'IQ', 'X'],
datasets: [{
label: 'Your Score',
data: [0,newNumber,0], ***no matter what i do plug in in either of these numebnrs here doesn't work.
backgroundColor: [
'rgba(54, 80, 235, 0.2)',
'rgba(54, 80, 235, 0.2)',
'rgba(54, 162, 235, 0.2)'
],
borderColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
],
borderWidth: 1,
},
{
label: 'Average',
data: [0, 100, 0],
backgroundColor: [
'rgba(54, 162, 235, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(54, 80, 235, 0.2)',
],
borderColor: [
'rgba(255, 99, 132, .5)',
'rgba(255, 99, 132, .5)',
'rgba(255, 99, 132, .5)',
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: false,
suggestedMin: 70,
suggestedMax: 160,
stepSize: 10
}
}]
}
}
});
},[])
return (
<div >
<canvas id="myLineChart" width="650" height="400"></canvas>
</div>
)
}
export default LineChart
to make things EVEN more bizarre if i plug in newNumber into the chart it gives me 10 in this case EVEN though console.logging newNumber gives me 92... HUH?!
Your code works fine on the first render for me. I am not 100% sure from your description what you think is going wrong, but 1 problem I see is that useEffect will only run once due to the [] in the second parameter.
If your prop.score updates, useEffect() won't run again, which means your chart won't update.
The main change I did below was add props.score in the array for useEffect, this tells useEffect to run again if props.score changes. You can read more about this in the useEffect docs
import React, { useEffect } from 'react'
import Chart from 'chart.js';
const LineChart = (props) => {
const number = props.score //***i am trying to get props.score into the chart js data point.
console.log(number) //****this console logs 82
const newNumber = 10 + number
console.log(newNumber) //***this console logs 92
useEffect(() => {
var ctx = document.getElementById('myLineChart');
var myChart = new Chart(ctx, {
type: 'line',
responsive: true,
data: {
labels: ['X', 'IQ', 'X'],
datasets: [{
label: 'Your Score',
data: [0, newNumber, 0],
backgroundColor: [
'rgba(54, 80, 235, 0.2)',
'rgba(54, 80, 235, 0.2)',
'rgba(54, 162, 235, 0.2)'
],
borderColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
],
borderWidth: 1,
},
{
label: 'Average',
data: [0, 100, 0],
backgroundColor: [
'rgba(54, 162, 235, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(54, 80, 235, 0.2)',
],
borderColor: [
'rgba(255, 99, 132, .5)',
'rgba(255, 99, 132, .5)',
'rgba(255, 99, 132, .5)',
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: false,
suggestedMin: 70,
suggestedMax: 160,
stepSize: 10
}
}]
}
}
});
}, [props.score])
return (
<div >
<canvas id="myLineChart" width="650" height="400"></canvas>
</div>
)
}
export default LineChart

Using Chart.js - The X axis labels are not all showing

I'm using Chart.js for my pie/bar charts and on the line and the bar chart all of the 'x' axis labels are not all showing for some reason, however in the pie chart they are:
Code below has been used and the 'type' has just been altered for the type of graph I wished to use:
var ctx = document.getElementById("my3Chart");
var mylineChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["Time Management", "Career Coach", "Stress & Wellbeing", "Note Taking", "Exam Prep", "Presentations"],
datasets: [{
label: 'Module Tracker',
data: [6, 4, 2, 0, 3, 1],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)'
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
});
I've tested your code in a fiddle with Chart.js 2.0 for both bar/line and it looks fine. Chart takes in x-axis labels with:
labels: ["Time Management", "Career Coach", "Stress & Wellbeing", "Note Taking", "Exam Prep", "Presentations"]
The reason you can't see all your x-axis labels is that the width's are too thin. You can fix this by either expanding your width, or rotating your labels to be vertical instead.
400px width example: https://jsfiddle.net/swcy2opv/
Rotated labels example: https://jsfiddle.net/swcy2opv/1/

Getting 'Chart is not defined' error when using chart.js in Meteor

I am using the official chart.js atmosphere package in my meteor application. I've tried running an example chart to see if I can pull it up however I am getting an issue saying "ReferenceError: Chart is not defined"
Here are the steps I took to installing the atmosphere package and running the code to produce the chart.
Installed the package with meteor add chart:chart
In my HTML I added the canvas tag calling the chart with it's informaiton
In the JS I added the function that creates the chart along with its relevant information
When I go to the page however, I just get an empty 400x400 image which is the canvas but there is no content there where the chart is supposed to be. Could someone assist me in figuring out what step I'm missing in order to get the chart to appear?
HTML
<template name="Home_page">
<canvas id="myChart" width="400" height="400"></canvas>
</template>
JS
import './home-page.html';
Template.Home_page.onRendered(function homePageOnRendered() {
var ctx = document.getElementById("myChart").getContext("2d");
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
});
});
Ok I forgot to add
import Chart from 'chart.js'
in the top of my js file. That fixed it.

Is it possible to add a custom font to chart js?

I want to use a external font in my chart made with Chart JS. Does anyone know if that is possible? I've searched trough the documentation but I haven't found a solution.
It is indeed possible.
Considering you have imported your font (from GoogleFonts for instance),
you just have to edit the defaultFontFamily attribute in your chart options like this :
var options = {
// 'Raleway' is the name of the fond I imported from GoogleFonts
defaultFontFamily: Chart.defaults.global.defaultFontFamily = "'Raleway'"
}
See Lolka's answer for more information about the defaultFontFamily attribute.
A full working example:
Chart.defaults.global.defaultFontFamily = "Indie Flower";
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.6/Chart.min.js"></script>
<link href='https://fonts.googleapis.com/css?family=Indie+Flower' rel='stylesheet' type='text/css'>
<canvas id="myChart" width="400" height="400"></canvas>
First result for google Chart.JS custom font
From documentation:
There are 4 special global settings that can change all of the fonts
on the chart. These options are in Chart.defaults.global.
...
defaultFontFamily String "'Helvetica Neue', 'Helvetica', 'Arial',
sans-serif" Default font family for all text

Categories

Resources