Highcharts conditional data labels - javascript

I'm creating a Highcharts line chart based upon some user input. The user can select 1 or more groupings and a date range and I create a series for each group. This works fine except for that when they select over 3 groups, the chart looks terrible because there are way too many data labels.
I'd like to conditionally enable data labels only when where are less than 4 series on a chart. How can I do that? I'm trying like this but I can't seem to get it to work.
plotOptions: {
line: {
dataLabels: {
enabled: function() {
return !!(chart.series.length > 3);
},
color: '#000000',
formatter: function() {
return Highcharts.numberFormat(this.y, 2);
}
}
}
}

When you create the series, keep track of how many you create. Also have a javascript variable 'showDataLabels=true'. If the number of series goes above 4 when you are creating them, set showDataLabels=false;
var showDataLabels = true;
// start creating the series.
If num series > 4
showDataLabels = false;
Once you are ready to generate the chart, use:
plotOptions: {
line: {
dataLabels: {
enabled:showDataLabels,
color: '#000000',
formatter: function() {
return Highcharts.numberFormat(this.y, 2);
}
}
}
},

Use Formatter fucntion in dataLables
formatter: function () {
if(this.y!=0)
return this.y;
else`enter code here`
return "";
}

Related

How to see truncated text with hover in highcharts?

I'm using the highcharts-react-official package and sometimes my charts have texts that are long enough to be truncated. In those cases the texts end with "...".
I would like to be able to see the full text if I hover the mouse over it. Is that possible somehow?
Edited: See the picture. The truncated text is the third one from the top.
Edited: I actually found out that the "tooltip" option can fix this, but I wonder if it's possible to configure the tooltip so that it only appears if the text is truncated?
My chart
The possible solution is to set custom "ellipsis" in formatter, according to the length of the label text.
dataLabels: {
enabled: true,
inside: true,
formatter: function() {
let name = this.key;
if (name.length > 10) {
name = name.substring(0, 8) + '...';
}
return name;
}
},
Then, you can easily check which label has an abbreviated text. For checking it and setting the tooltip on point hover, use the point.mouseOver() event.
point: {
events: {
mouseOver: function() {
let point = this;
let name = point.options.name;
if (name.length > 10) {
point.series.chart.update({
tooltip: {
enabled: true
}
});
}
},
mouseOut: function() {
this.series.chart.update({
tooltip: {
enabled: false
}
});
}
}
}
API References:
https://api.highcharts.com/highcharts/series.column.events.mouseOver
https://api.highcharts.com/highcharts/series.column.events.mouseOut
Demo:
https://jsfiddle.net/BlackLabel/c4qezstf/

Use series data but display custom text on top of columns Highchart

I'm trying to use highchart, working with colums.
My series data are some hours.
For example, if my data is 23.75, it means 23:45 hours.
I would like to use my 23.75 data so that my colums are in the right place, but the little text on top of my column displays "23:45".
Is it possible ? I can't find the right option to do this.
Thanks in advance !
you can format data label values by formatter
dataLabels: {
enabled: true,
formatter: function () {
return this.y; // you can update datalabel values here
}
}
Found it !
stackLabels: {
enabled: true,
formatter: function() {
return this.total // custom text label here
}
}

How to create custom legend in ChartJS

