Chart JS custom tooltip option? - javascript

I am trying to build chart using Chart.Js. This chart.js has default option for tooltip, I want to make customized tooltip option. Is there a way to make it possible?
Here is my code
var chart = null;
barChart: function (data1, data2, data3, label) {
var data = {
labels: label,
datasets: [
{
fillColor: "rgba(220,220,220,0.5)",
strokeColor: "rgba(220,220,220,0.8)",
highlightFill: "rgba(220,220,220,0.75)",
highlightStroke: "rgba(220,220,220,1)",
data: data1
},
{
fillColor: "rgba(151,187,205,0.5)",
strokeColor: "rgba(151,187,205,0.8)",
highlightFill: "rgba(151,187,205,0.75)",
highlightStroke: "rgba(151,187,205,1)",
data: data2
},
{
fillColor: "rgba(0,255,0,0.3)",
strokeColor: "rgba(220,220,220,0.8)",
highlightFill: "rgba(220,220,220,0.75)",
highlightStroke: "rgba(0,255,0,0.3)",
data: data3
},
]
}
var cht = document.getElementById('exampleCanvas');
var ctx = cht.getContext('2d');
if (chart)
chart.destroy();
chart = new Chart(ctx).Bar(data);
}

Try this:
You can make changes globally using this code:
Chart.defaults.global = {
// Boolean - Determines whether to draw tooltips on the canvas or not
showTooltips: true,
// Array - Array of string names to attach tooltip events
tooltipEvents: ["mousemove", "touchstart", "touchmove"],
// String - Tooltip background colour
tooltipFillColor: "rgba(0,0,0,0.8)",
// String - Tooltip label font declaration for the scale label
tooltipFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",
// Number - Tooltip label font size in pixels
tooltipFontSize: 14,
// String - Tooltip font weight style
tooltipFontStyle: "normal",
// String - Tooltip label font colour
tooltipFontColor: "#fff",
// String - Tooltip title font declaration for the scale label
tooltipTitleFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",
// Number - Tooltip title font size in pixels
tooltipTitleFontSize: 14,
// String - Tooltip title font weight style
tooltipTitleFontStyle: "bold",
// String - Tooltip title font colour
tooltipTitleFontColor: "#fff",
// Number - pixel width of padding around tooltip text
tooltipYPadding: 6,
// Number - pixel width of padding around tooltip text
tooltipXPadding: 6,
// Number - Size of the caret on the tooltip
tooltipCaretSize: 8,
// Number - Pixel radius of the tooltip border
tooltipCornerRadius: 6,
// Number - Pixel offset from point x to tooltip edge
tooltipXOffset: 10,
// String - Template string for single tooltips
tooltipTemplate: "<%if (label){%><%=label%>: <%}%><%= value %>",
// String - Template string for single tooltips
multiTooltipTemplate: "<%= value %>",
// Function - Will fire on animation progression.
onAnimationProgress: function(){},
// Function - Will fire on animation completion.
onAnimationComplete: function(){}
}
Use this Link for reference

The new version of chart.js, version 2, is found here:
https://github.com/nnnick/Chart.js/releases
Version 2 adds tooltip callbacks:
Every tooltip callback (beforeTitle, title, afterTitle, etc..) accepts a string or an array. If an array is used, it will produce multiple lines. Tooltips now come with a lot more options for visual customization as well.
However, there is a fork of chart.js called chartNew.js, found here:
https://github.com/FVANCOP/ChartNew.js/
It adds several great enhancements to the venerable chart.js, including:
tooltip functions (when download/unzip, look in the Samples folder and look at annotateFunction.html. When hover over any point, you can do anything.)
passing an array of colors to a bar chart (instead of each bar in series having the same color)
putting text on the chart wherever you want it
many etceteras.
Note that chart.js has been greatly enhanced in version 2, but the new version is not fully backwards compatible (just changing to the v2 plugin broke my existing code) whereas chartNew.js will work with old code whilst extending capabilities.

