Highcharts tooltip formatter function does not display values in table correct - if-statement

I have created an if else statement in my highcharts tooltip formatter function in order to display y values from different point.series.name.
Values from first and second series in the array displays correct, but styling for the last series.name values (HINDCAST - SPREAD) does not display correct, because font-size and point.series.color does not show. I suppose the problem is the table tags? Please see fiddle
https://jsfiddle.net/marialaustsen/w4k87jyo/
tooltip: {
shared: true,
useHTML: true,
formatter: function() {
var aYearFromNow = new Date(this.x);
aYearFromNow.setFullYear(aYearFromNow.getFullYear() + 5);
var tooltip = '<table><span style="font-size: 16px">' +
Highcharts.dateFormat('%e/%b/%Y', new Date(this.x)) + '-' + Highcharts.dateFormat('%e/%b/%Y', aYearFromNow) + '</span><br/><tbody>';
//loop each point in this.points
$.each(this.points, function(i, point) {
if (point.series.name === 'Observations') {
tooltip += '<tr><th style="font-size: 14px; color: ' + point.series.color + '">' + point.series.name + ': </th>' +
'<td style="font-size: 14px">' + point.y + '℃' + '</td></tr>'
} else if (point.series.name === 'BOXPLOT') {
const x = this.x;
const currentData = this.series.data.find(data => data.x === x);
const boxplotValues = currentData ? currentData.options : {};
tooltip += `<span style="font-size: 14px; color: #aaeeee">
Max: ${boxplotValues.high.toFixed(2)}<br>
Q3: ${boxplotValues.q3.toFixed(2)}<br>
Median: ${boxplotValues.median.toFixed(2)}<br>
Q1: ${boxplotValues.q1.toFixed(2)}<br>
Low: ${boxplotValues.low.toFixed(2)}<br></span>`;
} else {
tooltip += '<tr><th style="font-size: 14px; color: ' + point.series.color + '">' + point.series.name + ': </th>' +
'<td style="font-size: 14px">' + point.point.low + '℃ -' + point.point.high + '℃' + '</td></tr>' +
'</tbody></table>';
}
});
return tooltip;
}
},

You're closing the tbody before the last value (HINDCAST - SPREAD), once put outside the for loop it works :
...
tooltip += '<tr><th style="font-size: 14px; color: ' + point.series.color + '">' + point.series.name + ': </th>' +
'<td style="font-size: 14px">' + point.point.low + '℃ -' + point.point.high + '℃' + '</td></tr>'
}
});
tooltip += '</tbody></table>';
return tooltip;
...
Fiddle

Related

Chartjs tooltip out of page

