B. Clay Shannon B. Clay Shannon - 2 months ago 18
CSS Question

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

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";

Answer

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.