I have used this, i've found it on stackoverflow, but i try hardly to find it again
<div id="chartjs-tooltip"></div>
var chartoptions =
{
customTooltips: function ( tooltip )
{
var tooltipEl = $( "#chartjs-tooltip" );
if ( !tooltip )
{
tooltipEl.css( {
opacity: 0
} );
return;
}
tooltipEl.removeClass( 'above below' );
tooltipEl.addClass( tooltip.yAlign );
// split out the label and value and make your own tooltip here
var parts = tooltip.text.split( ":" );
var innerHtml = '<span>' + parts[0].trim() + '</span> : <span><b>' + parts[1].trim() + '</b></span>';
tooltipEl.html( innerHtml );
tooltipEl.css( {
opacity: 1,
left: tooltip.chart.canvas.offsetLeft + tooltip.x + 'px',
top: tooltip.chart.canvas.offsetTop + tooltip.y + 'px',
fontFamily: tooltip.fontFamily,
fontSize: tooltip.fontSize,
fontStyle: tooltip.fontStyle
} );
}
}
Link to where i got it: Chart.js: changing tooltip template

You can check for tooltip css - http://www.chartjs.org/docs/#chart-configuration-tooltip-configuration
tooltips:
{
bodyFontColor: "#000000", //#000000
bodyFontSize: 50,
bodyFontStyle: "bold",
bodyFontColor: '#FFFFFF',
bodyFontFamily: "'Helvetica', 'Arial', sans-serif",
footerFontSize: 50,
callbacks: {
label: function(tooltipItem, data) {
var value = data.datasets[0].data[tooltipItem.index];
if(tooltipItem.index == 0) {
return "<?php echo $data1;?>";
}
else if(tooltipItem.index == 1) {
return "<?php echo $data2;?>";
}
else if(tooltipItem.index == 2) {
return "<?php echo $data3;?>";
}
else {
return "<?php echo $data4; ?>";
}
},
},
},

It is very simple when you know where to put the option.
The answer is to add the custom option when you create the chart :
chart = new Chart(ctx).Bar(data, {"options goes here"} );
After you pass the data variable with the data info you can add custom options, so for example you want to change the size of the Title of the tooltip and you also want to put a light grey color in the title of the tooltip you would do something like that:
chart = new Chart(ctx).Bar(data, {
//Option for title font size in pixels
tooltipTitleFontSize: 14,
//Option for tooltip title color
tooltipTitleFontColor: "#eee"
});
Another way you can do is to create the set of options as a variable for organisation purposes and to be able to reuse it.
// Create a set of relevant options for you chart
var myoptions = {
scaleShowGridLines : false,
responsive : true,
scaleFontSize: 12,
pointDotRadius : 4,
scaleFontStyle: 14,
scaleLabel: "<%= ' ' + value%> %",
}
//Create the Chart
chart = new Chart(ctx).Bar(data, myoptions);
I hope it is clear now
Regards

I found this page to be helpful:
https://github.com/nnnick/Chart.js/blob/master/samples/pie-customTooltips.html
He shows where and how to define the function for your custom tooltip, as well as an example of the styling.
I had to modify the code to match my needs, but this is a great example on how to implement the custom tooltip feature.
Some things to note that threw me off at first:
1) The id in the style rules need to be modified to match your tooltip div. (this is obvious, but I didn't catch it at first)
2) tooltip.text will follow the format you set for 'tooltipTemplate' in your options, or the default tooltipTemplate set in chart.js