Is there a way to force the tooltip to stay inside the canvas?
right now if the window is too small, the pop up is not visible.
So, is there a way to force the tooltip to stay inside the canvas?
Well, if you are using a custom tooltip, like this one, you can create a offset so the tooltip will stay away from the borders:
var offset = tooltip.caretX + 20;
if (offset < tooltip.width)
offset = tooltip.width;
else if (tooltip.caretX > this._chart.width - tooltip.width)
offset = this._chart.width - tooltip.width;
// Hidden Code
tooltipEl.style.left = positionX + offset + 'px';
An working example, this code have been copied from another one of my answers in this post:
var customTooltips = function(tooltip) {
// Tooltip Element
var tooltipEl = document.getElementById('tooltip');
if (!tooltipEl) {
tooltipEl = document.createElement('div');
tooltipEl.id = 'tooltip';
tooltipEl.innerHTML = '<table></table>';
this._chart.canvas.parentNode.appendChild(tooltipEl);
}
// Hide if no tooltip
if (tooltip.opacity === 0) {
tooltipEl.style.opacity = 0;
return;
}
// Set caret Position
tooltipEl.classList.remove('above', 'below', 'no-transform');
if (tooltip.yAlign) {
tooltipEl.classList.add(tooltip.yAlign);
} else {
tooltipEl.classList.add('no-transform');
}
function getBody(bodyItem) {
return bodyItem.lines;
}
// Set Text
if (tooltip.body) {
var titleLines = tooltip.title || [];
var bodyLines = tooltip.body.map(getBody);
var innerHtml = '<thead>';
titleLines.forEach(function(title) {
innerHtml += '<tr><th>' + title + '</th></tr>';
});
innerHtml += '</thead><tbody>';
bodyLines.forEach(function(body, i) {
var colors = tooltip.labelColors[i];
var style = 'background:' + colors.backgroundColor;
style += '; border-color:' + colors.borderColor;
style += '; border-width: 2px';
var span = '<span class="chartjs-tooltip-key" style="' + style + '"></span>';
var innerContent = '<td>' + span + body + '</td>';
// Every even/odd create a new tr
if (i % 2 == 0)
innerHtml += '<tr>' + innerContent;
else
innerHtml += innerContent + '</tr>';
});
// If is a odd number of itens close the last open tr
if (bodyLines.count % 2 == 1)
innerHtml += '</tr></tbody>';
else
innerHtml += '</tbody>';
var tableRoot = tooltipEl.querySelector('table');
tableRoot.innerHTML = innerHtml;
}
var positionY = this._chart.canvas.offsetTop;
var positionX = this._chart.canvas.offsetLeft;
var offset = tooltip.caretX + 20;
if (offset < tooltip.width)
offset = tooltip.width;
else if (tooltip.caretX > this._chart.width - tooltip.width)
offset = this._chart.width - tooltip.width;
// Display, position, and set styles for font
tooltipEl.style.opacity = 1;
tooltipEl.style.left = positionX + offset + 'px';
tooltipEl.style.top = positionY + tooltip.caretY + 'px';
tooltipEl.style.fontFamily = tooltip._bodyFontFamily;
tooltipEl.style.fontSize = tooltip.bodyFontSize + 'px';
tooltipEl.style.fontStyle = tooltip._bodyFontStyle;
tooltipEl.style.padding = tooltip.yPadding + 'px ' + tooltip.xPadding + 'px';
};
var myChart = new Chart($('#myChart'), {
type: 'line',
data: {
labels: ['Day 1', 'Day 2', 'Day 3', 'Day 4'],
datasets: [{
label: 'Dats asd asda 1',
data: [12, 19, 3, 5],
pointRadius: 5,
pointHoverRadius: 5,
backgroundColor: 'rgba(255, 0, 0, 0.2)'
}, {
label: 'D 2',
data: [13, 17, 4, 6],
pointRadius: 5,
pointHoverRadius: 5,
backgroundColor: 'rgba(255, 255, 0, 0.2)'
}, {
label: 'D 3',
data: [14, 19, 3, 9],
pointRadius: 5,
pointHoverRadius: 5,
backgroundColor: 'rgba(0, 255, 0, 0.2)'
}, {
label: 'Data 4',
data: [15, 20, 2, 8],
pointRadius: 5,
pointHoverRadius: 5,
backgroundColor: 'rgba(0, 0, 255, 0.2)'
}]
},
options: {
responsive: false,
scales: {
yAxes: [{
display: true,
ticks: {
suggestedMax: 50,
}
}]
},
tooltips: {
enabled: false,
mode: 'index',
intersect: false,
custom: customTooltips
}
}
});
#tooltip {
opacity: 1;
position: absolute;
background: rgba(0, 0, 0, .7);
color: white;
border-radius: 3px;
-webkit-transition: all .1s ease;
transition: all .1s ease;
pointer-events: none;
-webkit-transform: translate(-50%, 0);
transform: translate(-50%, 0);
padding: 4px;
}
#tooltip td {
text-align: left;
}
.chartjs-tooltip-key {
display: inline-block;
width: 10px;
height: 10px;
margin-right: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.css" integrity="sha256-aa0xaJgmK/X74WM224KMQeNQC2xYKwlAt08oZqjeF0E=" crossorigin="anonymous" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.js" integrity="sha256-Uv9BNBucvCPipKQ2NS9wYpJmi8DTOEfTA/nH2aoJALw=" crossorigin="anonymous"></script>
<canvas id="myChart" width="400" height="200"></canvas>
Take a look at this: https://stackoverflow.com/a/64887282/8411093
Demo: https://codepen.io/themustafaomar/pen/wvWZrod
function customTooltips(tooltipModel) {
// Tooltip Element
var tooltipEl = document.getElementById("chartjs-tooltip");
const yAlign = tooltipModel.yAlign;
const xAlign = tooltipModel.xAlign;
// Create element on first render
if (!tooltipEl) {
tooltipEl = document.createElement("div");
tooltipEl.id = "chartjs-tooltip";
tooltipEl.innerHTML = "<table></table>";
document.body.appendChild(tooltipEl);
}
// Hide if no tooltip
if (tooltipModel.opacity === 0) {
tooltipEl.style.opacity = 0;
return;
}
// Set caret Position
tooltipEl.classList.remove("top", "bottom", "center", "left", "right");
if (tooltipModel.yAlign || tooltipModel.xAlign) {
tooltipEl.classList.add(tooltipModel.yAlign);
tooltipEl.classList.add(tooltipModel.xAlign);
}
// Set Text
if (tooltipModel.body) {
var titleLines = tooltipModel.title || [];
var bodyLines = tooltipModel.body.map((bodyItem) => {
return bodyItem.lines;
});
var innerHtml = "<thead>";
titleLines.forEach(function (title) {
innerHtml += '<tr><th><div class="mb-1">' + title + "</div></th></tr>";
});
innerHtml += "</thead><tbody>";
bodyLines.forEach((body, i) => {
var colors = tooltipModel.labelColors[i];
// var style = 'background-color:' + colors.borderColor
var style =
"background-color:" + this._chart.data.datasets[i].borderColor;
var value = tooltipModel.dataPoints[i].value;
var label = this._chart.data.datasets[i].label;
style += "; border-color:" + colors.borderColor;
style += "; border-color:" + this._chart.data.datasets[i].borderColor;
style += "; border-width: 2px";
var span =
'<span class="chartjs-tooltip-key" style="' + style + '"></span>';
innerHtml += `<tr><td> ${span} $${value}K </td></tr>`;
});
innerHtml += "</tbody>";
var tableRoot = tooltipEl.querySelector("table");
tableRoot.innerHTML = innerHtml;
}
// Tooltip height and width
const { height, width } = tooltipEl.getBoundingClientRect();
// Chart canvas positions
const positionY = this._chart.canvas.offsetTop;
const positionX = this._chart.canvas.offsetLeft;
// Carets
const caretY = tooltipModel.caretY;
const caretX = tooltipModel.caretX;
// Final coordinates
let top = positionY + caretY - height;
let left = positionX + caretX - width / 2;
let space = 8; // This for making space between the caret and the element.
// yAlign could be: `top`, `bottom`, `center`
if (yAlign === "top") {
top += height + space;
} else if (yAlign === "center") {
top += height / 2;
} else if (yAlign === "bottom") {
top -= space;
}
// xAlign could be: `left`, `center`, `right`
if (xAlign === "left") {
left = left + width / 2 - tooltipModel.xPadding - space / 2;
if (yAlign === "center") {
left = left + space * 2;
}
} else if (xAlign === "right") {
left -= width / 2;
if (yAlign === "center") {
left = left - space;
} else {
left += space;
}
}
// Display, position, and set styles for font
tooltipEl.style.opacity = 1;
// Left and right
tooltipEl.style.top = `${top}px`;
tooltipEl.style.left = `${left}px`;
// Font
tooltipEl.style.fontFamily = tooltipModel._bodyFontFamily;
tooltipEl.style.fontSize = tooltipModel.bodyFontSize + "px";
tooltipEl.style.fontStyle = tooltipModel._bodyFontStyle;
// Paddings
tooltipEl.style.padding =
tooltipModel.yPadding + "px " + tooltipModel.xPadding + "px";
}

How can I increase the size of the pie (Chart.JS)?

I'm generating a pie chart with legend that looks like so:
As you can perceive, the pie is pitifully puny. I prefer it to be twice as tall and twice as wide.
Here is the code I am using:
var formatter = new Intl.NumberFormat("en-US");
Chart.pluginService.register({
afterDatasetsDraw: function (chartInstance) {
var ctx = chartInstance.chart.ctx;
ctx.font = Chart.helpers.fontString(14, 'bold', Chart.defaults.global.defaultFontFamily);
ctx.textAlign = 'center';
ctx.textBaseline = 'bottom';
ctx.fillStyle = '#666';
chartInstance.config.data.datasets.forEach(function (dataset) {
for (var i = 0; i < dataset.data.length; i++) {
var model = dataset._meta[Object.keys(dataset._meta)[0]].data[i]._model,
total = dataset._meta[Object.keys(dataset._meta)[0]].total,
mid_radius = model.innerRadius + (model.outerRadius - model.innerRadius) / 2,
start_angle = model.startAngle,
end_angle = model.endAngle,
mid_angle = start_angle + (end_angle - start_angle) / 2;
var x = mid_radius * 1.5 * Math.cos(mid_angle);
var y = mid_radius * 1.5 * Math.sin(mid_angle);
ctx.fillStyle = '#fff';
if (i === 0 || i === 3 || i === 7) { // Darker text color for lighter background
ctx.fillStyle = '#666';
}
var percent = String(Math.round(dataset.data[i] / total * 100)) + "%";
// this prints the data number
// this prints the percentage
ctx.fillText(percent, model.x + x, model.y + y);
}
});
}
});
var data = {
labels: [
"Bananas (18%)",
"Lettuce, Romaine (14%)",
"Melons, Watermelon (10%)",
"Pineapple (10%)",
"Berries (10%)",
"Lettuce, Spring Mix (9%)",
"Broccoli (8%)",
"Melons, Honeydew (7%)",
"Grapes (7%)",
"Melons, Cantaloupe (7%)"
],
datasets: [
{
data: [2755, 2256, 1637, 1608, 1603, 1433, 1207, 1076, 1056, 1048],
backgroundColor: [
"#FFE135",
"#3B5323",
"#fc6c85",
"#ffec89",
"#021c3d",
"#3B5323",
"#046b00",
"#cef45a",
"#421C52",
"#FEA620"
]
}]
};
var optionsPie = {
responsive: true,
scaleBeginAtZero: true,
legend: {
display: false
},
tooltips: {
callbacks: {
label: function (tooltipItem, data) {
return data.labels[tooltipItem.index] + ": " +
formatter.format(data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index]);
}
}
}
};
var ctx = $("#top10ItemsChart").get(0).getContext("2d");
var top10PieChart = new Chart(ctx,
{
type: 'pie',
data: data,
options: optionsPie,
animation: {
duration: 0,
easing: "easeOutQuart",
onComplete: function () {
var ctx = this.chart.ctx;
ctx.font = Chart.helpers.fontString(Chart.defaults.global.defaultFontFamily, 'normal', Chart.defaults.global.defaultFontFamily);
ctx.textAlign = 'center';
ctx.textBaseline = 'bottom';
this.data.datasets.forEach(function (dataset) {
for (var i = 0; i < dataset.data.length; i++) {
var model = dataset._meta[Object.keys(dataset._meta)[0]].data[i]._model,
total = dataset._meta[Object.keys(dataset._meta)[0]].total,
mid_radius = model.innerRadius + (model.outerRadius - model.innerRadius) / 2,
start_angle = model.startAngle,
end_angle = model.endAngle,
mid_angle = start_angle + (end_angle - start_angle) / 2;
var x = mid_radius * Math.cos(mid_angle);
var y = mid_radius * Math.sin(mid_angle);
ctx.fillStyle = '#fff';
if (i === 3) { // Darker text color for lighter background
ctx.fillStyle = '#444';
}
var percent = String(Math.round(dataset.data[i] / total * 100)) + "%";
// this prints the data number
ctx.fillText(dataset.data[i], model.x + x, model.y + y);
// this prints the percentage
ctx.fillText(percent, model.x + x, model.y + y + 15);
}
});
}
}
});
$("#top10Legend").html(top10PieChart.generateLegend());
How can I increase the size of the pie?
UPDATE
The "View" as requested by Nkosi is:
<div class="row" id="top10Items">
<div class="col-md-6">
<div class="topleft">
<h2 class="sectiontext">Top 10 Items</h2>
<br />
<div id="piechartlegendleft">
<div id="container">
<canvas id="top10ItemsChart"></canvas>
</div>
<div id="top10Legend" class="pieLegend"></div>
</div>
</div>
</div>
. . .
The classes "row" and "col-md-6" are Bootstrap classes.
The custom classes are "topleft":
.topleft {
margin-top: -4px;
margin-left: 16px;
margin-bottom: 16px;
padding: 16px;
border: 1px solid black;
}
...sectionText:
.sectiontext {
font-size: 1.5em;
font-weight: bold;
font-family: Candara, Calibri, Cambria, serif;
color: green;
margin-top: -4px;
}
...and "pieLegend":
.pieLegend li span {
display: inline-block;
width: 12px;
height: 12px;
margin-right: 5px;
}
You just need to change the canvas size.
When you are creating the chart you can specify it right in the element:
<canvas id="top10ItemsChart" width="1000" height="1000"></canvas>
Or if you prefer to do it in javascript
var ctx = $("#top10ItemsChart").get(0).getContext("2d");
ctx.width = 1000;
ctx.height = 1000;
If the resizing doesn't work as you wish, you can also try setting the maintainAspectRatio option to false:
var optionsPie = {
/** ... */
responsive: true,
maintainAspectRatio: false,
/** ... */
};
Hope it helps.

