how to change default font family in react-chartjs-2 - chart.js

i have bar chart with "react-chartjs-2", where should i put my font family for labels of chart in xAxes:
this way:(not worked)
<Bar
data={chartData}
options={{ defaults: { global: { defaultFontFamily:"iransans} }}}
/>
this way not worked to:
<Bar
data={chartData}
options={{ font: { family: "iransans" }}}
/>
any body know this????

so after seeing a post in github, this way worked:
first import defaults:
import { defaults } from 'react-chartjs-2';
and then somewhere set font like this:
defaults.font.family = 'font name...';

If you are using chart.js 3.x+, refer the following code in order to change the font of your ticks, tooltip and legend:
// inside data.js(or your own data file)
const options = {
responsive: true,
maintainAspectRatio: false,
plugins: {
legend: {
display: true,
labels: {
color: "rgb(255, 99, 132)",
font: {
family: "Montserrat" // Add your font here to change the font of your legend label
}
},
tooltip: {
bodyFont: {
family: "Montserrat" // Add your font here to change the font of your tooltip body
},
titleFont: {
family: "Montserrat" // Add your font here to change the font of your tooltip title
}
}
}
},
tooltips: {
backgroundColor: "#f5f5f5",
titleFontColor: "#333",
bodyFontColor: "#666",
bodySpacing: 4,
xPadding: 12,
mode: "nearest",
intersect: 0,
position: "nearest"
},
scales: {
yAxes: {
barPercentage: 1.6,
grid: {
display: false,
color: chartLineColor,
zeroLineColor: "transparent"
},
ticks: {
suggestedMin: 0,
suggestedMax: 125000,
padding: 2,
backdropPadding: 2,
backdropColor: "rgba(255,255,255,1)",
color: chartLineColor,
font: {
family: "Montserrat", // Add your font here to change the font of your y axis
size: 12
},
major: {
enable: true
}
}
},
xAxes: {
barPercentage: 1.6,
grid: {
display: false,
zeroLineColor: "transparent"
},
ticks: {
padding: 20,
color: chartLineColor,
font: {
family: "Montserrat", // Add your font here to change the font of your x axis
size: 12
},
major: {
enable: false
}
}
}
}
};
Inside your react component:
import {someData,options} from './data.js'
function SomeComponent{
return(
<>
<Line data={someData} options={options} />
</>
)
}
Hope this was useful. For further reference, refer this article

Defaults are missing in react-chartjs-2 library v4, so it should be imported from chart.js directly:
import { defaults } from 'chart.js';
and then somewhere set font like this:
defaults.font.family = 'font name...';

Related

Chartjs scales.xAxis: Property 'title' does not exist on type '_DeepPartialObject

I have upgraded from chartjs v2.8.0 to 4.2.1, and I am trying to set the legend title in a line chart, however I am getting this vscode error...
However if I look at the object, title certainly seems to be there...
Any ideas why I am getting this type error, or alternatively how to set the legend text (dynamically)?
[UPDATE1]
As extra information, here is how I set up my chart (in an Angular component)
/**
* Create the chart and empty data object
*/
private createChart(): void {
if (this.chart !== undefined) {
return;
}
Chart.register(LineController, PointElement, Tooltip, Legend, TimeScale, LinearScale, CategoryScale, LinearScale, LineElement);
this.chartData = {
datasets: [{
fill: false, // shading under the line
data: []
}]
};
const options: ChartOptions = {
plugins: {
legend: {
display: false,
labels: {
padding: 10
}
}
},
elements: {
line: {
borderColor: this.lineColour // line colour
}
},
responsive: true,
maintainAspectRatio: false,
scales: {
x: {
ticks: {
source: 'auto',
maxRotation: 60,
minRotation: 60,
autoSkip: true,
},
grid: {
color: this.gridLinesColor
},
//label: { labelString: '', display: true },
type: 'time',
display: true,
position: 'bottom',
time: {
unit: 'minute',
displayFormats: {
minute: this.runtimeStatusService.getCacheTimePattern()
}
}
},
y:
{
min: 0,
grid: {
color: this.gridLinesColor,
},
}
}
};
this.chart = new Chart(this.chartRef.nativeElement, {
type: 'line',
data: this.chartData,
options
});
}
And this is how I use to be able to set the x Axis legend text (in v2)
this.chart.config.options.scales.xAxes[0].scaleLabel.labelString = legendText;
And it use to show up like this....
So I just want to do the same in v4
I found I could do what I was after by now adding a chart title.
First I add title to the register..
Chart.register(LineController, PointElement, Tooltip, Legend, Title /* <-- add this **/, TimeScale, LinearScale, CategoryScale, LinearScale, LineElement);
Next I add the title to the plugings...
const options: ChartOptions = {
plugins: {
legend: {
display: false, <---- HIDE THIS
position: 'bottom',
labels: {
padding: 10,
}
},
title: {
display: true, <---- SHOW THIS
position: 'bottom',
text: ''
},
},
And now I can set the title at runtime...
this.chart.config.options.plugins.title.text = 'hello';
In my case, this is all I am after...

why the main and axis title does not show in chart.js

I have the following code to make a chart with chart.js but the main and axis title just does not work. Also I have put the legend to the bottom but does not work. Can anybody tell why it is not working?
let dataSize = 30;
let readings = new Array(dataSize);
const data = {
// X axis labels
labels: new Array(dataSize),
datasets: [{
//label: 'My Input', // chart label
data: readings, // the data to chart
//borderColor: '#272323', // line color (lavender)
backgroundColor: 'rgba(123, 83, 252, 80)',
borderColor: "rgba(255, 0, 0,1)",
borderWidth: 1.2,
pointBorderColor: "rgba(255, 0, 0, 1)",
pointRadius: 0.2 // point size
}]
};
const config = {
type: 'line', // type of chart
data: data, // the data
options: {
animation: false, // remove animation to speed drawing up
responsive: true,
maintainAspectRatio: false,
title: {
display: true,
text: 'Tarrif'
},
legend:{
position: 'bottom'
},
scales: { // axis ranges:
y: {
//type: 'linear',
scaleLabel: {
display: true,
labelString: 'X axis Title'
},
min: 0,
max: 260,
gridLines: {
display: true,
drawBorder: false //hide the chart edge line
}
},
x:[{
gridLines: {
display: false
},
scaleLabel: {
display: true,
labelString: 'X axis Title'
},
min:0
}]
}
}
};
Below is screenshot of my graph:
I followed the advice here:
In Chart.js set chart title, name of x axis and y axis?
thanks
First of all don't use an array for your X scales, all the scales need to be defined as objects. Second you are placing the options in the wrong part, it has to be configured in the title namespace like so:
scales: {
y: {
title: {
display: true,
text: 'yTitle'
}
},
x: {
title: {
display: true,
text: 'xTitle'
}
}
}

Add labels to bar chart: chartjs

I am creating bar charts using chartjs 3.5.1, and I am new to chartjs. I want to add value labels to each bar in my bar chart.
I have reviewed some relevant answers, but they are either too old or too complicated to achieve.
Below is the intended outcome, note that the non-hand-written part is what I have achieved.
The code is below:
let chart2 = new Chart('chart2', {
type: 'bar',
data: {
labels: ["a", "b", "c", "d"],
datasets: [{
data: [500, 400, 300, 200],
}]
},
options: {
indexAxis: 'y',
plugins: {
title: {
display: true,
text: "Graph"
},
legend: {
display: false,
}
},
scales: {
y: {
grid: {
display: false
},
},
x: {
grid: {
display: false
}
}
}
},
});
Really appreciate your help!
You can use the chartjs-plugin-datalabels library.
First you'll have to register the plugin, then you can define the desired options inside options.plugins.datalabels.
Please take a look at your amended code and see how it works.
Chart.register(ChartDataLabels);
new Chart('chart2', {
type: 'bar',
data: {
labels: ["a", "b", "c", "d"],
datasets: [{
data: [500, 400, 300, 200],
}]
},
options: {
indexAxis: 'y',
layout: {
padding: {
right: 60
}
},
plugins: {
title: {
display: true,
text: "Graph"
},
legend: {
display: false,
},
datalabels: {
color: 'blue',
anchor: 'end',
align: 'right',
labels: {
title: {
font: {
weight: 'bold'
}
}
}
}
},
scales: {
y: {
grid: {
display: false
},
},
x: {
grid: {
display: false
}
}
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.1/chart.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-datalabels/2.0.0/chartjs-plugin-datalabels.min.js"></script>
<canvas id="chart2" height="100"></canvas>

Chart.js how to use scriptable options

I am migrating chart.js to 3.x as per the migration guide.
https://www.chartjs.org/docs/master/getting-started/v3-migration/
I am trying to set the xAxis zeroLineColor to "#FFFFFF" and I want to have the Grid line color as "#00FFFF" but as per the chart.js migration document document scales.[x/y]Axes.zeroLine* options of axes were removed. Use scriptable scale options instead.
I am not sure how to use scriptable scale options for setting the xAxis line zero to white.
Update:
Working example:
https://jsfiddle.net/g4vq7o2b/2/
In order to obtain different colors for the grid's zero line, you could define an array of colors for the option gridLines.color.
gridLines: {
drawBorder: false,
color: ["#FFFFFF", "#00FFFF", "#00FFFF", "#00FFFF", "#00FFFF"]
}
Since gridLines.color is a scriptable options, it also accepts a function which is invoked with a context argument for each of the underlying data values as follows:
gridLines: {
drawBorder: false,
color: context => context.tick.value == 0 ? "#FFFFFF" : "#00FFFF"
}
Please take a look at below runnable code and see how it works.
new Chart(document.getElementById("myChart"), {
type: "line",
data: {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [{
label: "My Dataset",
data: [2, 3, 1, 4, 2, 4, 2],
fill: false,
backgroundColor: "rgba(0, 255, 0, 0.3)",
borderColor: "rgb(0, 255, 0)"
}]
},
options: {
scales: {
y: {
min: 0,
ticks: {
stepSize: 1
},
gridLines: {
drawBorder: false,
color: context => context.tick.value == 0 ? "#FFFFFF" : "#00FFFF"
}
},
x: {
gridLines: {
drawBorder: false,
color: context => context.tick.value == 0 ? "#FFFFFF" : "#00FFFF"
}
}
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.0.0-beta/chart.min.js"></script>
<canvas id="myChart" height="90"></canvas>
Using chart_v3.7.0.js cartesian time axis, for me, configuring zeroline and other gridlines works, using scriptable options.
Apply property for "context.tick.value == 0" (=baseline)
like:
...
options: {
scales: {
x: {
gridLines: {
color: "#00ff00",
},
ticks: { font: { size: 30 },
maxRotation: 90,
minRotation: 90,
},
type: 'time',
time: {
/*tooltipFormat: "DD.MM hh:mm",*/
displayFormats: {
minute: 'HH:mm',
hour: 'HH:mm',
day: 'dd.MMM',
}
},
},
y: {
grid: {
color: (line) => (line.index === 0 ? 'red' : 'rgba(0, 0, 0, 0.1)') //color of lowest horizontal grid line
color: context => context.tick.value == 0 ? "#FFFFFF" : "#00FFFF", // zero-line baseline color
lineWidth: context => context.tick.value == 0 ? 3 : 1, // zero-line baseline width
},
position: 'right', // show axis on the right
title: { display: true,
rotation: 0,
text: "°C", },
},
},

gap between half doughnut chart and container div

I'm trying to build a doughnut chart with chart.js but the chart container is bigger than the chart canvas and it makes it harder to design stuff around it...
is there any option to make the chart and the container the same height and width?
settings:
var option = {
rotation: 1 * Math.PI,
circumference: 1 * Math.PI,
responsive: true,
aspectRatio:2,
title: { display: false },
legend: { display: false },
scales: {
xAxes: [
{
gridLines: {
drawBorder: false,
display: false,
},
ticks: {
display: false,
},
},
],
yAxes: [
{
gridLines: {
drawBorder: false,
display: false,
},
ticks: {
display: false,
},
},
],
}
};
Code Pen:
https://codepen.io/ronmara/pen/vYGeJyo
You can see there is a little gap between the left, right, and bottom border of the div.
It's a bit of a hacky solution, but setting layout.padding to -10 fits your doughnut more neatly in your container:
var data = {
labels: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul"],
datasets: [
{
label: "Dataset #1",
backgroundColor: "rgba(255,99,132,0.2)",
borderColor: "rgba(255,99,132,1)",
borderWidth: 2,
hoverBackgroundColor: "rgba(255,99,132,0.4)",
hoverBorderColor: "rgba(255,99,132,1)",
data: [65, 59, 20, 81, 56, 55, 40]
}
]
};
var option = {
rotation: 1 * Math.PI,
circumference: 1 * Math.PI,
responsive: true,
aspectRatio: 2,
title: { display: false },
legend: { display: false },
layout: {
padding: -10
},
scales: {
xAxes: [
{
gridLines: {
drawBorder: false,
display: false
},
ticks: {
display: false
}
}
],
yAxes: [
{
gridLines: {
drawBorder: false,
display: false
},
ticks: {
display: false
}
}
]
}
};
Chart.Doughnut("chart_0", {
options: option,
data: data
});
body {
background: white;
padding: 16px;
}
canvas {
border: 1px dotted red;
}
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.9.3"></script>
<div class="chart-container" style="position: relative; height:16vh; width:32vh">
<canvas id="chart_0"></canvas>
</div>
I got it centered by removing the inline styles and adding them to the class attached to the div.
I also added the layout.padding into your options.
layout: {
padding: {
left: 0,
top: 10,
right: 10,
bottom: 0
}},
Adding codepen for reference. https://codepen.io/robert9111/pen/abNVxWY