may be this can help you
Chart.types.Line.extend({
name: "LineAlt",
initialize: function (data) {
Chart.types.Line.prototype.initialize.apply(this, arguments);
var xLabels = this.scale.xLabels
xLabels.forEach(function (label, i) {
if (i % 2 == 1)
xLabels[i] = label.substring(1, 4);
})
}
});
var data = {
labels: ["1/jan/08", "15/fab/08", "1/mar/08", "1/apr/08", "10/apr/08", "10/may/2008", "1/jun/2008"],
datasets: [{
label: "First dataset",
fillColor: "rgba(220,220,220,0.2)",
strokeColor: "rgba(220,20,20,1)",
pointColor: "rgba(220,20,20,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(220,220,220,1)",
data: [65, 59, 80, 81, 56, 55, 90]
}, {
label: "Third dataset",
fillColor: "rgba(151,187,205,0.2)",
strokeColor: "rgba(15,187,25,1)",
pointColor: "rgba(15,187,25,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(151,187,205,1)",
data: [38, 55, 50, 65, 35, 67, 54]
}]
};
var ctx = document.getElementById("myChart").getContext("2d");
var myChart = new Chart(ctx).LineAlt(data);
// Chart.js replaces the base inRange function for Line points with a function that checks only the x coordinate
// we replace it with the original inRange fucntion (one that checks both x and y coordinates)
myChart.datasets.forEach(function(dataset) {
dataset.points.forEach(function(point) {
point.inRange = Chart.Point.prototype.inRange;
});
});
// Chart.js shows a multiTooltip based on the index if it detects that there are more than one datasets
// we override it to show a single tooltip for the inRange element
myChart.showTooltip = function(ChartElements, forceRedraw) {
// this clears out the existing canvas - the actual Chart.js library code is a bit more optimized with checks for whether active points have changed, etc.
this.draw();
// draw tooltip for active elements (if there is one)
Chart.helpers.each(ChartElements, function(Element) {
var tooltipPosition = Element.tooltipPosition();
new Chart.Tooltip({
x: Math.round(tooltipPosition.x),
y: Math.round(tooltipPosition.y),
xPadding: this.options.tooltipXPadding,
yPadding: this.options.tooltipYPadding,
fillColor: this.options.tooltipFillColor,
textColor: this.options.tooltipFontColor,
fontFamily: this.options.tooltipFontFamily,
fontStyle: this.options.tooltipFontStyle,
fontSize: this.options.tooltipFontSize,
caretHeight: this.options.tooltipCaretSize,
cornerRadius: this.options.tooltipCornerRadius,
text: Chart.helpers.template(this.options.tooltipTemplate, Element),
chart: this.chart,
custom: this.options.customTooltips
}).draw();
}, this);
};
http://jsfiddle.net/6cgo4opg/747/

Related

Highcharts - overlapping values with the x-Axis

I am trying to create a line graph, wherein if all the values for the particular series is zero then, I want the line to be drawn on the bottom over the x-axis line. But it seems like the line of the x-axis takes the preference than the series line. Is there any way to change that?
Below is my configuration:
xAxis: {
type: "datetime",
tickmarkPlacement: "on",
lineWidth: 10,
lineColor: 'red',
},
yAxis: {
min: 0,
minRange : 0.1,
title: {
text: ""
}
},
plotOptions: {
line: {
softThreshold: false
}
},
Example:
http://jsfiddle.net/shivajyothibalavikas/twxs7mL2/3
In the above example the axis line color is red and series line color is black. but red takes the preference. I want the black line to take the preference while displaying
It is not possible to move a series line above an axis line by options in Highcharts API. As a solution, you can use the Highcharts.SVGRenderer class and draw a custom line at the chart bottom.
chart: {
...,
events: {
render: function() {
const chart = this;
const x1 = chart.plotLeft;
const x2 = x1 + chart.plotWidth;
const y = chart.plotTop + chart.plotHeight;
if (!chart.customLine) {
chart.customLine = chart.renderer
.path().attr({
stroke: 'red',
'stroke-width': 10
}).add();
}
chart.customLine.attr({
d: ['M', x1, y, 'L', x2, y]
});
}
}
}
Live demo: http://jsfiddle.net/BlackLabel/70d6sg2o/
API Reference: https://api.highcharts.com/class-reference/Highcharts.SVGRenderer

Making the labels responsive in chart js

