Using Chart.js, how do I avoid having tooltips overlap? - javascript

I am using Chart.js via Angular Char. I have displayed all the tooltips in order to download a chart with the information displayed by creating a plugin.
The tooltips overlap, there doesn't seem to be any logic to distribute them so that they don't. Is there a way to do this?
Some of the plugin code. This isn't important to my question. The 'beforeRender' function creates a new Chart.Tooltip for each item in the dataset and afterDraw renders them:
// turn on tooltips
chart.options.tooltips.enabled = true;
Chart.helpers.each(chart.pluginTooltips, function (tooltip) {
tooltip.initialize();
tooltip.update();
// we don't actually need this since we are not animating tooltips
tooltip.pivot();
tooltip.transition(easing).draw();
The chart:

You can achieve some overlap solution using these snippets:
tooltips: {
mode: 'index',
intersect: false,
yPadding: 2,
xPadding: 2,
caretSize: 0,
borderWidth: 0,
}

Related

When `sync` is enabled, hiding/showing dataset is also sync'ed?

Situation
I have multiple charts in my page that show different datasets.
I want to use chartjs-plugin-crosshair to be able to show vertical lines on hover.
I also want to sync the vertical lines so that I can the vertical on the same date.
Bug
Both of the above work, except I noticed a weird bug where enabling sync: {enabled: true} means hiding/showing a dataset of one chart hides/shows a dataset of another (even though they have different keys)
When I make sync: {enabled: false}, the weird bug stops, but then I lose the feature of syncing the vertical lines.
I looked through the code of the plugin but I don't see anything that changes the hidden property of datasets.
Plugin config
The plugin config is simple:
crosshair: {
...
sync: {
enabled: true, // enable trace line syncing with other charts
group, // chart group
suppressTooltips: false, // suppress tooltips when showing a synced tracer
},
zoom: {
enabled: false,
},
},
For confidentiality reasons I had to hide some info with red boxes. When I toggle a label on the first chart (top left) some of the labels of the others ones also get toggled. I never touch any of the labels of the remaining charts.
What gives?

How can I make the horizontal line in ChartJS end at a specific value?

I am using ChartJS alongside the ChartJs annotation plugin. The plugin allows users to draw lines on a chart.
I am trying to draw a horizontal line on my line chart that ends at a specific value instead of extending all of the way to the end of the chart.
Here is what the chart is supposed to look like, it is the red line labeled 'Peak':
The line should end at the largest value in the data array. However right now, the horizontal line extends all of the way to the end of the chart as you can see in the fiddle below.
Here is the code for the annotation:
annotation: {
drawTime: 'afterDatasetsDraw',
events: ['click'],
dblClickSpeed: 350,
annotations: [{
drawTime: 'afterDraw', // overrides annotation.drawTime if set
id: 'a-line-1', // optional
type: 'line',
mode: 'horizontal',
scaleID: 'y-axis-0',
value: '1300',
borderColor: 'red',
borderWidth: 2,
// Fires when the user clicks this annotation on the chart
// (be sure to enable the event in the events array below).
onClick: function(e) {
// `this` is bound to the annotation element
}
}]
Is it possible to limit the width of the line like this?
Here is the fiddle
ChartJS and ChartJS Annotation

Chart.js pie tooltip getting cut

I'm using Chart.js pie chart with tooltips which being cut for some reason.
Screenshot attached, didn't found any attribute/option to take care of it..
Is there anyway to take care of it?
Thanks!
This improper cutoff was raised as issue#622 in the Github repository for ChartJS.
This was determined to be a bug (evidently this bug hasn't yet been fixed)
https://github.com/nnnick/Chart.js/issues/622
In response to that issue, Robert Turrall has a solution which he says is a good workaround. Here is his proposed fix:
I'm sure that this is due to the fact that the tooltips are generated
within the confines of the canvas, making it difficult to fix.
I had the same issue on my doughnut chart and solved it by
implementing custom tooltips as per the example on the samples folder
- worked in conjunction with my existing tooltip fontsize and template settings in the chart initialisation code:
var myDoughnutChart = new Chart(donut).Doughnut(donutdata, {
tooltipFontSize: 10,
tooltipTemplate: "<%if (label){%><%=label%>: <%}%><%= value %>hrs",
percentageInnerCutout : 70
});
Check out samples/pie-customTooltips.html for the custom tooltip code.
Copy/paste and it worked straight away. Very happy!
Tooltip displayed well outside the bounds of the canvas:
PS: there's a line chart example too, which I'm guessing will work
fine with bar charts.
You can add internal padding to the chart. For instance in my case I had a cut of tooltips on the right.
options: {
responsive: true,
maintainAspectRatio: false,
cutoutPercentage: 60,
legend: {
display: false
},
animation: {
animateRotate: false
},
layout: {
padding: {
right: 40
}
}
}
I found a workaround for this. I have blank labels on my x axis, so I just added a label with several spaces in it for the last label entry. That caused ChartJS to leave enough space for the label to fit, which also leaves enough room for the tooltip to fit.
In addition, I have large circles for my data points and the last one on the right was getting clipped before. Adding the extra space to the label also fixed that.
Here is the code where I create my labels. The ratings is my actual data defined earlier:
// Add blank labels and "Today"
for (i=0; i<ratings.length; i++) {
labels.push("");
}
labels[ratings.length-1] = " ";
var data = {
labels: labels,
datasets: [
{
label: "Progress",
strokeColor: "rgba(255,165,0,1.0)",
pointColor: "white",
pointStrokeColor: "rgba(255,165,0,1.0)",
pointHighlightStroke: "#B87700",
data: ratings
}
]
};
Even if you have actual labels on your graph, you could add spaces to your last label to make it bigger. If you are centering your label, you could add the same amount of space before and after.
Obviously there will be limits where this will or won't work for you, but for my case I added 7 spaces and all looks good now.
Also, my case had an issue on the right side, whereas this question has an issue with the left side. The same fix should work, but putting the space on the first label.
It seems like Chart.js can't figure out which direction to show the tooltip because it can't detect the size of the tooltip element when it extends beyond the canvas.
In my scenario I fixed it by squeezing the text inside this particular tooltip closer with these options for the tooltip options object:
tooltips.titleMarginBottom = 1;
tooltips.bodySpacing = 1;
tooltips.yPadding = 2;
Wierdly enough Chart.js then correctly decides to show the tooltip to the left of the mouse and not below.
Would be cool if you could choose which direction the tooltip appears compared to the mouse.
In my case, I was able to work around this issue by reducing the amount of text in the tooltip. I did so using custom tooltip callbacks to specify the label text. My initialization looked like this:
var chart = new Chart(canvas.getContext("2d"), {
type: 'line',
data: chartData,
options: {
responsive: true,
tooltips: {
callbacks: {
title: function(tooltipItems, data) {
return tooltipItems[0].xLabel;
},
label: function(tooltipItems, data) {
return tooltipItems.yLabel;
},
}
},
},
});
There appears to be a fix available that hasn't yet been merged into the project: https://github.com/chartjs/Chart.js/pull/1064
Interestingly, by the setting the tooltipCaretSize option to 0 solves the issue.
{ tooltipCaretSize: 0, ... }

Highcharts Line Chart with Only x-axis

I've recently made the switch to Highcharts, for easy compatibility with IE8, and have been updating past projects because of the simplicity, but I have run into a minor hurdle.
In one project the last SVG element remaining is a single x-axis without any accompanying chart (see below). Is it possible to show only an x-axis in Highcharts without any accompanying series or y-axis? Or if not, is there a way to create this type of design as a DIV?
Yes, you can display just xAxis. Don't add any of series, but set xAxis.min and xAxis.max. Demo: http://jsfiddle.net/m4r1qttL/6/
Now just disable titles, legend etc.
Just add
yAxis: {
...
lineWidth: 0,
minorGridLineWidth: 0,
lineColor: 'transparent',
...
labels: {
enabled: false
},
minorTickLength: 0,
tickLength: 0
}
To the axis definition

Jquery Pie chart with inner circle

For an project i need to realise an chart with two circles. It need to looks like this one:
Is there an Jquery solution that support this? I already tried with Jqplot but with that plug-in i can't succeed to create something like this. I tried with this code:
// Create chart
var plot1 = $.jqplot('pie_chart', [s2,s1], {
seriesDefaults: {
renderer:$.jqplot.DonutRenderer,
rendererOptions:{
startAngle: -90,
showDataLabels: true,
dataLabels: 'value',
innerDiameter :0,
padding:5,
highlightMouseOver:false
}
}
});
//Theming based in the rendered module items in the HTML
temp = {
seriesStyles: {seriesColors: array2},
grid: {
backgroundColor: 'rgba(0,0,0,0)',
borderWidth: 0,
shadow: false
}
};
plot1.themeEngine.newTheme('uma', temp);
plot1.activateTheme('uma');
But the colors are for the inner and outer ring the same and create something like this:
The settings for the style are for the inner and outer ring. In my case i need to give the outer ring an different style.
Can i use this plug-in or do i need to use an other Jquery plug-in to realise my chart?
I found an solution wich works with d3.js (http://d3js.org/):
http://bl.ocks.org/mbostock/4063423
Works fine for me! Currently looks like this:

Categories

Resources