Chart.js how to highlight a part of a label - reactjs

i am trying to highlight part of a label from the axis labels based on what the user has searched for.
However the label is being rendered as text so the html tags are shown like plain text. any ideas on how to achieve this?

You can use the Plugin Core API. It offers different hooks that may be used for executing custom code. In below code snippet, I use the afterDraw hook to draw text of different styles underneath each bar.
When drawing your own tick labels, probably want to define the text rotation. Further you need to instruct Chart.js not to display the default labels. This can be done through the following definition inside the chart options.
scales: {
xAxes: [{
ticks: {
display: false,
rotation: 40
}
}],
You also need to define some padding for the bottom of the chart, otherwise you won't see your custom tick labels.
layout: {
padding: {
bottom: 60
}
},
Please take a look at below code sample and see how it works. Tick labels that need to be drawn with two different styles are separated with a semicolon inside data.labels.
new Chart(document.getElementById('myChart'), {
type: 'bar',
plugins: [{
afterDraw: chart => {
let ctx = chart.chart.ctx;
let xAxis = chart.scales['x-axis-0'];
let yAxis = chart.scales['y-axis-0'];
chart.data.labels.forEach((l, i) => {
let labelTokens = l.split(';');
let rotation = xAxis.options.ticks.rotation * -Math.PI / 180;
let x = xAxis.getPixelForValue(l);
if (labelTokens.length == 2) {
ctx.save();
let width = ctx.measureText(labelTokens.join(' ')).width;
ctx.translate(x, yAxis.bottom + 10);
ctx.rotate(rotation);
ctx.font = 'italic 12px Arial';
ctx.fillStyle = 'blue';
ctx.fillText(labelTokens[0], -width, 0);
ctx.restore();
}
ctx.save();
let labelEnd = labelTokens[labelTokens.length - 1];
let width = ctx.measureText(labelEnd).width;
ctx.translate(x, yAxis.bottom + 10);
ctx.rotate(rotation);
ctx.font = '12px Arial';
ctx.fillText(labelEnd, -width, 0);
ctx.restore();
});
}
}],
data: {
labels: ['NASTY!!;Errors', 'Warnings'],
datasets: [{
label: 'Result',
data: [30, 59],
fill: false,
backgroundColor: ['rgba(255, 99, 132, 0.2)', 'rgba(255, 159, 64, 0.2)'],
borderColor: ['rgb(255, 99, 132)', 'rgb(255, 159, 64)'],
borderWidth: 1
}]
},
options: {
layout: {
padding: {
bottom: 60
}
},
legend: {
display: false
},
tooltips: {
callbacks: {
title: tooltipItem => tooltipItem[0].xLabel.split(';').join(' ')
}
},
scales: {
xAxes: [{
ticks: {
display: false,
rotation: 40
}
}],
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
canvas {
max-width: 250px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"></script>
<canvas id="myChart" width="10" height="8"></canvas>

Related

How to use a static color for Chart.js bar chart's legend, when using an array of background colors [duplicate]

I have a bar chart that always shows 4 bars. The bars are coloured dynamically. It looks like the coloured box takes its colour from the first data. I would like to use the colour from the 4th (last) data value. Maybe the options:plugins:legend:label:sort function helps but I don't understand what it does.
options
const options = {
scales: {
x: {
grid: {
display: false,
color: 'rgba(0,0,0)'
}
},
y: {
display: false,
min: 0,
max: 4
},
},
plugins: {
legend: {
position: 'bottom'
}
}
}
So I don't know if I can change the data that the box color comes from, or if there is a config option somewhere where I can change it manually.
You can use the generateLabels function as described here.
Please take a look at below runnable sample code and see how it works.
new Chart('myChart', {
type: 'bar',
data: {
labels: ['Red', 'Blue', 'Yellow'],
datasets: [{
label: 'My Dataset',
data: [300, 50, 100],
backgroundColor: ['#FF6384', '#36A2EB', '#FFCE56']
}]
},
options: {
responsive: false,
plugins: {
legend: {
labels: {
generateLabels: chart => {
let ds = chart.data.datasets[0];
let color = ds.backgroundColor[ds.backgroundColor.length - 1];
return [{
datasetIndex: 0,
text: ds.label,
fillStyle: color,
strokeStyle: color
}];
}
}
}
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.1/chart.min.js"></script>
<canvas id="myChart" height="180"></canvas>
Following up with #uminder's answer, if you want to keep the hide/show chart and the line-through style after clicking on the legend, you can add the following line:
options: {
responsive: false,
plugins: {
legend: {
labels: {
generateLabels: chart => {
let ds = chart.data.datasets[0];
let color = ds.backgroundColor[ds.backgroundColor.length - 1];
return [{
datasetIndex: 0,
text: ds.label,
fillStyle: color,
strokeStyle: color,
+ hidden: !chart.isDatasetVisible(0)
}];
}
}
}
}
}

Change background color of every second column in Chartjs? [duplicate]

In react-chartjs-2
In Line chart every grid should have different background colors.
Is this achievable with this library?
This is how LineChart should looks:
This is my Code/configuration:
const options = {
responsive: true,
scales: {
y: {
grid: {
backgroundColor: [
'rgba(36, 206, 0, 0.8)',
'rgba(255, 255, 0, .8)',
'rgba(255, 162, 0, 0.8)',
'rgba(36, 206, 0, 0.8)',
],
},
};
Thanks for reading.
You can use an inline plugin to achieve it:
var GradientBgPlugin = {
beforeDraw: function(chart, args, options) {
const ctx = chart.ctx;
const canvas = chart.canvas;
const chartArea = chart.chartArea;
// Chart background
var gradientBack = canvas.getContext("2d").createLinearGradient(0, 250, 0, 0);
gradientBack.addColorStop(0, "rgba(213,235,248,1)");
gradientBack.addColorStop(0.16, "rgba(213,235,248,1)");
gradientBack.addColorStop(0.17, "rgba(226,245,234,1)");
gradientBack.addColorStop(0.25, "rgba(226,245,234,1)");
gradientBack.addColorStop(0.26, "rgba(252,244,219,1)");
gradientBack.addColorStop(0.5, "rgba(252,244,219,1)");
gradientBack.addColorStop(0.51, "rgba(251,221,221,1)");
gradientBack.addColorStop(1, "rgba(251,221,221,1)");
ctx.fillStyle = gradientBack;
ctx.fillRect(chartArea.left, chartArea.bottom,
chartArea.right - chartArea.left, chartArea.top - chartArea.bottom);
}
};
Than just include it in your Chart options:
plugins: [GradientBgPlugin]
The result should be similar to this JSFiddle.
EDIT
For Reach Charts JS 2, you need small changes in setup. You define plugin this way:
const plugins = [{
beforeDraw: function(chart) {
const ctx = chart.ctx;
const canvas = chart.canvas;
const chartArea = chart.chartArea;
// Chart background
var gradientBack = canvas.getContext("2d").createLinearGradient(0, 250, 0, 0);
gradientBack.addColorStop(0, "rgba(213,235,248,1)");
gradientBack.addColorStop(0.16, "rgba(213,235,248,1)");
gradientBack.addColorStop(0.17, "rgba(226,245,234,1)");
gradientBack.addColorStop(0.25, "rgba(226,245,234,1)");
gradientBack.addColorStop(0.26, "rgba(252,244,219,1)");
gradientBack.addColorStop(0.5, "rgba(252,244,219,1)");
gradientBack.addColorStop(0.51, "rgba(251,221,221,1)");
gradientBack.addColorStop(1, "rgba(251,221,221,1)");
ctx.fillStyle = gradientBack;
ctx.fillRect(chartArea.left, chartArea.bottom,
chartArea.right - chartArea.left, chartArea.top - chartArea.bottom);
}
}];
Than you plug it this way:
<Line data={data} plugins={plugins} />
You can see it working fine on CodeSandbox here.
You can write a custom inline plugin, that draws the colors on the chart Area. In the options section you can put an object with all the sections you want, from where to where and which color they need to be
Example:
var options = {
type: 'line',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [100, 19, 3, 5, 2, 3],
borderWidth: 1
},
{
label: '# of Points',
data: [7, 11, 5, 8, 3, 7],
borderWidth: 1
}
]
},
options: {
plugins: {
backgrounds: {
hbars: [{
from: 28,
to: 100,
color: "rgb(195, 230, 195)"
},
{
from: 20,
to: 28,
color: "rgb(230, 220, 195)"
},
{
from: 0,
to: 20,
color: "rgb(230, 195, 195)"
}
]
}
}
},
plugins: [{
id: 'backgrounds',
beforeDraw: (chart, args, options) => {
const {
ctx,
chartArea,
scales: {
y
}
} = chart;
options.hbars.forEach((hBar) => {
ctx.save();
ctx.fillStyle = hBar.color;
ctx.fillRect(chartArea.left, y.getPixelForValue(hBar.from), chartArea.right - chartArea.left, y.getPixelForValue(hBar.to) - y.getPixelForValue(hBar.from));
ctx.restore();
})
}
}]
}
var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.2.0/chart.js"></script>
</body>
Detailed explanation can be found here: https://medium.com/#omi10859/alternative-background-lines-in-chartjs-a626ce4d3bcb
We can use annotaion plugin with chartjs to create custom elements.
we can use annotation plugin to do this
import annotationPlugin from "chartjs-plugin-annotation";
import {Chart} from 'chart.js';
Chart.register(annotationPlugin);
this code will add a box to our chart
{
type: 'box', #type of draw
drawTime: 'beforeDraw', #this will decide background or foreground
yMin: 5, #value min on y axis
yMax: 10, #value max on y axis
borderColor: 'rgb(242, 244, 248, 0.9)', #border color of the box
borderWidth: 1, #boarder width for box
backgroundColor: '#F2F4F8', #colour of the box
}
# add option while rendering
const options = {
plugins: {annotation: {annotations: background_annotation}
}
this code render this

chartjs: bars smaller than actual column, tooltip doesn't display

As you can see my bars are not covering the entire width of the label 'column'.
My tooltip only shows if I am exactly hovering the bar, or, if I remove the bars, exactly on the line point.
options: {
plugins: {
legend: { display: false },
title: { display: false },
tooltip: {
displayColors: false, backgroundColor: '#ffffff',
bodyColor: '#595f69', bodyFont: {size: 14},
borderColor: '#595f69', borderWidth: 1,
titleFont: {size: 0}
}
},
responsive: true, aspectRatio: 4,
scales: {
y: { display: true, suggestedMin: 0, suggestedMax: 80, ticks: { stepSize: 20 } },
y1: {display: false, suggestedMin: 0, suggestedMax: 80, ticks: { stepSize: 2 }},
x: { grid: { drawBorder: false, display: false } }
I tried plugins like chartjs crosshair, but don't manage to make it work with typescript.
How can I make it so that anywhere my mouse hover in the label 'column' area, the tooltip displays?
You can set the intersect property to false to always get the tooltip without needing to intersect the bar exactly:
var options = {
type: 'bar',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
borderWidth: 1
}]
},
options: {
plugins: {
tooltip: {
intersect: false
}
}
}
}
var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.0/chart.js"></script>
</body>
You can make your own tooltip by editing the callbacks, i had to get the nearest values around my cursor, from all datasets, on my line chart. this works for me on Chartjs 2.9.3:
tooltips: {
mode: "x",
position: "nearest",
intersect: false,
callbacks: {
beforeBody: function(tooltipItems, allData) {
let x = tooltipItems[0].x; // get x coordinate
let datasets = allData.datasets; // datasets
let values = [];
for (i in datasets) {
let dataset = datasets[i];
let meta = this._chart.getDatasetMeta(i); // dataset metadata
let xScale = this._chart.scales[meta.xAxisID]; // dataset's x axis
let xValue = xScale.getValueForPixel(x); // we get the x value on the x axis with x coordinate
let data = dataset.data // data
// search data for the first value with a bigger x value
let index = data.findIndex(function(o) {
return o.x >= xValue;
});
let value = data[index]; // this is our nearest value
// format label
if (isNaN(value.ymax)) {
values.push(`${dataset.label}: ${value.y}\n`);
} else {
values.push(`${dataset.label}: ${value.y}, min: ${value.ymin}, max: ${value.ymax}\n`)
}
}
return values.join(""); // return label
},
label: function() { // this needs to be empty
},
}
},

Mouse over on line chart data active other data-set in Chart.js

I'm creating a line chart using Chart.js. The chart has two datasets. The x-axis is date, and y-axis is the value. When I hover the first data in dataset 1, the first data in dataset 2 is also active(zoom). That isn't I expected. Is there any way to active only the hovered data. And is there any way to active all data by their y value, not by index.
I've tried edit the tooltips mode but the result is not I expected. It shows the tooltips in difference dataset with same index.
https://www.chartjs.org/docs/latest/general/interactions/modes.html
var ctx = document.getElementById("myChart");
var barChart = new Chart(ctx, {
type: 'line',
data: {
datasets: [{
label: 'Dataset 1',
data: [{
x: '2019-01-15',
y: 100
}, {
x: '2019-02-03',
y: 300
}],
backgroundColor: 'rgba(0, 0, 0, 0)',
borderColor: 'rgba(255, 0, 0, 1)',
borderWidth: 1
}, {
label: 'Dataset 2',
data: [{
x: '2019-01-03',
y: 150
}, {
x: '2019-01-15',
y: 200
}, {
x: '2019-02-06',
y: 250
}],
backgroundColor: 'rgba(0, 0, 0, 0)',
borderColor: 'rgba(0, 255, 255, 1)',
borderWidth: 1
}],
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true,
}
}],
xAxes: [{
type: 'time',
position: 'bottom',
time: {
min: "2019-1-1",
max: "2019-2-28",
unit: "month",
displayFormats: {
"month": "YYYY-MM",
}
}
}]
}
}
});
https://jsfiddle.net/t1gmrujo/2/
I've tried edit the tooltips mode but the result is not I expected. It shows the tooltips in difference dataset with same index.
The tooltip configuration controls display of the tooltip popup, not the dataset points. Points are controlled by the hover configuration. This is mentioned on the page you linked (emphasis mine):
When configuring interaction with the graph via hover or tooltips, a number of different modes are available.
If you only want the single point you are hovering over to be highlighted, use:
options: {
hover: {
mode: 'point'
}
}
If you want the whole dataset highlighted when hovering any single dataset point, use:
options: {
hover: {
mode: 'dataset'
}
}
If you want to highlight the dataset and see all dataset values in the tooltip, use:
options: {
hover: {
mode: 'dataset'
},
tooltips: {
mode: 'dataset'
}
}

Adding tooltip to legend in highcharts

I am trying to add a tooltip to the legend in highcharts. I am using a pie chart. Using angular js framework.
The legend code is as below
legend: {
useHTML: true,
layout: 'vertical',
align: 'left',
itemMarginTop: 10,
itemMarginBottom: 15,
title: {
style: {
fontSize: "14px",
fontWeight: "600",
color: "#404040"
}
},
itemStyle: {
fontWeight: 'normal',
color: '#404040',
fontSize: '14px'
},
//x : 70,
//y: 110,
labelFormatter: function() {
return ` <md-icon>
<md-tooltip md-direction="top">Hello</md-tooltip>
<i class="material-icons help_icon">info_outline</i>
</md-icon>`
}
},
I do not get the expected results. it just displays the letter H and no icon. If i use a standalone icon like
<i class="material-icons help_icon">info_outline</i>
It just displays the icon. But I am unable to add any tooltip. I searched online and found a solution using the jquery UI plugin. Is there any other way without the plugin and using the angular material icons? Please suggest.
Ps: I have also tried with single quotes / double quotes instead of inverted ticks.
Unfortunately, tooltip in a legend is not supported. However, you can create it using Highcharts.SVGRenderer. Check code and demo posted below.
Code:
var chart = Highcharts.chart('container', {
chart: {
type: 'column',
events: {
load: function() {
var chart = this,
legend = chart.legend,
legendItems = legend.allItems,
group,
rectElem,
textElem,
box,
i;
group = chart.renderer.g('legend-tooltip').attr({
transform: 'translate(-9999, -9999)',
zIndex: 99
}).add();
textElem = chart.renderer.text().attr({
class: 'legend-tooltip-text',
zIndex: 7
}).add(group);
rectElem = chart.renderer.rect().attr({
'class': 'legend-tooltip',
'stroke-width': 1,
'stroke': '#c5c5c5',
'fill': 'rgba(245, 245, 245, 0.95)',
}).add(group);
for (i = 0; i < legendItems.length; i++) {
(function(i) {
var item = legend.allItems[i].legendItem.parentGroup;
item.on('mouseover', function(e) {
// Define legend-tooltip text
var str = chart.series[i].userOptions.fullName;
textElem.element.innerHTML = str;
// Adjust rect size to text
box = textElem.getBBox()
rectElem.attr({
x: box.x - 8,
y: box.y - 5,
width: box.width + 15,
height: box.height + 10
});
// Show tooltip
group.attr({
transform: `translate(${e.clientX + 7}, ${e.clientY + 7})`
})
}).on('mouseout', function(e) {
// Hide tooltip
group.attr({
transform: 'translate(-9999,-9999)'
})
});
})(i);
}
}
}
},
series: [{
data: [10, 12, 5],
fullName: 'Series 1 tooltip'
}, {
data: [6, 10, 7],
fullName: 'Series 2 tooltip'
}]
});
Demo:
https://jsfiddle.net/BlackLabel/3cbpe0mn/
API reference:
https://api.highcharts.com/class-reference/Highcharts.SVGRenderer
https://api.highcharts.com/class-reference/Highcharts.SVGElement#on

Resources