I'm having a hard time making the labels in the y-axis responsive.I want the labels to move to multiple lines and have responsive font sizes when the space is not enough.I'm using the chart.js datalabels library for labelling on top of horizontalBar Graph.Also the labels are getting hidden due to the outer chart container.
var chart = new Chart('ctx', {
type: 'horizontalBar',
data: {
labels: ["Something something something", "blah blah..", "blah blah..","Something something something"],
datasets: [{
data: [6, 87, 56,25,100,65],
backgroundColor: "#4082c4"
}]
},
options:{
responsive: true,
maintainAspectRatio: false,
plugins: {
datalabels: {
color: 'black',
anchor: "end",
align: "right",
offset: 20,
display: function (context) {
return context.dataset.data[context.dataIndex];
},
font: {
weight: 'bold',
size: 26
},
formatter: Math.round
}
},
legend: {
"display": false
},
tooltips: {
"enabled": false
},
scales: {
yAxes: [{
barPercentage: 1.0,
gridLines: {
display: false
},
ticks: {
fontSize: 20,
beginAtZero: true,
}
}],
xAxes: [{
gridLines: {
display: false
},
ticks: {
min: 0,
max: 100,
stepSize: 20
}
}]
}
}
})
The numbers in the right side of the bar also gets clipped of.I want the chart to be at the center horizontally.In the browser the chart looks like this-
Link to the fiddle:-https://jsfiddle.net/24wdpfxL/
You can do this, but it's a bit hack-y.
First the data labels. In the datalabels config section, you can try something like:
/* Adjust data label font size according to chart size */
font: function(context) {
var width = context.chart.width;
var size = Math.round(width / 32);
return {
weight: 'bold',
size: size
};
}
Change the size calculation as necessary.
For the y-axis labels, there's an answer here, however apparently since Chart.js 2.7.0, the line:
c.scales['y-axis-0'].options.ticks.fontSize
..should be changed to:
c.scales['y-axis-0'].options.ticks.minor.fontSize
(ref)
So to scale the y-axis labels font size according to chart height, it might look like:
plugins: [{
/* Adjust axis labelling font size according to chart size */
beforeDraw: function(c) {
var chartHeight = c.chart.height;
var size = chartHeight * 5 / 100;
c.scales['y-axis-0'].options.ticks.minor.fontSize = size;
}
}]
Note: This requires "maintainAspectRatio:" to be set to "true".
There's still one problem however, and that's that the part of the chart containing the y-axis labels will remain at the same pixel width even when resized.
We need to also resize this area to keep it at a constant % of the overall chart width, e.g. 40%, instead of a fixed pixel width (added to yAxes config section):
/* Keep y-axis width proportional to overall chart width */
afterFit: function(scale) {
var chartWidth = scale.chart.width;
var new_width=chartWidth*0.4;
scale.width = new_width;
}
(You might not notice this as a problem with your original example, since there is a oversized line that seems to cause the y-axis width to keep expanding when the window is enlarged. But when the labels don't overflow, then the width stays constant unless the above is used.)
Complete jsFiddle: https://jsfiddle.net/0kxt25v3/2/
(fullscreen)
I'm not sure about wrapping labels on to the next line, you might just need to pre-process the labels to limit the maximum number of characters per label.
I also haven't attempted to scale the x-axis label font sizes, but it should be easy enough to add it in to the "beforeDraw:" section.
If you're using chartjs-plugin-datalabels; here's how i was able to make the labels responsive. Considering the chart may have variable width and height, we can get the average of both (height and width) and calculate the font size. I am also setting the max font size limit to 12.
datalabels: {
font: function (context) {
var avgSize = Math.round((context.chart.height + context.chart.width) / 2);
var size = Math.round(avgSize / 32);
size = size > 12 ? 12 : size; // setting max limit to 12
return {
size: size,
weight: 'bold'
};
},
}
I ran into the clipping problem myself recently and fixed this by setting a suggestedMax value that was wider than the largest value in my dataset.

Using Chartist.js how do you change the color of the stroke for a donut chart?

Hello I am trying to create the following donut chart using Chartist.js:
GOAL CHART
This is what the chart looks like currently:
Chartist.js Donut Chart
I am trying to find where or how I can change the colors of this chart to match the 1st donut chart. The red and pink seem to be the defaults. I haven't been able to find any documentation of how to accomplish this goal. I would also like to customize the size of the stroke and the size of the chart itself. Any help is greatly appreciated!
Current code:
// ** START CHARTIST DONUT CHART ** //
var chart = new Chartist.Pie('.ct-chart', {
series: [70, 30],
labels: [1, 2]
}, {
donut: true,
showLabel: false
});
chart.on('draw', function(data) {
if(data.type === 'slice') {
// Get the total path length in order to use for dash array animation
var pathLength = data.element._node.getTotalLength();
// Set a dasharray that matches the path length as prerequisite to animate dashoffset
data.element.attr({
'stroke-dasharray': pathLength + 'px ' + pathLength + 'px'
});
// Create animation definition while also assigning an ID to the animation for later sync usage
var animationDefinition = {
'stroke-dashoffset': {
id: 'anim' + data.index,
dur: 1000,
from: -pathLength + 'px',
to: '0px',
easing: Chartist.Svg.Easing.easeOutQuint,
// We need to use `fill: 'freeze'` otherwise our animation will fall back to initial (not visible)
fill: 'freeze'
}
};
// If this was not the first slice, we need to time the animation so that it uses the end sync event of the previous animation
if(data.index !== 0) {
animationDefinition['stroke-dashoffset'].begin = 'anim' + (data.index - 1) + '.end';
}
// We need to set an initial value before the animation starts as we are not in guided mode which would do that for us
data.element.attr({
'stroke-dashoffset': -pathLength + 'px'
});
// We can't use guided mode as the animations need to rely on setting begin manually
// See http://gionkunz.github.io/chartist-js/api-documentation.html#chartistsvg-function-animate
data.element.animate(animationDefinition, false);
}
});
// ** END CHARTIST DONUT CHART ** //
HTML:
<div class="ct-chart ct-perfect-fourth"></div>
So I figured it out...
I had to go into css and override the defaults. I had to make sure that the css file was loaded after the cdn for Chartist. Then just set width and height of ct-chart.
.ct-series-a .ct-bar, .ct-series-a .ct-line, .ct-series-a .ct-point, .ct-series-a .ct-slice-donut {
stroke: #0CC162;
}
.ct-series-b .ct-bar, .ct-series-b .ct-line, .ct-series-b .ct-point, .ct-series-b .ct-slice-donut {
stroke: #BBBBBB;
}
.ct-chart {
margin: auto;
width: 300px;
height: 300px;
}
Then I had to add donutWidth key to the chart object to set the stroke width:
var chart = new Chartist.Pie('.ct-chart', {
series: [7, 3],
labels: [1, 2]
}, {
donut: true,
donutWidth: 42,
showLabel: false
});
A little later here, but you can provide class names to the data series to allow you to change the colors on each graph independently:
From the docs:
The series property can also be an array of value objects that contain
a value property and a className property to override the CSS class
name for the series group.
Instead of:
series: [70, 30]
Do this:
series: [{value: 70, className: 'foo'}, {value: 30, className: 'bar'}]
and then you can style however you'd like with the stroke css property
Chartist relies on modifying CSS to control the colors, sizes, etc. of the charts.
I'd suggest having a look at the documentation here to learn lots of cool tips and tricks: https://gionkunz.github.io/chartist-js/getting-started.html
But to your specific question, here's an except from the above link that tells you how to control the donut chart:
/* Donut charts get built from Pie charts but with a fundamentally difference in the drawing approach. The donut is drawn using arc strokes for maximum freedom in styling */
.ct-series-a .ct-slice-donut {
/* give the donut slice a custom colour */
stroke: blue;
/* customize stroke width of the donut slices in CSS. Note that this property is already set in JavaScript and label positioning also relies on this. In the right situation though it can be very useful to style this property. You need to use !important to override the style attribute */
stroke-width: 5px !important;
/* create modern looking rounded donut charts */
stroke-linecap: round;
}
I've managed to change the stroke color by overriding this class. You can change ct-series-b to which bar graph you change to change color (ct-series-a, ct-series-b and etc).
<html>
<head>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/chartist/0.10.1/chartist.min.css" />
<style>
.ct-series-b .ct-bar, .ct-series-b .ct-line, .ct-series-b .ct-point, .ct-series-b .ct-slice-donut {
stroke: goldenrod;
}
</style>
</head>
<body>
<div class="ct-chart ct-perfect-fourth"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chartist/0.10.1/chartist.min.js"></script>
<script>
window.onload = function() {
var data = {
labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
series: [
[5, 4, 3, 7, 5, 10, 3, 4, 8, 10, 6, 8],
[3, 2, 9, 5, 4, 6, 4, 6, 7, 8, 7, 4]
]
};
var options = {
seriesBarDistance: 10
};
var responsiveOptions = [
['screen and (max-width: 640px)', {
seriesBarDistance: 5,
axisX: {
labelInterpolationFnc: function (value) {
return value[0];
}
}
}]
];
new Chartist.Bar('.ct-chart', data, options, responsiveOptions);
}
</script>
</body>
</html>
What I did to make it work is the following. I am using a bar chart, but I guess it is the same for all graphs.
my css
.ct-chart .ct-series.stroke-green .ct-bar {
stroke: green;
}
.ct-chart .ct-series.stroke-yellow .ct-bar {
stroke: rgba(255, 167, 38, 0.8);
}
.ct-chart .ct-series.stroke-red .ct-bar {
stroke: rgba(230, 20, 20, 0.8);
}
chart conf
{
labels: ['Jan', 'Feb'],
series: [
{className:"stroke-green", meta:"OK", data: [12,23] },
{className:"stroke-yellow", meta:"Rest", data: [34,34]},
{className:"stroke-red", meta: "NOK", data: [2, 5] },
]
}
This code worked for me to change the color of the stroke:
// Prepare chart params
var chartColors = ['orange'];
var chartWidth = 9;
var percent = 77;
var arc = percent ? 360 * percent / 100 : 0;
// Create chart
var chart = new Chartist.Pie('.my-donut', {
series: [arc],
labels: [percent + '%'],
}, {
donut: true,
donutWidth: chartWidth,
startAngle: 0,
total: 360,
});
// Set chart color
chart.on('draw', function(data) {
if(data.type === 'slice') {
if (chartColors[data.index]) {
data.element._node.setAttribute('style','stroke: ' + chartColors[data.index] + '; stroke-width: ' + chartWidth + 'px');
}
}
});
Bar charts with a single serie - use nth-child(N):
.ct-bar:nth-child(1){
stroke: #379683 !important;
}
.ct-bar:nth-child(2){
stroke: #91A453 !important;
}
.ct-bar:nth-child(3){
stroke: #EFB200 !important;
}
The answers above wont work for me since I'm dynamically excluding categories with 0 points. You can do it pragmatically though. You can directly modify the svg node. My charts use fill instead of stroke but the method should be the same. This worked for me in Chrome:
const data = {
series: [],
labels: []
};
const pieColors = [];
enrollment.CoverageLevelTotals.forEach(e => {
if (e.Total === 0) return;
data.series.push(e.Total);
data.labels.push(e.Total);
pieColors.push(colors[e.CoverageLevel]);
});
new Chartist.Pie(document.getElementById(canvasId), data,
{
width: '160px',
height: '160px',
donut: true,
donutWidth: 50,
donutSolid: true,
showLabel: (data.series.length > 1)
}).on('draw',function (data) {
if (data.type !== 'slice') return;
data.element._node.setAttribute('style','fill:' + pieColors[data.index]);
});
}

