JS import updated JSON file for use with ChartJS - javascript

I am trying to import and read from a JSON file that gets updated every few minutes by a different process. I need to loop through the values in this JSON files for use with ChartJS.org.
If I keep the JSON data local to the script in a var (var jsonfile={}) the chart works as expected.
What I am struggling to do is import the JSON file from outside the script (it is on the local web server under a different folder).
The JSON file looks exactly the same as data in the var below.
The below works as expected.
<div class="row">
<div class="col-4">
<div class="ca-comms-by-month">
</div>
<script>
var jsonfile = {
"comms_by_month": [
{
"name": "July",
"count": 2130
},
{
"name": "August",
"count": 890
},
{
"name": "September",
"count": 1654
},
{
"name": "October",
"count": 120
}
]
};
var labels = jsonfile.comms_by_month.map(function(e) {
return e.name;
});
var data = jsonfile.comms_by_month.map(function(e) {
return e.count;
});
function createConfig(details, data) {
return {
type: 'line',
data: {
labels: labels,
datasets: [{
label: 'Comms count by month',
steppedLine: details.steppedLine,
data: data,
borderColor: details.color,
fill: true,
}]
},
options: {
responsive: true,
title: {
display: false,
text: details.label,
},
tooltips: {
enabled:true, // Disable this for custom tool tips || http://www.chartjs.org/docs/latest/configuration/tooltip.html
mode: 'index',
intersect: false,
cornerRadius:0
},
hover: {
mode: 'nearest',
intersect: true
},
scales: {
xAxes: [{
display: true,
scaleLabel: {
display: true,
labelString: 'Month'
}
}],
yAxes: [{
display: true,
scaleLabel: {
display: true,
labelString: 'Count'
},
ticks: {
beginAtZero:true
}
}]
},
legend: {
display: false, // False to hide the legdend dataset tile
labels: {
fontColor: 'rgb(255, 99, 132)'
}
}
}
};
}
window.onload = function()
{
var container = document.querySelector('.ca-comms-by-month');
var steppedLineSettings = [{
steppedLine:false,
label: '',
color: window.chartColors.purple
}];
steppedLineSettings.forEach(function(details) {
var div = document.createElement('div');
div.classList.add('chart-container');
var canvas = document.createElement('canvas');
div.appendChild(canvas);
container.appendChild(div);
var ctx = canvas.getContext('2d');
var config = createConfig(details, data);
new Chart(ctx, config);
});
};
</script>
</div>
</div>
The below code will display some of the data in the updated JSON file based on the getElementById names but this is no good to me as I need the ChartJS to go and get the values.
<h1 class="toolsportal text-right">Temp</h1>
<p id="demo"></p>
<p id="demo1"></p>
<br /><br /><br /><br />
<script>
var jsonurl = 'http://mydevicename/portal/js/export_json/dash-comms-month.json';
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()
{
if (this.readyState == 4 && this.status == 200)
{
var jsonfile = JSON.parse(this.responseText);
document.getElementById("demo").innerHTML = jsonfile.comms_by_month[0].month;
document.getElementById("demo1").innerHTML = jsonfile.comms_by_month[0].name;
}
};
xmlhttp.open("GET", jsonurl, true);
xmlhttp.send();
</script>
What I can't put together is how I can get the values out of the updated JSON file using the below functions that happily go and get the data from the local jsonfile{} var.
var labels = jsonfile.comms_by_month.map(function(e){return e.name;});
var data = jsonfile.comms_by_month.map(function(e){return e.count;});
I am clearly missing something fundamental, any pointers would be great.
Thanks