csv data with d3 doesn't work

I'm trying to load data from a csv-File to create a pie chart.
I found a example and copied it to test it. But it doesn't work. It seems that I'm the only one with this Problem. Whats my fault? Can someone help me?
My html-file:
<!DOCTYPE html>
<meta charset="utf-8">
<style>
body {
font: 10px sans-serif;
}
.arc path {
stroke: #fff;
}
</style>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script>
<script>
var width = 960,
height = 500,
radius = Math.min(width, height) / 2;
var color = d3.scale.ordinal()
.range(["#98abc5", "#8a89a6", "#7b6888", "#6b486b", "#a05d56", "#d0743c", "#ff8c00"]);
var arc = d3.svg.arc()
.outerRadius(radius - 10)
.innerRadius(0);
var pie = d3.layout.pie()
.sort(null)
.value(function(d) { return d.population; });
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
d3.csv("data.csv", function(error, data) {
data.forEach(function(d) {
d.population = +d.population;
});
var g = svg.selectAll(".arc")
.data(pie(data))
.enter().append("g")
.attr("class", "arc");
g.append("path")
.attr("d", arc)
.style("fill", function(d) { return color(d.data.age); });
g.append("text")
.attr("transform", function(d) { return "translate(" + arc.centroid(d) + ")"; })
.attr("dy", ".35em")
.style("text-anchor", "middle")
.text(function(d) { return d.data.age; });
});
</script>
and the csv:
age,population
<5,2704659
5-13,4499890
14-17,2159981
18-24,3853788
25-44,14106543
45-64,8819342
≥65,612463
Perhaps I have to edit, that I'm using it with django. Without django it works.
So here is my view:
def test(request):
t = get_template('test.html')
html = t.render()
return HttpResponse(html)