How to dynamically change point location with line in Chart.js?

I am using the line graph in Chart.js v1 stable, and I want to dynamically change the point location along with the ling thats attached to it, so like if I slide the point up using javascript, then the point attached to it moves too. Does anyone know how to do it?
Thanks
$(document).ready(function() {
var data = {
labels: ["Dec", "Jan", "Feb", "March", "April", "May", "June"],
datasets: [
{
label: "My Second dataset",
fillColor: "rgba(151,187,205,0.2)",
strokeColor: "#ed1b2e",
pointColor: "red",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(151,187,205,1)",
data: [-28, -48, -40, -19, -86, -27, -90]
}
]
};
// Get the context of the canvas element we want to select
var ctx = document.getElementById("myChart").getContext("2d");
var myLineChart = new Chart(ctx).Line(data, {
bezierCurve: false
});
setTimeout(function() {
var len = myLineChart.datasets[0].points.length;
myLineChart.datasets[0].points[len-1].fillColor = "blue";
myLineChart.datasets[0].points[len-1].y = 250; // <---- doesn't work, it moves but then slides back to initial location
myLineChart.update();
}, 5000);
var g = myLineChart.datasets[0];
Chart.defaults.global = {
// Boolean - Whether to animate the chart
animation: true,
// Number - Number of animation steps
animationSteps: 60,
// String - Animation easing effect
// Possible effects are:
// [easeInOutQuart, linear, easeOutBounce, easeInBack, easeInOutQuad,
// easeOutQuart, easeOutQuad, easeInOutBounce, easeOutSine, easeInOutCubic,
// easeInExpo, easeInOutBack, easeInCirc, easeInOutElastic, easeOutBack,
// easeInQuad, easeInOutExpo, easeInQuart, easeOutQuint, easeInOutCirc,
// easeInSine, easeOutExpo, easeOutCirc, easeOutCubic, easeInQuint,
// easeInElastic, easeInOutSine, easeInOutQuint, easeInBounce,
// easeOutElastic, easeInCubic]
animationEasing: "easeOutQuart",
// Boolean - If we should show the scale at all
showScale: true,
// Boolean - If we want to override with a hard coded scale
scaleOverride: false,
// ** Required if scaleOverride is true **
// Number - The number of steps in a hard coded scale
scaleSteps: null,
// Number - The value jump in the hard coded scale
scaleStepWidth: null,
// Number - The scale starting value
scaleStartValue: null,
// String - Colour of the scale line
scaleLineColor: "rgba(0,0,0,.1)",
// Number - Pixel width of the scale line
scaleLineWidth: 1,
// Boolean - Whether to show labels on the scale
scaleShowLabels: true,
// Interpolated JS string - can access value
scaleLabel: "<%=value%>",
// Boolean - Whether the scale should stick to integers, not floats even if drawing space is there
scaleIntegersOnly: true,
// Boolean - Whether the scale should start at zero, or an order of magnitude down from the lowest value
scaleBeginAtZero: false,
// String - Scale label font declaration for the scale label
scaleFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",
// Number - Scale label font size in pixels
scaleFontSize: 12,
// String - Scale label font weight style
scaleFontStyle: "normal",
// String - Scale label font colour
scaleFontColor: "#666",
// Boolean - whether or not the chart should be responsive and resize when the browser does.
responsive: true,
// Boolean - whether to maintain the starting aspect ratio or not when responsive, if set to false, will take up entire container
maintainAspectRatio: true,
// Boolean - Determines whether to draw tooltips on the canvas or not
showTooltips: true,
// Function - Determines whether to execute the customTooltips function instead of drawing the built in tooltips (See [Advanced - External Tooltips](#advanced-usage-custom-tooltips))
customTooltips: false,
// Array - Array of string names to attach tooltip events
tooltipEvents: ["mousemove", "touchstart", "touchmove"],
// String - Tooltip background colour
tooltipFillColor: "rgba(0,0,0,0.8)",
// String - Tooltip label font declaration for the scale label
tooltipFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",
// Number - Tooltip label font size in pixels
tooltipFontSize: 14,
// String - Tooltip font weight style
tooltipFontStyle: "normal",
// String - Tooltip label font colour
tooltipFontColor: "#fff",
// String - Tooltip title font declaration for the scale label
tooltipTitleFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",
// Number - Tooltip title font size in pixels
tooltipTitleFontSize: 14,
// String - Tooltip title font weight style
tooltipTitleFontStyle: "bold",
// String - Tooltip title font colour
tooltipTitleFontColor: "#fff",
// Number - pixel width of padding around tooltip text
tooltipYPadding: 6,
// Number - pixel width of padding around tooltip text
tooltipXPadding: 6,
// Number - Size of the caret on the tooltip
tooltipCaretSize: 8,
// Number - Pixel radius of the tooltip border
tooltipCornerRadius: 6,
// Number - Pixel offset from point x to tooltip edge
tooltipXOffset: 10,
// String - Template string for single tooltips
tooltipTemplate: "<%if (label){%><%=label%>: <%}%><%= value %>",
// String - Template string for multiple tooltips
multiTooltipTemplate: "<%= value %>",
// Function - Will fire on animation progression.
onAnimationProgress: function(){},
// Function - Will fire on animation completion.
onAnimationComplete: function(){}
}
});
Use .value instead of .y i.e.
myLineChart.datasets[0].points[len - 1].value = 250