I have answered my own question by properly looking into what XMLHttpRequest() & JSON.parse() does.
If someone is looking to hook a JSON file into https://www.chartjs.org/ charts then the below might help.
The JSON file
"comms_by_month":[
{
"name": "July",
"month":7,
"count":0
},
{
"name": "August",
"month":8,
"count":1652
},
{
"name": "September",
"month":9,
"count":600
},
{
"name": "October",
"month":10,
"count":0
},
{
"name": "November",
"month":11,
"count":0
},
{
"name": "December",
"month":12,
"count":0
}
]
Get the JSON file into a var
<script>
// Set the var for the json file located on the web server
var jsonFile_dash_comms_by_month = 'http://hostname/portal/js/export_json/dash-comms-by-month.json';
var request = new XMLHttpRequest();
request.open("GET",jsonFile_dash_comms_by_month,false);
request.send(null)
var jsonObj_dash_comms_by_month = JSON.parse(request.responseText);
</script>
A div where the chart will be displayed
<div class="ca-comms-by-month"></div>
Functions to get the labels and datasets into a var
<script>
var labels = jsonObj_dash_comms_by_month.comms_by_month.map(function(e) {
return e.name;
});
var data = jsonObj_dash_comms_by_month.comms_by_month.map(function(e) {
return e.count;
});
</script>
Function to create the CharJS config
See (http://www.chartjs.org/docs/latest/configuration/) for more about ChartJs config.
<script>
function createConfig(details, data) {
return {
type: 'line',
data: {
labels: labels,
datasets: [{
label: 'Comms count by month',
steppedLine: details.steppedLine,
data: data,
borderColor: details.color,
fill: true,
}]
},
options: {
responsive: true,
title: {
display: false,
text: details.label,
},
tooltips: {
enabled:true, // Disable this for custom tool tips || http://www.chartjs.org/docs/latest/configuration/tooltip.html
mode: 'index',
intersect: false,
cornerRadius:0
},
hover: {
mode: 'nearest',
intersect: true
},
scales: {
xAxes: [{
display: true,
scaleLabel: {
display: true,
labelString: 'Month'
}
}],
yAxes: [{
display: true,
scaleLabel: {
display: true,
labelString: 'Count'
},
ticks: {
beginAtZero:true
}
}]
},
legend: {
display: false, // False to hide the legdend dataset tile
labels: {
fontColor: 'rgb(255, 99, 132)'
}
}
}
};
}<script>
On load function to display the chart
<script>
window.onload = function()
{
var container = document.querySelector('.ca-comms-by-month');
var steppedLineSettings = [{
steppedLine:false,
label: '',
color: window.chartColors.purple
}];
steppedLineSettings.forEach(function(details) {
var div = document.createElement('div');
div.classList.add('chart-container');
var canvas = document.createElement('canvas');
div.appendChild(canvas);
container.appendChild(div);
var ctx = canvas.getContext('2d');
var config = createConfig(details, data);
new Chart(ctx, config);
});
};
</script>
This gave me the below chart
I would be keen to hear from anyone who can point out any improvements on the above. I am expecting to have 10+ charts on a dashboard type page.
Thanks
edwoli

Related

Chart JS custom message on tooltip, not x and y axis

I am displaying a bar chart that has 3 different pieces of information, (project name, number of days remaining, and the end date.) I am displaying the project name on one axis, and the number of days remaining determines the height of the bar. Currently, when I hover over a bar the tooltip displays the information already on the x and y axis. I want it to instead have the end date.
ie: project "b" will end in 2 days (August 4th), when I hover over the bar I want the tooltip to say "End date of 2022-08-04" instead of "b Work Days Remaining: 2"
My json of the data looks like this:
[{"po_num": "a", "days_rem": 10, "date_end": "2022-08-16"},
{"po_num": "b", "days_rem": 2, "date_end": "2022-08-04"},
{"po_num": "c", "days_rem": 6, "date_end": "2022-08-10"}]
Here is the link of the current graph.
https://i.stack.imgur.com/HefRz.png
Here is an MS paint rendering of what I am trying to do:
https://i.stack.imgur.com/GAT2I.png
The implementation code:
link = "{{{BASE_BACK_URL}}}";
$.getJSON(link, function (data) {
let po_names = [];
let days_rem = [];
for (let i = 0; i < data.length; i++) {
po_names.push(data[i]["po_num"]);
days_rem.push(data[i]["days_rem"]);
}
const ctx = document.getElementById('po-timeline-chart');
const myChart = new Chart(ctx, {
type: 'horizontalBar',
data: {
labels: po_names,
datasets: [{
label: 'Work Days Remaining',
data: days_rem,
backgroundColor: 'rgb(0, 89, 178)'
}],
},
options: {
legend: {
align: "end"
},
scales: {
xAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
});
Solution listed below:
$.getJSON(link, function (data) {
let po_names = [];
let days_rem = [];
for (let i = 0; i < data.length; i++) {
po_names.push(data[i]["po_num"]);
days_rem.push(data[i]["days_rem"]);
}
const ctx = document.getElementById("po-timeline-chart");
const myChart = new Chart(ctx, {
type: "horizontalBar",
data: {
labels: po_names,
datasets: [
{
label: "Work Days Remaining",
data: days_rem,
backgroundColor: "rgb(0, 89, 178)",
},
],
},
options: {
tooltips: {
enabled: true,
callbacks: {
// To change title in tooltip
title: (data) => {
return "This PO will run out on";
},
// To change label in tooltip
label: (data) => {
return date_end[data['index']];
},
},
},
legend: {
align: "end",
},
scales: {
xAxes: [
{
ticks: {
beginAtZero: true,
},
},
],
},
},
});
});

chart.js display a default chart with option value

so I'm generating charts with a database and displaying them with JSON script and it works fine but the chart only displays when I click an option value, what I'm trying to do now is set a default value option for when the website opens it displays a default chart if that makes sense, below is my chart.js code.
function renderHtmlChart(){
$(document).ready(function (){
var selection= document.getElementById('YEAR').value;
var link = "https://udon.ads.ntu.ac.uk/web/itec30151/N0773065/new/data.php?YEAR='"+selection+"'";
$.ajax({
url: link,
method: "GET",
success: function(data=this.responseText) {
console.log(data);
var Destination = [];
var Bookings = [];
for(var i in data) {
Destination.push(data[i].Destination);
Bookings.push(data[i].Bookings);
}
createChart(Destination,Bookings,selection)
},
error: function(data) {
console.log(data);
}
});
});
}
function createChart(Destination,Bookings,selection){
var universalOptions = {
maintainAspectRatio: true,
responsive: false,
title: {
display: true,
text: 'Top 5 Flight Bookings'
},
legend: {
display: true,
},
scales: {
yAxes: [{
ticks: {
beginAtZero: true,
},
scaleLabel: {
display: true,
labelString: 'Bookings'
}
}],
xAxes: [{
scaleLabel: {
display: true,
labelString: 'Destinations'
}
}],
}
}
var chartdata = {
labels: Destination,
datasets : [
{
label: selection,
data: Bookings,
backgroundColor: ["#3366cc","#dc3912","#ff9900","#109618","#990099"],
borderWidth: '1',
borderColour: 'grey',
hoverBorderColor: 'black',
fill: false,
pointRadius: 0,
}
]
};
//stop overlap
$('select').on('change',function(){
barGraph.destroy();
});
// this makes legend hidden
var update_caption = function(legend) {
labels[legend.text] = legend.hidden;
var selected = Object.keys(labels).filter(function(key) {
return labels[key];
});
};
//this creates new graph
var ctx = document.getElementById('myChart');
var barGraph = new Chart(ctx, {
type: 'bar',
data: chartdata,
options: universalOptions,
responsive: false,
});
}
hope you have latest version of jquery like:-
<script src="https://code.jquery.com/jquery-3.4.1.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"></script>
hope this will help
//create renderHtmlChart function
function renderHtmlChart()
{
var selection= document.getElementById('YEAR').value;
var link = "https://udon.ads.ntu.ac.uk/web/itec30151/N0773065/new/data.php?YEAR='"+selection+"'";
$.ajax({
url: link,
method: "GET",
success: function(data=this.responseText)
{
console.log(data);
var Destination = [];
var Bookings = [];
for(var i in data)
{
Destination.push(data[i].Destination);
Bookings.push(data[i].Bookings);
}
createChart(Destination,Bookings,selection)
},
error: function(data)
{
console.log(data);
}
});
}
//create createChart function
function createChart(Destination,Bookings,selection)
{
var universalOptions =
{
maintainAspectRatio: true,
responsive: false,
title:
{
display: true,
text: 'Top 5 Flight Bookings'
},
legend:
{
display: true,
},
scales:
{
yAxes: [{
ticks: {
beginAtZero: true,
},
scaleLabel: {
display: true,
labelString: 'Bookings'
}
}],
xAxes: [{
scaleLabel: {
display: true,
labelString: 'Destinations'
}
}],
}
}
var chartdata = {
labels: Destination,
datasets : [
{
label: selection,
data: Bookings,
backgroundColor: ["#3366cc","#dc3912","#ff9900","#109618","#990099"],
borderWidth: '1',
borderColour: 'grey',
hoverBorderColor: 'black',
fill: false,
pointRadius: 0,
}
]
};
// this makes legend hidden
var update_caption = function(legend) {
labels[legend.text] = legend.hidden;
var selected = Object.keys(labels).filter(function(key) {
return labels[key];
});
};
//this creates new graph
var ctx = document.getElementById('myChart');
var barGraph = new Chart(ctx, {
type: 'bar',
data: chartdata,
options: universalOptions,
responsive: false,
});
}
$(funtion(){
//onload call renderHtmlChart function
renderHtmlChart();
//on select input change call renderHtmlChart function
$('select').on('change',function(){
renderHtmlChart();
});
})

Chartjs X axis labels will not display

The documentation for time in ChartJs is extremely vague and gives little working examples so I'm struggling to get a time series working for temperature data recorded at a particular time. I can get the correct time format to appear in the tooltip, but it will not appear on the X axis.
Graph code:
<script>
var ctx = document.getElementById('myChart');
var data = {
labels: [],
datasets: [{
label: "Temperature Graph",
fill: false,
borderColor: '#3cba9f',
data: []
}]
}
const options = {
type: 'line',
data: data,
options: {
fill: false,
responsive: true,
scales: {
xAxes: [{
type: 'time',
time: {
unit: 'day',
stepSize: 1,
displayFormats: {
day: 'MMM D'
}
},
display: true,
scaleLabel: {
display: true,
labelString: "Date",
}
}],
yAxes: [{
ticks: {
beginAtZero: true,
},
display: true,
scaleLabel: {
display: true,
labelString: "Temperature",
}
}]
}
}
}
var chart = new Chart(ctx, options)
</script>
Data collection code:
window.onload = function load() {
getData();
}
var prevData = [];
var prevLabels = [];
function getData() {
var xhr = new XMLHttpRequest();
xhr.open('GET', encodeURI('http://localhostlocalhost/getTemp'));
xhr.onload = function() {
if (xhr.status === 200) {
var data = JSON.parse(xhr.responseText);
console.log(data);
var label = data.timestamp * 1000;
prevData.push(data.temperature);
prevLabels.push(label);
chart.data.datasets[0].data = prevData;
chart.data.labels = prevLabels;
chart.update();
}
else {
alert(xhr.status);
}
};
xhr.send();
setTimeout(getData, 10000);
}
Example xhr response:
{temperature: 17, humidity: 38, location: "location", timestamp: 1542824305}
The data is plotted to the graph and all works as expected, the time just does not appear on the X axis

Display multiple tags in the legend for a single data value in Chart.js

I have graph that I built with the Chart.js library :
Normally, Sshare is represented with two color, red and green. In the legend, however, Sshare displays with just the first color value, red.
How can I get both Sshare colors to show in the legend?
I tried searching for a solution in the Chart.js documentation, but could not find a way to edit the legend properties.
My code:
<script>
// chart colors //BLUE & RED & VERT
var colors = ['#007bff','#dc3545',"#008000"];
var colors_suggested =[];
var labels_in =[];
var mshare_value =[];
var svalues =[];
var data_work_in =[
{ "ID":12, "Les": "AB", "Name": " AB_12", "Mmin": 75, "Sshare": 29},
{ "ID":13, "Les": "BB", "Name": " BB_13", "Mmin": 26.8, "Sshare": 36}
];
for (var i = 0; i < data_work_in.length;i++)
{
labels_in.push(data_work_in[i].Name+";"+data_work_in[i].Mill);
mshare_value.push(data_work_in[i].Mmin);
svalues.push(data_work_in[i].Sshare);
if ( data_work_in[i].Sshare >= data_work_in[i].Mmin)
colors_suggested.push(colors[2]);
else {
colors_suggested.push(colors[1]);
}
}
var chBar = document.getElementById("chBar");
var chartData = {
// Label of Entity
labels: labels_in,
// Value of percent category RTI|| VSM ...
datasets: [{
label: 'Mmin',
data: mshare_value,
backgroundColor: colors[0]
},
{
label: 'Sshare',
data: svalues,
xAxisID:'xAxis1',
backgroundColor: colors_suggested
}]
};
if (chBar) {
// new graph
new Chart(chBar, {
type: 'bar',
data: chartData,
options: {
scales: {
xAxes:[
{
barPercentage: 0.9,
categoryPercentage: 0.7,
id:'xAxis1',
type:"category",
ticks:{
callback:function(label){
var sublabel_x = label.split(";")[0];
var label_p = label.split(";")[1];
return sublabel_x;
}
}
},
{
id:'xAxis2',
type:"category",
gridLines: {
drawOnChartArea: false, // only want the grid lines for one axis to show up
},
ticks:{
callback:function(label){
var sublabel_x = label.split(";")[0];
var label_p = label.split(";")[1];
return label_p;
}
}
}],
yAxes: [{
ticks: {
beginAtZero: false
},
scaleLabel: {
display: true,
labelString: '%'
}
}]
},
legend: {
display: true,
legendText : ['Mmin','Sshare']
}
}
});
}
</script>

ChartJS New Lines '\n' in X axis Labels or Displaying More Information Around Chart or Tooltip with ChartJS V2

I'm using chart.js (V2) to try to build a bar chart that has more information available to user without having to hover over or click anywhere. I've provided two examples of how I hope to edit my chart.
Two edited versions of what I hope to achieve
As can be seen, I hope to place (somewhere), some extra information outside of the labels. I had hope that by adding '\n' to the labels I might have been able to get what I was looking for similar to option A.
Some edited code is provided blow:
var barChartData = {
labels: playerNames,
datasets: [{
label: 'Actual Score/Hour',
backgroundColor: "rgba(0, 128, 0,0.5)",
data: playerScores
}, {
label: 'Expected Score/Hour',
backgroundColor: "rgba(255,0,0,0.5)",
data: playerExpected
}]
};
function open_win(linktosite) {
window.open(linktosite)
}
canvas.onclick = function(evt){
var activePoints = myBar.getElementsAtEvent(evt);
console.log(activePoints);
linktosite = 'https://www.mytestsite.com/' + activePoints[1]['_model']['label'];
open_win(linktosite);
};
window.onload = function() {
var ctx = document.getElementById("canvas").getContext("2d");
window.myBar = new Chart(ctx, {
type: 'bar',
data: barChartData,
options: {
title:{
display:true,
text:"Player Expected and Actual Score per Hour"
},
tooltips: {
mode: 'label'
},
responsive: true,
scales: {
xAxes: [{
stacked: false,
}],
yAxes: [{
stacked: false
}]
},
animation: {
onComplete: function () {
var ctx = this.chart.ctx;
ctx.textAlign = "center";
Chart.helpers.each(this.data.datasets.forEach(function (dataset) {
Chart.helpers.each(dataset.metaData.forEach(function (bar, index) {
// console.log("printing bar" + bar);
ctx.fillText(dataset.data[index], bar._model.x, bar._model.y - 10);
}),this)
}),this);
}
}
}
});
// Chart.helpers.each(myBar.getDatasetMeta(0).data, function(rectangle, index) {
// rectangle.draw = function() {
// myBar.chart.ctx.setLineDash([5, 5]);
// Chart.elements.Rectangle.prototype.draw.apply(this, arguments);
// }
// }, null);
};
At this point I'd be satisfied with having the extradata anywhere on the bar. Any help would be appreciated. Thanks~
Chart.js v2.1.5 allows for multi-line labels using nested arrays (v2.5.0 fixes it for radar graphs):
...
data: {
labels: [["Jake", "Active: 2 hrs", "Score: 1", "Expected: 127", "Attempts: 4"],
["Matt", "Active: 2 hrs", "Score: 4", "Expected: 36", "Attempts: 4"]],
...
However, this does mean that you will have to pre-calculate the label values.
var config = {
type: 'line',
data: {
labels: [["January","First Month","Jellyfish","30 of them"], ["February","Second Month","Foxes","20 of them"], ["March","Third Month","Mosquitoes","None of them"], "April", "May", "June", "July"],
datasets: [{
label: "My First dataset",
data: [65, 40, 80, 81, 56, 85, 45],
backgroundColor: "rgba(255,99,132,0.2)",
}, {
label: "My Second dataset",
data: [40, 80, 21, 56, 85, 45, 65],
backgroundColor: "rgba(99,255,132,0.2)",
}]
},
scales : {
xAxes : [{
gridLines : {
display : false,
lineWidth: 1,
zeroLineWidth: 1,
zeroLineColor: '#666666',
drawTicks: false
},
ticks: {
display:true,
stepSize: 0,
min: 0,
autoSkip: false,
fontSize: 11,
padding: 12
}
}],
yAxes: [{
ticks: {
padding: 5
},
gridLines : {
display : true,
lineWidth: 1,
zeroLineWidth: 2,
zeroLineColor: '#666666'
}
}]
},
spanGaps: true,
responsive: true,
maintainAspectRatio: true
};
var ctx = document.getElementById("myChart").getContext("2d");
new Chart(ctx, config);
<div class="myChart">
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.bundle.js"></script>
<canvas id="myChart"></canvas>
</div>
If a label is an array as opposed to a string i.e. [["June","2015"], "July"] then each element is treated as a separate line. The appropriate calculations are made to determine the correct height and width, and rotation is still supported.
charJS version 2.7.2 used
this also works in https://github.com/jtblin/angular-chart.js
If you are using Chart.js v2.7.1, the above solution might not work.
The solution that actually worked for us was adding a small plugin right in the data and options level:
const config = {
type: 'bar',
data: {
// ...
},
options: {
// ...
},
plugins: [{
beforeInit: function (chart) {
chart.data.labels.forEach(function (label, index, labelsArr) {
if (/\n/.test(label)) {
labelsArr[index] = label.split(/\n/)
}
})
}
}]
};
A full description of how to fix this issue can be found here.
With Chart.js v2.1, you can write a chart plugin to do this
Preview
Script
Chart.pluginService.register({
beforeInit: function (chart) {
var hasWrappedTicks = chart.config.data.labels.some(function (label) {
return label.indexOf('\n') !== -1;
});
if (hasWrappedTicks) {
// figure out how many lines we need - use fontsize as the height of one line
var tickFontSize = Chart.helpers.getValueOrDefault(chart.options.scales.xAxes[0].ticks.fontSize, Chart.defaults.global.defaultFontSize);
var maxLines = chart.config.data.labels.reduce(function (maxLines, label) {
return Math.max(maxLines, label.split('\n').length);
}, 0);
var height = (tickFontSize + 2) * maxLines + (chart.options.scales.xAxes[0].ticks.padding || 0);
// insert a dummy box at the bottom - to reserve space for the labels
Chart.layoutService.addBox(chart, {
draw: Chart.helpers.noop,
isHorizontal: function () {
return true;
},
update: function () {
return {
height: this.height
};
},
height: height,
options: {
position: 'bottom',
fullWidth: 1,
}
});
// turn off x axis ticks since we are managing it ourselves
chart.options = Chart.helpers.configMerge(chart.options, {
scales: {
xAxes: [{
ticks: {
display: false,
// set the fontSize to 0 so that extra labels are not forced on the right side
fontSize: 0
}
}]
}
});
chart.hasWrappedTicks = {
tickFontSize: tickFontSize
};
}
},
afterDraw: function (chart) {
if (chart.hasWrappedTicks) {
// draw the labels and we are done!
chart.chart.ctx.save();
var tickFontSize = chart.hasWrappedTicks.tickFontSize;
var tickFontStyle = Chart.helpers.getValueOrDefault(chart.options.scales.xAxes[0].ticks.fontStyle, Chart.defaults.global.defaultFontStyle);
var tickFontFamily = Chart.helpers.getValueOrDefault(chart.options.scales.xAxes[0].ticks.fontFamily, Chart.defaults.global.defaultFontFamily);
var tickLabelFont = Chart.helpers.fontString(tickFontSize, tickFontStyle, tickFontFamily);
chart.chart.ctx.font = tickLabelFont;
chart.chart.ctx.textAlign = 'center';
var tickFontColor = Chart.helpers.getValueOrDefault(chart.options.scales.xAxes[0].fontColor, Chart.defaults.global.defaultFontColor);
chart.chart.ctx.fillStyle = tickFontColor;
var meta = chart.getDatasetMeta(0);
var xScale = chart.scales[meta.xAxisID];
var yScale = chart.scales[meta.yAxisID];
chart.config.data.labels.forEach(function (label, i) {
label.split('\n').forEach(function (line, j) {
chart.chart.ctx.fillText(line, xScale.getPixelForTick(i + 0.5), (chart.options.scales.xAxes[0].ticks.padding || 0) + yScale.getPixelForValue(yScale.min) +
// move j lines down
j * (chart.hasWrappedTicks.tickFontSize + 2));
});
});
chart.chart.ctx.restore();
}
}
});
and then
...
data: {
labels: ["January\nFirst Month\nJellyfish\n30 of them", "February\nSecond Month\nFoxes\n20 of them", "March\nThird Month\nMosquitoes\nNone of them", "April", "May", "June", "July"],
...
Note - we assume that the maximum content of one line will fit between the ticks (i.e. that no rotation logic is needed. I'm sure it's possible to incorporate rotation logic too, but it would be a tad more complicated)
You should format the tooltips to not show the x axis label, or format it to show a shorter version of the label.
Fiddle - http://jsfiddle.net/m0q03wpy/

Categories

Resources