How can I change the font (family) for the labels in Chart.JS? - javascript

I want to change the font to something snazzier in my Chart.JS horizontal bar chart. I've tried the following, but none of it works:
var optionsBar = {
. . .
//fontFamily: "'Candara', 'Calibri', 'Courier', 'serif'"
//bodyFontFamily: "'Candara', 'Calibri', 'Courier', 'serif'"
//bodyFontFamily: "'Candara'"
label: {
font: {
family: "Georgia"
}
}
};
I also read that this would work:
Chart.defaults.global.defaultFont = "Georgia"
...but where would this code go, and how exactly should it look? I tried this:
priceBarChart.defaults.global.defaultFont = "Georgia";
...but also to no good effet.
For the full picture/context, here is all the code that makes up this chart:
HTML
<div class="chart">
<canvas id="top10ItemsChart" class="pie"></canvas>
<div id="pie_legend"></div>
</div>
JQUERY
var ctxBarChart =
$("#priceComplianceBarChart").get(0).getContext("2d");
var barChartData = {
labels: ["Bix Produce", "Capitol City", "Charlies Portland",
"Costa Fruit and Produce", "Get Fresh Sales",
"Loffredo East", "Loffredo West", "Paragon", "Piazza Produce"],
datasets: [
{
label: "Price Compliant",
backgroundColor: "rgba(34,139,34,0.5)",
hoverBackgroundColor: "rgba(34,139,34,1)",
data: [17724, 5565, 3806, 5925, 5721, 6635, 14080, 9027,
25553]
},
{
label: "Non-Compliant",
backgroundColor: "rgba(255, 0, 0, 0.5)",
hoverBackgroundColor: "rgba(255, 0, 0, 1)",
data: [170, 10, 180, 140, 30, 10, 50, 100, 10]
}
]
}
var optionsBar = {
scales: {
xAxes: [{
stacked: true
}],
yAxes: [{
stacked: true
}]
},
//fontFamily: "'Candara', 'Calibri', 'Courier', 'serif'"
//bodyFontFamily: "'Candara', 'Calibri', 'Courier', 'serif'"
//bodyFontFamily: "'Candara'"
//Chart.defaults.global.defaultFont = where does this go?
label: {
font: {
family: "Georgia"
}
}
};
var priceBarChart = new Chart(ctxBarChart, {
type: 'horizontalBar',
data: barChartData,
options: optionsBar
});
//priceBarChart.defaults.global.defaultFont = "Georgia";
I even tried this:
CSS
.candaraFont13 {
font-family:"Candara, Georgia, serif";
font-size: 13px;
}
HTML
<div class="graph_container candaraFont13">
<canvas id="priceComplianceBarChart"></canvas>
</div>
...but I reckon the canvas drawing takes care of the font appearance, as adding this made no difference.
UPDATE
I tried this and it completely broke it:
Chart.defaults.global = {
defaultFontFamily: "Georgia"
}
UPDATE 2
As Matthew intimated, this worked (before any of the chart-specific script):
Chart.defaults.global.defaultFontFamily = "Georgia";

This should be useful: http://www.chartjs.org/docs/. It says "There are 4 special global settings that can change all of the fonts on the chart. These options are in Chart.defaults.global".
You'll need to change defaultFontFamily for the font. And defaultFontColor, defaultFontSize, and defaultFontStyle for color, size, etc.

If you wanted to add the font-family to the chart object then you can add it in the options object.
options: {
legend: {
labels: {
fontFamily: 'YourFont'
}
}...}
Here is a link to the docs: https://www.chartjs.org/docs/latest/general/fonts.html