Edit tooltips in ChartJS

I have some troubles with customization of chartjs tooltips.
var animationComplete = function () {
var self = this;
Chart.helpers.each(self.datasets[0].points, function (point, index) {
Chart.helpers.each(self.datasets, function (dataset) {
new Chart.MultiTooltip({
x: point.x,
y: dataset.points[index].y,
xPadding: self.options.tooltipXPadding,
yPadding: self.options.tooltipYPadding,
xOffset: self.options.tooltipXOffset,
//yOffset: self.options.tooltipYOffset,
fillColor: self.options.tooltipFillColor,
textColor: self.options.tooltipFontColor,
fontFamily: self.options.tooltipFontFamily,
fontStyle: self.options.tooltipFontStyle,
fontSize: self.options.tooltipFontSize,
titleTextColor: self.options.tooltipTitleFontColor,
titleFontFamily: self.options.tooltipTitleFontFamily,
titleFontStyle: self.options.tooltipTitleFontStyle,
titleFontSize: self.options.tooltipTitleFontSize,
cornerRadius: self.options.tooltipCornerRadius,
labels: [dataset.points[index].value],
legendColors: [{
fill: dataset.strokeColor,
stroke: dataset.strokeColor
}],
legendColorBackground: self.options.multiTooltipKeyBackground,
//title: point.label,
//title: false,
title: '',
chart: self.chart,
ctx: self.chart.ctx,
custom: self.options.customTooltips
}).draw()
});
self.chart.ctx.font = Chart.helpers.fontString(self.fontSize, self.fontStyle, self.fontFamily)
self.chart.ctx.textAlign = 'center';
self.chart.ctx.textBaseline = "middle";
self.chart.ctx.fillStyle = "#666";
self.chart.ctx.fillText(point.label, point.x, self.scale.startPoint);
});
};
var ctx = document.getElementById("weeksChart").getContext("2d");
window.weeksChart = new Chart(ctx).Line(dataWeeks, {
responsive: true,
pointDot: true,
datasetStrokeWidth: 0.5,
bezierCurve : false,
scaleSteps: 2,
scaleLabel: "<%=value + '°'%>",
//tooltipTemplate: "<%= value %>",
tooltipTemplate: "<%= value + '°'%>",
tooltipFillColor: "transparent",
tooltipFontColor: "#000",
tooltipFontSize: 14,
tooltipXOffset: -10,
//tooltipYOffset: -100,
//tooltipYOffset: 100,
tooltipYPadding: 0,
showTooltips: true,
scaleShowLabels: false,
scaleFontColor: "transparent",
onAnimationComplete: function () {
animationComplete.apply(this)
},
tooltipEvents: []
});
Is it possible:
to remove colored squares?;
to change fontColor of numbers, so on blue line numbers will have blue font, and on red line numbers will be red?;
to move numbers higher on Y-axis? (i'd tried to add/change lines 30,78,79 in my Fiddle, but nothing works);
to remove Titles from tooltips? (everything what is works for me right now is to set title: '', on line 49. Line 48 doesn't work);
to add ° symbol right after number? (I tried to make like this -> tooltipTemplate: "<%= value + '°'%>", but it doesn't work...)
Here is my Fiddle
1.to remove colored squares?;
2.to change fontColor of numbers, so on blue line numbers will have blue font, and on red line numbers will be red?;
4.to remove Titles from tooltips? (everything what is works for me right now is to set title: '', on line 49. Line 48 doesn't work);
5.to add ° symbol right after number? (I tried to make like this -> tooltipTemplate: "<%= value + '°'%>", but it doesn't work...)
All of these can be done by just switching from the MultiTooltip constructor to a (single series) Tooltip constructor (the single series tooltip doesn't have a colored square or a title) and adjusting the options textColor and text like so
new Chart.Tooltip({
x: point.x,
y: dataset.points[index].y,
xPadding: self.options.tooltipXPadding,
yPadding: self.options.tooltipYPadding,
fillColor: self.options.tooltipFillColor,
textColor: dataset.strokeColor,
fontFamily: self.options.tooltipFontFamily,
fontStyle: self.options.tooltipFontStyle,
fontSize: self.options.tooltipFontSize,
caretHeight: self.options.tooltipCaretSize,
cornerRadius: self.options.tooltipCornerRadius,
cornerRadius: self.options.tooltipCornerRadius,
text: dataset.points[index].value + '°',
chart: self.chart,
custom: self.options.customTooltips
}).draw()
3.to move numbers higher on Y-axis? (i'd tried to add/change lines 30,78,79 in my Fiddle, but nothing works);
I assume you mean the x axis labels that are on the top (I couldn't see lines 78 and 79 on your fiddle, and 30 seemed unrelated).
If it's a slight change you could do it easily by adjusting the y parameter in the line that writes out the label.
self.chart.ctx.fillText(point.label, point.x, self.scale.startPoint - 2);
However, if you want to move it up a lot further, you need to make some space on the top of the chart or the top of your labels will be clipped off. You can do this by extending the chart and overriding scale.startPoint in the draw function.
So
Chart.types.Line.extend({
name: "LineAlt",
draw: function (data) {
this.scale.startPoint = 25;
Chart.types.Line.prototype.draw.apply(this, arguments);
}
});
and then using LineAlt instead of Line
window.weeksChart = new Chart(ctx).LineAlt(dataWeeks, {
will allow you to do
self.chart.ctx.fillText(point.label, point.x, self.scale.startPoint - 12);
without clipping off the label
Fiddle - http://jsfiddle.net/kphmkL0e/

Categories

Resources