I need to create custom legend for my donut chart using ChartJS library.
I have created donut with default legend provided by ChartJS but I need some modification.
I would like to have value above the car name. Also I don't like sticky legend I want to have it separate from donut so I can change the style for fonts, boxes (next to the text "Audi" for example)
I know there is some Legend generator but I'm not sure how to use it with VueJS - because I'm using VueJS as a framework
This is how my legend looks like now - http://imgur.com/a/NPUoi
My code:
From Vue component where I import a donut component:
<div class="col-md-6">
<div class="chart-box">
<p class="chart-title">Cars</p>
<donut-message id="chart-parent"></donut-message>
</div>
</div>
Javascript:
import { Doughnut } from 'vue-chartjs'
export default Doughnut.extend({
ready () {
Chart.defaults.global.tooltips.enabled = false;
Chart.defaults.global.legend.display = false;
this.render({
labels: ['Audi','BMW','Ford','Opel'],
datasets: [
{
label: 'Cars',
backgroundColor: ['#35d89b','#4676ea','#fba545','#e6ebfd'],
data: [40, 30, 20, 10]
}
]
},
{
responsive: true,
cutoutPercentage: 75,
legend: {
display: true,
position: "right",
fullWidth: true,
labels: {
boxWidth: 10,
fontSize: 14
}
},
animation: {
animateScale: true
}
})
}
});
I'm having the same problem trying to understand the documentation and this link might clarify the process of customize the legends:
https://codepen.io/michiel-nuovo/pen/RRaRRv
The trick is to track a callback to build your own HTML structure and return this new structure to ChartJS.
Inside the options object:
legendCallback: function(chart) {
var text = [];
text.push('<ul class="' + chart.id + '-legend">');
for (var i = 0; i < chart.data.datasets[0].data.length; i++) {
text.push('<li><span style="background-color:' +
chart.data.datasets[0].backgroundColor[i] + '">');
if (chart.data.labels[i]) {
text.push(chart.data.labels[i]);
}
text.push('</span></li>');
}
text.push('</ul>');
return text.join("");
}
Second, you need a container to insert the new html and using the method myChart.generateLegend() to get the customized html:
$("#your-legend-container").html(myChart.generateLegend());
After that, if you need, track down the events:
$("#your-legend-container").on('click', "li", function() {
myChart.data.datasets[0].data[$(this).index()] += 50;
myChart.update();
console.log('legend: ' + data.datasets[0].data[$(this).index()]);
});
$('#myChart').on('click', function(evt) {
var activePoints = myChart.getElementsAtEvent(evt);
var firstPoint = activePoints[0];
if (firstPoint !== undefined) {
console.log('canvas: ' +
data.datasets[firstPoint._datasetIndex].data[firstPoint._index]);
}
else {
myChart.data.labels.push("New");
myChart.data.datasets[0].data.push(100);
myChart.data.datasets[0].backgroundColor.push("red");
myChart.options.animation.animateRotate = false;
myChart.options.animation.animateScale = false;
myChart.update();
$("#your-legend-container").html(myChart.generateLegend());
}
}
Another solution that I found, if you don't need to change the HTMl structure inside the legend, you can just insert the same HTML in your legend container and customize it by CSS, check this another link:
http://jsfiddle.net/vrwjfg9z/
Hope it works for you.
You can extract the legend markup.
data () {
return {
legendMarkup: ''
}
},
ready () {
this.legendMarkup = this._chart.generateLegend()
}
And in your template you can output it.
<div class="legend" ref="legend" v-html="legendMarkup"></div>
this._chart is the internal chartjs instance in vue-chartjs. So you can call all chartjs methods which are not exposed by vue-chartjs api over it.
However you can also use the legend generator. The usage is the same in vue. You can pass in the options, use callbacks etc.
please check this documentation
.
Legend Configuration
The chart legend displays data about the datasets that area appearing on the chart.
Configuration options
Position of the legend. Options are:
'top'
'left'
'bottom'
'right'
Legend Item Interface
Items passed to the legend onClick function are the ones returned from labels.generateLabels. These items must implement the following interface.
{
// Label that will be displayed
text: String,
// Fill style of the legend box
fillStyle: Color,
// If true, this item represents a hidden dataset. Label will be rendered with a strike-through effect
hidden: Boolean,
// For box border. See https://developer.mozilla.org/en/docs/Web/API/CanvasRenderingContext2D/lineCap
lineCap: String,
// For box border. See https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/setLineDash
lineDash: Array[Number],
// For box border. See https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/lineDashOffset
lineDashOffset: Number,
// For box border. See https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/lineJoin
lineJoin: String,
// Width of box border
lineWidth: Number,
// Stroke style of the legend box
strokeStyle: Color
// Point style of the legend box (only used if usePointStyle is true)
pointStyle: String
}
Example
The following example will create a chart with the legend enabled and turn all of the text red in color.
var chart = new Chart(ctx, {
type: 'bar',
data: data,
options: {
legend: {
display: true,
labels: {
fontColor: 'rgb(255, 99, 132)'
}
}
}
});
Custom On Click Actions
It can be common to want to trigger different behaviour when clicking an item in the legend. This can be easily achieved using a callback in the config object.
The default legend click handler is:
function(e, legendItem) {
var index = legendItem.datasetIndex;
var ci = this.chart;
var meta = ci.getDatasetMeta(index);
// See controller.isDatasetVisible comment
meta.hidden = meta.hidden === null? !ci.data.datasets[index].hidden : null;
// We hid a dataset ... rerender the chart
ci.update();
}
Lets say we wanted instead to link the display of the first two datasets. We could change the click handler accordingly.
var defaultLegendClickHandler = Chart.defaults.global.legend.onClick;
var newLegendClickHandler = function (e, legendItem) {
var index = legendItem.datasetIndex;
if (index > 1) {
// Do the original logic
defaultLegendClickHandler(e, legendItem);
} else {
let ci = this.chart;
[ci.getDatasetMeta(0),
ci.getDatasetMeta(1)].forEach(function(meta) {
meta.hidden = meta.hidden === null? !ci.data.datasets[index].hidden : null;
});
ci.update();
}
};
var chart = new Chart(ctx, {
type: 'line',
data: data,
options: {
legend: {
}
}
});
Now when you click the legend in this chart, the visibility of the first two datasets will be linked together.
HTML Legends
Sometimes you need a very complex legend. In these cases, it makes sense to generate an HTML legend. Charts provide a generateLegend() method on their prototype that returns an HTML string for the legend.
To configure how this legend is generated, you can change the legendCallback config property.
var chart = new Chart(ctx, {
type: 'line',
data: data,
options: {
legendCallback: function(chart) {
// Return the HTML string here.
}
}
});

Highcharts: Format all numbers with comma?

I'm using Highcharts and I want to format all numbers showed anywhere in the chart (tooltips, axis labels...) with comma-separated thousands.
Otherwise, the default tooltips and labels are great, and i want to keep them exactly the same.
For example, in this chart, the number should be 2,581,326.31 but otherwise exactly the same.
How can I do this?
I tried adding:
tooltip: {
pointFormat: "{point.y:,.0f}"
}
But this got rid of the nice circle and series label in the tooltip - I'd like to keep that. And ideally I'd prefer to use a single option to set global number formatting, across the whole chart.
This can be set with the thousandSep (API) global option.
Highcharts.setOptions({
lang: {
thousandsSep: ','
}
});
See this JSFiddle example.
This way worked with me.
I configured in yAxis option.
yAxis: {
labels: {
formatter: function() {
return Highcharts.numberFormat(this.value, 2);
}
}
}
In case you want to show numbers without commas and spaces.
eg. by default 9800 shows as 9 800.
If you want 9800 to be shown as 9800
you can try this in tooltip:
tooltip: {
pointFormat: '<span>{point.y:.f}</span>'
}
This way work for me.
I use Angular 10 and I did this for Tooltip and yAxis.
for yAxis use numberFormat:
labels: {
format: '{value}',
style: {
color: Highcharts.getOptions().colors[0]
},
formatter: function() {
return Highcharts.numberFormat(this.value, 3);
}
},
and for Tooltip :
{point.y:.f}

Highcharts - Adding tooltip to ONLY certain dynamically added series

Using highcharts, I am adding multiple series to an exist chart. When adding the series I need to be able to set tooltip on or off depending on the series added.
Here is where I am at:
widget.chart.addSeries({
data: newSeries,
color: color,
tooltip: {
enabled: true,
formatter: function() {
return 'test';
}
}
});
Try this.
Inside chart options.
tooltip: {
formatter: function() {
var text = false;
if(this.series.name == "GOOG") {
// just an example of serie name
// you can use index or other data too
text = 'test';
}
return text;
}
}
demo

Categories

Resources