Change font size, color, family and weight using chart.js
scales: {
yAxes: [{ticks: {fontSize: 12, fontFamily: "'Roboto', sans-serif", fontColor: '#000', fontStyle: '500'}}],
xAxes: [{ticks: {fontSize: 12, fontFamily: "'Roboto', sans-serif", fontColor: '#000', fontStyle: '500'}}]
}
See the full code
<!doctype html>
<html>
<head>
<title>Chart.js</title>
<link href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700" rel="stylesheet">
<script src="js/Chart.bundle.js"></script>
<script src="js/utils.js"></script>
<style>
canvas {
-moz-user-select: none;
-webkit-user-select: none;
-ms-user-select: none;
font-weight:700;
}
</style>
</head>
<body>
<div id="container" style="width:70%;">
<canvas id="canvas"></canvas>
</div>
<script>
var MONTHS = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var color = Chart.helpers.color;
var barChartData = {
labels: ["Jan", "Feb", "Mar", "Apr", "May", "Jun"],
datasets: [{
label: 'Completed',
// Green
backgroundColor: '#4caf50',
borderColor: '#4caf50',
borderWidth: 1,
data: [
5, 15, 25, 35, 45, 55
]
}, {
label: 'Created',
// Blue
backgroundColor: '#1976d2',
borderColor: '#1976d2',
borderWidth: 1,
data: [
10, 20, 30, 40, 50, 60
]
}]
};
window.onload = function () {
var ctx = document.getElementById("canvas").getContext("2d");
window.myBar = new Chart(ctx, {
type: 'bar',
data: barChartData,
options: {
responsive: true,
legend: {
position: 'top',
onClick: null
},
title: {
display: true,
text: '',
fontSize: 20
},
scales: {
yAxes: [{ticks: {fontSize: 12, fontFamily: "'Roboto', sans-serif", fontColor: '#000', fontStyle: '500'}}],
xAxes: [{ticks: {fontSize: 12, fontFamily: "'Roboto', sans-serif", fontColor: '#000', fontStyle: '500'}}]
}
}
});
};
</script>
</body>
</html>

You named the chart priceBarChart in the following part of your code:
var priceBarChart = new Chart(ctxBarChart, {
type: 'horizontalBar',
data: barChartData,
options: optionsBar
})
Which means that priceBarChart.defaults.global.defaultFont = 'Georgia' will 'dive' into the variable priceBarChart, go into its default properties, change one of its global properties and that one is defaultFont, exactly what you want.
But when you apply this code, you basically create the chart with the wrong font and then change it again, which is a bit ugly. What you need to do is tell the chart what the font is beforehand.
You do this by merging your font declaration with the rest of the options, just like how you did it with your variables barChartData and optionsBar.
After you've created barChartData and optionsBar, create another variable with the name, let's say, defaultOptions, like so:
var defaultOptions = {
global: {
defaultFont: 'Georgia'
}
}
You can see that it has the same structure. You go into the global options, and change its defaultFont property. Now you need to apply it to the created chart at the moment it is created, like so:
var priceBarChart = new Chart(ctxBarChart, {
type: 'horizontalBar',
data: barChartData,
options: optionsBar,
defaults: defaultOptions //This part has been added
})
This method of overwriting options is what is being used in almost every JavaScript plugin. When you create a new instance, the plugin copies an object that contains objects that contain objects and so forth. But these objects can be modified with additional options, like barChartData, optionsBar and defaultOptions.
I hope this helps!

Related

chart.js - horizontalBar stacked chart with xaxis as dates

I am looking to create a bar chart but have had a hell of a time trying to find what I need through chart.js 2.1
Goal is to have a chart that looks like this:
sample image
So far I have been unsuccessful getting the xAxis to reflect dates.
Here's the story:
yAxis are vendor groups that have stacking due dates (the dates may/may not match up with another vendor group). Each stack has a numeric value as well, but this does not affect the layout of the chart, just an overlay of data.
xAxis are all the due dates, starting with the current date and moving on.
Any assistance or jfiddle examples would be EXTREMELY helpful!
Here's what I have today: https://jsfiddle.net/npk3xdb0/
HTML:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/moment#latest/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.0/Chart.min.js"></script>
<canvas id="bar-chart-horizontal" width="200" height="50"></canvas>
JAVASCRIPT:
new Chart(document.getElementById("bar-chart-horizontal"), {
type: "horizontalBar",
data: {
labels: ['V1','V2','V3'],
datasets: [{ data: [50, 60, 75], backgroundColor: "#8C453E"},{ data: [50, 70, 85], backgroundColor: "#684796"},{ data: [50, 53, 111], backgroundColor: "#427780"},{ data: [19, , ], backgroundColor: "#599647"}]
},
options: {
tooltips: { enabled: false },
hover :{ animationDuration:0 },
scales: {
xAxes: [{
ticks: { beginAtZero:true, fontFamily: "'Open Sans Bold', sans-serif", fontSize:11 },
scaleLabel:{ display:false },
gridLines: { },
stacked: true
}],
yAxes: [{
gridLines: { display:false, color: "#fff", zeroLineColor: "#fff", zeroLineWidth: 0 },
ticks: { fontFamily: "'Open Sans Bold', sans-serif", fontSize:11 },
stacked: true
}]
},
legend:{ display:false },
animation: {
onComplete: function () {
var chartInstance = this.chart;
var ctx = chartInstance.ctx;
ctx.textAlign = "right";
ctx.font = "9px Open Sans";
ctx.fillStyle = "#fff";
Chart.helpers.each(this.data.datasets.forEach(function (dataset, i) {
var meta = chartInstance.controller.getDatasetMeta(i);
Chart.helpers.each(meta.data.forEach(function (bar, index) {
data = dataset.data[index];
//if(i==0){
// ctx.fillText(data, 20, bar._model.y+4);
//} else {
ctx.fillText(data, bar._model.x-3, bar._model.y+4);
//}
}),this)
}),this);
}
},
pointLabelFontFamily : "Quadon Extra Bold",
scaleFontFamily : "Quadon Extra Bold",
}
});