How to add image to chart.js tooltip?

i'm using Chart.js to build a line graph by specific directions from a designer, and I want my tooltip to include a small icon.
is it possible ?
You can override the customTooltips function.
var myLineChart = new Chart(ctx).Line(data, {
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 = '<img src="pathTomyImage/myImage.png"> <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,
});
}
});
Replace pathTomyImage/myImage.png with your image URL (you could also pick this from a lookup using parts[0] - which is the x axis label, or easier still give your images a name depending on the axis label. eg. January.png, February.png)
Make sure you add the following markup as well
<div id="chartjs-tooltip"></div>
Fiddle - http://jsfiddle.net/02xrgy10/

Extjs Custom Combobox

how to create a custom combo like above?
here i just did a small hack to the component.by this way you can add any html element to the selection item in combo.
Ext.define('AMShiva.ux.custom.Combo', {
extend: 'Ext.form.field.ComboBox',
alias: 'widget.ux_combo',
colorField: 'color',//to get color value
displayField: 'text',
valueField:'value',
initComponent: function () {
var me = this;
// dropdown item template
me.tpl = Ext.create('Ext.XTemplate',
'<tpl for=".">',
'<div class="x-boundlist-item">',
'<span style="background-color: {' + me.colorField + '};" class="color-box-icon"></span>{' + me.displayField + '}',
'</div>',
'</tpl>'
);
me.callParent(arguments);
// here change the selection item html
me.on('change',
function(element, newValue) {
var inputEl = element.inputCell.child('input');
var data = element.getStore().findRecord(element.valueField, newValue);
if (data) {
inputEl.applyStyles('padding-left:26px');
var parent = inputEl.parent(),
spanDomEle = parent.child('span');
if (!spanDomEle) {
Ext.DomHelper.insertFirst(parent, { tag: 'span', cls: 'color-box-icon' });
var newSpanDomEle = parent.child('span');
newSpanDomEle.applyStyles('background-color: ' + data.get(element.colorField) + ';float: left;position: absolute;margin: 3px 2px 2px 4px;');
} else {
spanDomEle.applyStyles('background-color:' + data.get(element.colorField));
}
}
});
}
});
sample store:
var store = Ext.create('Ext.data.Store', {
fields: ['value', 'text', 'color']
});
css:
.color-box-icon {
width: 16px;
height: 16px;
margin: 0px 4px 0px -3px;
padding: 0px 8px;
}
Is there another way to do this kind of thing?