ChartJS Pie chart is too small on mobile

I am trying to make my ChartJS Pie chart responsive on mobile. All the labels and titles scale ok, but when it comes to the actual chart
it looks like this.
This is what I am aiming for it to look like.
I tried changing aspect ratios and responsiveness true/false values, but that didn't do anything.
Does anyone know what could be the issue here?
JS:
Chart.defaults.global.defaultFontFamily = "Archivo";
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'pie',
responsive: true,
maintainAspectRatio: false,
data: {
labels: ["Total Working Time", "Time Wasted On Scheduling"],
datasets: [{
data: [40-appendHours, 40-(40-appendHours)],
backgroundColor: [
'#73D500',
'#FD4D7A',
],
borderColor: [
'#73D500',
'#73D500'
],
borderWidth: 5
}]
},
options: {
events: [],
legend: {
labels: {
fontColor: '#44566c',
fontSize: 15,
fontStyle: "normal",
fontFamily: "'Archivo', sans-serif"
},
},
title: {
display: true,
text: 'Hours wasted by 1 person on scheduling per week',
fontSize: 15,
position: 'bottom',
fontColor: '#44566c',
fontFamily: "'Archivo', sans-serif"
},
}
});
}); ///End
HTML:
<div class="col-md-6 order-lg-2 order-md-2 order-sm-2 order-col-2 resultsBox">
<div class="Task">
<h3 class="resultsFont">Results</h3>
<p class="descriptionFont" id="savings"></p>
<hr />
<canvas id="myChart" class="descriptionFont"></canvas>
</div>
</div>

Legend option destroys pie chart in Chart.js

My Chart.js pie is working fine, but when I add the legend option, it disappears, much to my dismay. Other options like title and animation work pretty well, only the legend options ruins the pie. I have looked at the code thoroughly, but can't figure out what I'm not doing right. Below is my code:
if ( $('#broadsheet_piechart_sample').length ) {
var ctx = document.getElementById("broadsheet_piechart_sample");
var data = {
datasets: [{
data: [10, 20, 30, 40, 50],
backgroundColor: ['#455C73', '#9B59B6', '#BDC3C7', '#26B99A', '#3498DB'],
}],
labels: ['Dark Gray', 'Purple', 'Gray', 'Green', 'Blue']
};
//options
var options = {
title: {
display: true,
position: "top",
text: "Test Pie Chart",
fontSize: 18,
fontColor: "#111"
},
animation: {
duration: 0
},
legend: {
display: true,
position: "bottom",
labels: {
fontColor: "#333",
fontSize: 16
}
}
};
var broadsheet_piechart_sample = new Chart(ctx, {
data: data,
type: 'pie',
options: options
});
}
You are may using an old version which can cause this issue.
Please upgrade to the latest CharJs version (2.7.3).
Here is what I did for example : example Just exactly what you did.

Chart js. How to change font styles for "labels" array?

I got a chart from Chart JS library.
Screenshot
var ctx = document.getElementById("myChart");
var data = {
labels: ["HTML", "CSS", "JavaScript", "jQuery", "Bootstrap", "Gulp", "PHP", 'SQL', 'Git'],
datasets: [
{
defaultFontColor: 'red',
backgroundColor: "rgba(0,255,255,.4)",
borderColor: "rgba(0,255,255,.4)",
pointBackgroundColor: "red",
pointBorderColor: "#fff",
lineTension: 0,
pointHoverBackgroundColor: "#fff",
pointHoverBorderColor: "rgba(179,181,198,1)",
data: [95, 99, 60, 91, 36, 95, 40, 95, 95]
}
]
};
var myRadarChart = new Chart(ctx, {
type: 'radar',
data: data,
options: {
responsive: true,
scale: {
reverse: false,
ticks: {
// defaultFontSize: true
}
}
}
});
I need to change font styles for underlined labels. I've dug over documentation and i tried all what i could. Even global font settings didn't change label styles, though it worked for the rest of other text. Have you met such a problem? Thanks.
It's well hidden, but you can find this under "Point Label Options"
http://www.chartjs.org/docs/#scales-radial-linear-scale
here is a example:
https://jsfiddle.net/qvrt01jp/1/
options: {
scale: {
pointLabels :{
fontStyle: "bold",
}
}
}
global should also work if set it like this:
Chart.defaults.global.defaultFontStyle = 'italic'
To give an update for v3.5.1:
Like this for font weights:
Chart.defaults.font.weight = '600';
Or if you want to do it inside the options object:
options: {
plugins: {
legend: {
labels: {
font: {
style: 'italic',
weight: '600',
}
}
}
}
}
Documentation with more info: https://www.chartjs.org/docs/latest/general/fonts.html

Add a horizontal line to the chart

I have a requirement to have horizontal lines in Kendo Line Chart to denote maximum and minimum values as well as high limit and low limit.
Another solution would be to add plotbands.
Example:
<div id="chart"></div>
<script>
$("#chart").kendoChart({
valueAxis: {
plotBands: [
{ from: 89, to: 90, color: "red" }
]
}
});
</script>
Adding striplines or Horizontal Lines (Min/Max/Average) via Kendo-chart Render Event Handler
I wanted to add a complete solution here so it can be used for variety reasons.
Using kendo 2015.3.1111 version, IE11/10
I had the same challenge to add upper and lower limit lines similar to MS-Chart strip lines. Kendo 2015.3.1111 and prior versions don't support this feature.
My solution is
Add a stripline property to kendo-chart value-axis property
Use render event handler to draw lines provided by the stripline property per value axis
A value axis (y-axis) may have multiple striplines
Make sure have the following references in the <head>
<link href="http://kendo.cdn.telerik.com/2016.2.714/styles/kendo.common.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="http://kendo.cdn.telerik.com/2016.2.714/js/kendo.all.min.js"></script>
Here is the stripline property. I leave the implementation of level position up to you.
valueAxis: [{
name:..
labels:{..}
stripLine: [{
value: 78,
color: "blue",
borderwidth: "1px",
//"dot", "dash", "solid", "dashDot", "longDash", "longDashDot"
dashstyle: "dot",
label: "In Max",
labelposition: "",
labelfont: "12 sans-serif"
},
{
value: 70,
color: "blue",
borderwidth: "1px",
dashstyle: "dot",
label: "In Min",
labelposition: "",
labelfont: "12 sans-serif"
}]
}
Second Important point is the number of value axes (y-axes). Kendo-chart "value-axis" property has either the value axis or the array of value axes. Render event handler should figure out object versus array
render: function (e) {
if (e.sender.options.valueAxis.length) {
$.each(e.sender.options.valueAxis, function (i, value) {
drawStriptLine(e.sender, value);
});
}
else {
drawStriptLine(e.sender, e.sender.options.valueAxis);
}
}
You can see the drawStripline in the Code snippet below. Here are some notes about the code.
Make sure the axis names match
axis.slot is the data point. If you know how many data point you have, your data axis starts from 0 to your last data point number. Putting a higher number will return the last point. Otherwise line will be drawn from 0 to last point you specified in the end slot.
KendoChart property renderAs is optional, however canvas doesn't raise the render event handler, so use VML or SVG
Chrome (tested version Version 52.0.2743.116 m) doesn't support dotted and dashed lines yet (solid line only), IE11/10 supports all the dash styles
plotBands implementation is also demonstrated as an alternative to Render Event Handler
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
<link href="http://kendo.cdn.telerik.com/2016.2.714/styles/kendo.common.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="http://kendo.cdn.telerik.com/2016.2.714/js/kendo.all.min.js"></script>
<!--<link href="http://kendo.cdn.telerik.com/2015.3.1111/styles/kendo.common.min.css" rel="stylesheet" />-->
<!--<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>-->
<!--<script src="http://kendo.cdn.telerik.com/2015.3.1111/js/kendo.all.min.js"></script>-->
</head>
<body>
<div id="chart" />
<script>
var mPlotBands = [];
mPlotBands.push({
from: 60,
to: 61,
color: "red",
borderwidth: "3px",
borderstyle: "dashed",
label: "Min",
labelposition: ""
})
mPlotBands.push({
from: 95,
to: 94,
color: "red",
borderwidth: "3px",
borderstyle: "dashed",
label: "Max",
labelposition: ""
});
$("#chart").kendoChart({
renderAs: "VML", //"canvas", "SVG", "VML"
title: {
text: "Average In/Out Temperatures"
},
legend: {
position: "bottom"
},
seriesDefaults: {
type: "line"
},
series: [{
name: "In Temperature",
data: [74, 74, 76, 78, 74, 70],
axis: "intemperature"
}, {
name: "Out Temperature",
data: [45, 65, 75, 95, 80, 70],
axis: "outtemperature"
}],
categoryAxis: {
name: "CategoryAxis",
categories: ["May", "June", "July", "Aug", "Sep", "Oct"]
},
valueAxis: [{
name: "intemperature",
labels: {
format: "{0}F"
},
min: 50,
max: 110,
plotBands: [],
stripLine: [{
value: 78,
color: "blue",
borderwidth: "1px",
dashstyle: "dot", //"dot", "dash", "solid", "dashDot", "longDash", "longDashDot"
label: "In Max",
labelposition: "",
labelfont: "12 sans-serif"
}, {
value: 70,
color: "blue",
borderwidth: "1px",
dashstyle: "dot", //"dot", "dash", "solid", "dashDot", "longDash", "longDashDot"
label: "In Min",
labelposition: "",
labelfont: "12 sans-serif"
}]
}, {
name: "outtemperature",
labels: {
format: "{0}F"
},
plotBands: mPlotBands,
stripLine: [{
value: 75,
color: "green",
borderwidth: "3px",
dashstyle: "dot", //"dot", "dash", "solid", "dashDot", "longDash", "longDashDot"
label: "Out Avg",
labelposition: "",
labelfont: "italic 12 sans-serif"
}]
}],
render: function(e) {
if (e.sender.options.valueAxis.length) {
$.each(e.sender.options.valueAxis, function(i, value) {
drawStriptLine(e.sender, value);
});
} else {
drawStriptLine(e.sender, e.sender.options.valueAxis);
}
}
});
function drawStriptLine(chart, yaxis) {
var axis = chart.getAxis(yaxis.name);
var stripline;
$.each(yaxis.stripLine, function(i, stripline) {
// Locate value slot
var slot = axis.slot(stripline.value);
// Locate last category slot. Trying to get the last slot on the right given data x-axis plots
var categoryAxis = chart.getAxis("CategoryAxis");
var categorySlotBeg = categoryAxis.slot(0);
var categorySlotEnd = categoryAxis.slot(100000);
// Render a line element
var line = new kendo.drawing.Path({
stroke: {
color: stripline.color,
width: stripline.borderwidth,
dashType: stripline.dashstyle
}
});
line.moveTo([categorySlotBeg.origin.x, slot.origin.y]).lineTo([categorySlotEnd.origin.x, slot.origin.y]);
var labelPos = [categorySlotEnd.origin.x - 50, slot.origin.y - 20];
var label = new kendo.drawing.Text(stripline.label, labelPos, {
fill: {
color: stripline.color
},
font: stripline.labelfont
});
var group = new kendo.drawing.Group();
group.append(line, label);
chart.surface.draw(group);
});
}
</script>
</body>
</html>
Hope this helps.
References
http://docs.telerik.com/kendo-ui/controls/charts/how-to/custom-plot-bands
Simply add one more line series with the chart. This will create a hr line in chart. We will be able to manage the line position also.

Categories