Add additional tooltip from from JSON Array - highcharts

I have a JSON array like this:
chart_data = [
{category: 'A', per: '0.74', total: 10294, in: 5651, out: 5661},
{category: 'B', per: '0.72', total: 10294, in: 5556, out: 7751},
{category: 'C', per: '0.68', total: 10294, in: 5598, out: 5991},
{category: 'D', per: '0.54', total: 10294, in: 6551, out: 5001}
]
now I am showing the data in the column chart where I am using per column chart data where in Highcharts the only tooltip visible is "per" but I want to show "total, in, out" all of them in the tooltip.
Here's my HighChart Code:
plotColumnChart(chart_data:any, chart_config: any){
let columnChartSeries = [];
let categories = [];
let columnChartData = {
exporting: {
chartOptions: { // specific options for the exported image
plotOptions: {
series: {
dataLabels: {
enabled: true
}
}
}
},
fallbackToExportServer: false
},
chart: {
type: 'column',
borderColor: '#c1e1c182',
borderWidth: 1,
borderRadius: 5,
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false,
},
title: {
text: chart_config['name'],
x: -20,
style: {
color: '#0D6ABF',
fontWeight: 'bold'
}
},
credits: {
enabled: false
},
legend: {
enabled: false,
},
xAxis: {
categories: chart_data.map(function(point:any){
return [(<any>Object).values(point)[0]]
}),
title: {
text: null
},
gridLineColor: '#ffffff',
},
yAxis: {
min: 0,
tickInterval: 20,
max:100,
gridLineColor: '#ffffff',
title: {
text: null,
align: null
},
labels: {
overflow: 'justify'
}
},
tooltip: {
shared: false,
backgroundColor: 'black',
borderColor: 'black',
borderRadius: 10,
style: {
color: 'white'
},
useHTML: true,
borderWidth: 3,
headerFormat: '<b style="color: #fff;">{point.x}</b><br/>',
formatter: function() {
}
},
plotOptions: {
series: {
dataLabels: {
enabled: true,
distance: "-80%",
pointFormat: '{point.y}%',
},
},
column: {
pointPadding: 0.5,
borderWidth: 0,
showInLegend: true,
zones:[{
value: chart_config['color-format'][0], // Values up to 50 (not including) ...
color: '#FA5F55' // ... have the this color.
},
{
value: chart_config['color-format'][1], // Values up to 60/70 (not including) ...
color: '#FFBF00' // ... have the this color.
},
{
color: '#98FB98' // Values greater than 70 ... have the this color.
}
],
}
},
series: [
{
name: '', //chart_config['name'],
color: '', //'#98FB98',
pointWidth: 20,
data: chart_data.map(function(point:any){
return [
Number(
(
parseFloat(
(<any>Object).values(point)[1]
)*100
).toFixed(0)
)
]
})
},
]
} as any;
Highcharts.chart(chart_config['id'], columnChartData);
}
And chart_config = {"id": 'column-chart', "name": 'ABC', 'color-format': [50, 70]};
Can anybody help me to achieve this by writing a formatter function for this?

There is no possibility to get other values from the chart level if you don't provide them in the data. In your example, only "per" value is passed to the series.data . After parsing data to the relevant format, you will also need to define series.keys in order to have access to these options.
//Data parsing to the two dimensional array
let new_chart_data = [];
chart_data.forEach(data => {
data.per = Number(data.per)
new_chart_data.push([data.category, data.per, data.total, data.in, data.out])
})
//Chart
Highcharts.chart('container', {
tooltip: {
pointFormatter: function() {
console.log(this.options)
return `<b>Per:</b> ${this.y}</br><b>Total:</b> ${this.total}</br><b>In:</b> ${this.in}</br><b>Out:</b> ${this.out}</br>`
}
},
series: [{
type: 'column',
keys: ['name', 'y', 'total', 'in', 'out'],
pointWidth: 20,
data: new_chart_data
}]
});
API Reference:
https://api.highcharts.com/highcharts/series.column.keys
Demo:
https://jsfiddle.net/BlackLabel/3dh2m79c/

Something like this?
public formatter(row): string {
return row ? `${row.per}, ${row.in}, ${row.out}` : null;
}

Related

How to detect when dataLabels are overlapping and adjust them programmatically

I have a stacked column/scatter chart with some dataLabels off to one side. The issue I am facing is that when my two markers begin to get close to one another, their dataLabels overlap
I need to always show both labels, so is there a way to detect when labels are overlapping and move the bottom one down by adjusting its y value based on how much overlap there is?
sample fiddle of the issue
Highcharts.chart('container', {
chart: {
type: 'column',
width: 500
},
title: {
text: 'Stacked column chart'
},
xAxis: {
visible: false,
},
yAxis: {
min: 0,
visible: false,
title: {
},
},
legend: {
layout:"vertical",
align: "right",
verticalAlign: "bottom",
itemMarginTop: 15,
y: -10,
x: -50
},
tooltip: {
enabled: false,
},
plotOptions: {
scatter: {
marker: {
symbol: "triangle",
},
dataLabels: {
enabled: true,
x: -80,
y: 50,
allowOverlap: true,
useHTML: true,
}
},
column: {
pointWidth: 70,
stacking: 'normal',
dataLabels: {
enabled: false
}
}
},
series: [{
name: '',
data: [100],
color: "#ededed"
}, {
name: '',
data: [500]
}, {
name: '',
data: [400]
},
{
type: "scatter",
data: [1000],
color: "#000",
dataLabels: {
formatter: function(){
return "<div class='label-text'>Your goal of <br/>$"+ this.y +"<br/>text</div>"
},
}
},
{
type: "scatter",
data: [900],
color: "#000",
dataLabels: {
formatter: function(){
return "<div class='label-text'>You are here <br/>$"+ this.y +"<br/>text</div>"
},
}
}]
});
You can correct data-labels positions by using the attr method on their SVG elements.
For example:
chart: {
events: {
render: function() {
const series = this.series;
const dl1 = series[3].points[0].dataLabel;
const dl2 = series[4].points[0].dataLabel;
if (dl1.y + dl1.height > dl2.y) {
dl2.attr({
y: dl1.y + dl1.height
});
}
}
}
}
Live demo: https://jsfiddle.net/BlackLabel/5Lmh4owb/
API Reference:
https://api.highcharts.com/class-reference/Highcharts.SVGElement.html#attr
https://api.highcharts.com/highcharts/chart.events.render

Highcharts bar chart configuration to increase height and round edges

In an Angular 4 project I am using the angular2-highcharts library to create a stacked bar chart. The following object is the configuration I have so far.
{
title: { text: '' },
xAxis: {
categories: [''],
crosshair: true,
visible: false
},
yAxis: {
min: 0,
max: 100,
title: {
text: ''
},
labels: {
enabled: true
},
visible: false
},
chart: {
type: 'bar',
backgroundColor: 'rgba(255, 255, 255, 0.1)'
},
legend: {
enabled: false
},
plotOptions: {
column: {
pointPadding: 0,
borderWidth: 0,
stacking: 'normal',
dataLabels: {
enabled: true,
formatter: function() {
return this.point.y + '%';
},
inside: true
},
enableMouseTracking: false,
},
series: {
stacking: 'normal',
dataLabels: {
enabled: true,
formatter: function () {
if (this.point.y) {
return this.point.y + '%';
}
return '';
},
style: { fontSize: '10px' },
padding: 10
},
borderWidth: 0
}
},
series: [{
name: 'Pending',
data: ...,
color: '#ff4233'
}, {
name: 'Executed',
data: ...,
color: '#34d788'
}, {
name: 'Cancelled',
data: ...,
color: '#8f8c87'
}]
}
and this produces this visual result ->
I need to transform this into ->
As you see in the desired result the chart has more height and also its edges are round. That I don't know how to do.
Have you tried to use rounded-corners plugin? With it you can use following properties:
borderRadiusTopLeft, borderRadiusTopRight, borderRadiusBottomRight and borderRadiusBottomLeft
Plugin Reference:
https://github.com/highcharts/rounded-corners
Example:
http://jsfiddle.net/3Lhzx8ao/

Highcharts change legend of only last stacked value

I have a highchart, as showed on the appended image.
I am attempting to format the legend of only my last data stacked. In this case, index 1 always.
Any help on how to achieve this?
My main goal, being, on there always showing a value i have in a variable, which will be the max value possible.
createChart: function (id, chartData, maxYValues, chartTitle, chartNames, dataToMax) {
var me = this;
debugger;
me.highChart = new Highcharts.Chart({
chart: {
type: 'column',
renderTo: id
},
title: {
text: chartTitle,
fontSize: '8px'
},
xAxis: {
labels: {
overflow: 'justify'
},
categories: chartNames
},
yAxis: {
gridLineWidth: 0,
minorGridLineWidth: 0,
labels: {
enabled: false
},
stackLabels: {
enabled: true,
format: maxYValues
},
title: {
enabled: false
}
},
colors: ['#afafaf', '#f89c1c', '#3aaa80'],
credits: {
enabled: false
},
tooltip: {
pointFormat: '<span>{point.name}</span>'
},
plotOptions: {
series: {
colors: ['#3aab80', '#3aab80'],
colorByPoint: true,
borderWidth: 0,
dataLabels: {
enabled: true,
headerFormat: '{point.y + point.name}',
format: '{y} mb',
verticalAlign: 'top',
y: -20
}
},
column: {
stacking: "percent"
},
area: {
dataLabels: {
enabled: false
}
}
},
legend: {
labelFormat: '<b>{point.y} MB</b><br/>',
labelFormatter: function () {
if (me.series.data.index === 1) {
return maxYValues;
}
}
},
series: [{
showInLegend: false,
data: chartData,
color: '#3aab80'
}, {
showInLegend: false,
data: dataToMax,
legend: {
labelFormat: maxYValues + 'MB</b><br/>'
}
}],
navigation: {
menuItemStyle: {
fontSize: '8px'
}
}
});
},
Thank you
UPDATE: Added code snipped, and updated the image to what my current code is showing

how do I get two highcharts on one page?

I have two charts that I am trying to load on separate div's on the same page, they are similar but one is a drill down and the other isn't. I have tried wrapping the entire function with var chart = $('#review').highcharts({ but it doesn't work.
The two charts are below:
$(function () {
var colors = Highcharts.getOptions().colors,
categories = ['Metric 1', 'Metric 2', 'Metric 3','metric 4'],
name = 'Votes',
data = [{
y: 1,
color: colors[0],
}, {
y: 2,
color: colors[1],
}, {
y: 3,
color: colors[2],
},{
y: 5,
color: colors[3],
}];
function setChart(name, categories, data, color) {
chart.xAxis[0].setCategories(categories, false);
chart.series[0].remove(false);
chart.addSeries({
name: name,
data: data,
color: color || 'white'
}, false);
chart.redraw();
}
var chart = $('#review').highcharts({
chart: {
type: 'column'
},
title: {
text: 'Review breakdown'
},
xAxis: {
categories: categories
},
tooltip: {
formatter: function() {
var point = this.point,
s = this.x +'<br><b>'+ this.y +' stars</b><br/>';
return s;
}
},
series: [{
name: name,
data: data,
color: 'white'
}],
exporting: {
enabled: false
},
legend: {
enabled: false
},
credits: {
enabled: false
}, yAxis: {min: 0, max: 5,
title: {text: 'Star Rating'}
}
})
.highcharts(); // return chart
});
$(function () {
var colors = Highcharts.getOptions().colors,
categories = ['positive', 'negative', 'sum'],
name = 'Votes',
data = [{
y: 55.11,
color: colors[0],
drilldown: {
name: 'Positive votes',
categories: ['Users', 'Admin', 'Anonymous'],
data: [10.85, 7.35, 33.06],
color: colors[0]
}
}, {
y: -7.15,
color: colors[3],
drilldown: {
name: 'Negative votes',
categories: ['Users', 'Admin', 'Anonymous'],
data: [-4.55, -1.42, -0.23],
color: colors[3]
}
}, {
y: 2.14,
color: colors[4],
drilldown: {
name: 'Total votes',
categories: ['Users', 'Admin', 'Anonymous'],
data: [ 0.12, 0.37, 1.65],
color: colors[4]
}
}];
function setChart(name, categories, data, color) {
chart.xAxis[0].setCategories(categories, false);
chart.series[0].remove(false);
chart.addSeries({
name: name,
data: data,
color: color || 'white'
}, false);
chart.redraw();
}
var chart = $('#votes').highcharts({
chart: {
type: 'column'
},
title: {
text: 'Vote breakdown'
},
subtitle: {
text: 'Click the columns to view breakdown.'
},
xAxis: {
categories: categories
},
yAxis: {
title: {
text: 'Total votes'
}
},
plotOptions: {
column: {
cursor: 'pointer',
point: {
events: {
click: function() {
var drilldown = this.drilldown;
if (drilldown) { // drill down
setChart(drilldown.name, drilldown.categories, drilldown.data, drilldown.color);
} else { // restore
setChart(name, categories, data);
}
}
}
},
dataLabels: {
enabled: true,
color: colors[0],
style: {
fontWeight: 'bold'
}
}
}
},
tooltip: {
formatter: function() {
var point = this.point,
s = this.x +':<b>'+ this.y +' votes</b><br/>';
if (point.drilldown) {
s += 'Click to view '+ point.category +' breakdown';
} else {
s += 'Click to return';
}
return s;
}
},
series: [{
name: name,
data: data,
color: 'white'
}],
exporting: {
enabled: false
},
legend: {
enabled: false
},
credits: {
enabled: false
},
})
.highcharts(); // return chart
});
If you're trying to get two charts on one page then it is VERY simple.
<div id="chart-A" class="chart"></div>
<div class="spacer"></div>
<div id="chart-B" class="chart"></div>
CSS - Just to make the example a little easier on the eyes
.chart {
height: 200px;
}
.spacer {
height: 20px;
}
JavaScript
$(function() {
// If you need to specify any global settings such as colors or other settings you can do that here
// Build Chart A
$('#chart-A').highcharts({
chart: {
type: 'column'
},
title: {
text: 'Chart A'
},
xAxis: {
categories: ['Jane', 'John', 'Joe', 'Jack', 'jim']
},
yAxis: {
min: 0,
title: {
text: 'Apple Consumption'
}
},
legend: {
enabled: false
},
credits: {
enabled: false
},
tooltip: {
shared: true
},
series: [{
name: 'Apples',
data: [5, 3, 8, 2, 4]
}]
});
// Build Chart B
$('#chart-B').highcharts({
chart: {
type: 'column'
},
title: {
text: 'Chart B'
},
xAxis: {
categories: ['Jane', 'John', 'Joe', 'Jack', 'jim']
},
yAxis: {
min: 0,
title: {
text: 'Miles during Run'
}
},
legend: {
enabled: false
},
credits: {
enabled: false
},
tooltip: {
shared: true
},
series: [{
name: 'Miles',
data: [2.4, 3.8, 6.1, 5.3, 4.1]
}]
});
});
Here's a JSFiddle: http://jsfiddle.net/engemasa/7cvCX/
I am not really sure what some of your code is trying to do - seems a little needlessly complicated, FWIW
AS to how to make multiple charts on the same page - you do it just like you would make one chart on a page, just do it more than once :)
and make sure you have different container element ids - otherwise you are just overwriting one chart with the next.
One example of multiple charts on a page:
http://jsfiddle.net/kwtZr/1/
there's no relevant code to put here, just click the link

remove grid line on chart

I have the charts of lib HighCharts and I want to remove the gridline of yAxis on charts
I write gridLineWidth: 0
but gridlines are not removing
All code:
<script type="text/javascript">
(function($){ // encapsulate jQuery
$(function() {
Highcharts.setOptions({
lang: {
rangeSelectorZoom: 'Маcштаб',
rangeSelectorFrom: 'От',
rangeSelectorTo: 'До',
thousandsSep: ' '
},
global: {
useUTC: false
}
});
$.getJSON('http://www.highcharts.com/samples/data/jsonp.php?filename=aapl-c.json&callback=?', function(data) {
// Create the chart
window.chart = new Highcharts.StockChart({
chart : {
borderColor: 'white',
renderTo : <?php echo "cont".$i; ?>,
backgroundColor: '#f9f9f9' // Сделаем слегка серый фон
},
rangeSelector: {
buttons: [
{
type: 'week',
count: 1,
text: 'Неделя',
},
{
type: 'month',
count: 1,
text: 'Месяц',
},
{
type: 'year',
count: 1,
text: 'Год'
},
{
type: 'all',
text: 'Всё'
}],
inputDateFormat: '%d.%m.%Y', // Меняем на привычный для нас формат даты в интервалах
inputEditDateFormat: '%d.%m.%Y',
buttonTheme: {
width: 43 // Увеличим ширину кнопки
},
selected: 1 // Какая кнопка выбрана по умолчанию
},
yAxis: [{
gridLineWidth: 0,
plotBands: [{
color: 'rgba(1, 143, 189, 1)',
from: -2,
to: 11
},
{
color: 'rgba(157, 200, 5, 1)',
from: 11,
to: 21
},
{
color: 'rgba(202, 1, 94, 1)',
from: 21,
to: 50
}],
title: {
text: 'Позиции'
},
startOnTick: false,
// min: 1,
showFirstLabel: true,
showLastLabel: true,
reversed: true,
tickPositioner: function(min, max) {
// specify an interval for ticks or use max and min to get the interval
var interval = Math.round((max-min)/5);
// push the min value at beginning of array
var dataMin=this.dataMin;
var dataMax=this.dataMax;
var positions = [dataMin];
var defaultPositions = this.getLinearTickPositions(interval, dataMin, max);
//push all other values that fall between min and max
for (var i = 0; i < defaultPositions.length; i++) {
if (defaultPositions[i] > dataMin && defaultPositions[i] < dataMax) {
positions.push(defaultPositions[i]);
}
}
// push the max value at the end of the array
positions.push(dataMax);
return positions;
},
//changed min valuereversed: true
}],
navigator: {
enabled: false,
maskFill: 'rgba(255, 255, 255, 0.45)',
//margin: 20,
series: {
type: 'areaspline',
color: 'rgba(255, 255, 255, 0.00)',
fillOpacity: 0.4,
dataGrouping: {
smoothed: false
},
lineWidth: 2,
lineColor: '#e9cc00',
marker: {
enabled: false
},
shadow: true
},
yAxis: {
reversed: true
}
},
xAxis : {
gridLineWidth: 0,
type: 'datetime',
title : {
text : ' '
},
},
title : {
//text : 'Позиции сайта'
},
legend: {
enabled: true,
align: 'center',
itemWidth: 234, // указал ширину, чтобы выводились сайты в 4 колонки
verticalAlign: 'top'
},
series : [{
lineColor: 'white',
name : 'Позиция в яндексе',
id : 'dataseries',
data : <?php echo $d ?>,
tooltip: {
backgroundColor: 'rgba(250, 250, 250, .85)', // Фон немного темнее
borderColor: 'rgba(100, 100, 100, .90)', // Цвет границы (по умолчанию меняется автоматом)
xDateFormat: '%d.%m.%Y %H:%M', // Наш формат даты
// Тут немного увеличиваем размер даты
headerFormat: '<span style="font-size: 12px">{point.key}</span><br/>',
// Формат надписей в подсказке, названия цветом графика, а значения жирным
pointFormat: '<span style="color:{series.color}">{series.name}</span>: <b>{point.y}</b><br/>',
//valueDecimals: 2
}
}]
});
});
});
})(jQuery);
</script>
The problem is not the gridLineWidth. You've set that correctly.
In addition you need to set the minorGridLineWidth that you have to set to 0
Working demo
If you doesn't want to touch the config object, you just hide the grid by css:
.chart-container .highcharts-grid {
display: none;
}
you just need to gridLineWidth set to 0
yAxis: {
min:0,
categories: ["","Low","Medium","High"],
tickWidth: 0,
crosshair: false,
lineWidth: 0,
gridLineWidth:0,//Set this to zero
title: '',
labels: {
formatter: function () {
return this.value;labels
}
},
showEmpty: false
}
None of the mentioned solutions worked for me, so this one finally worked (taken from Sparklines examples: https://www.highcharts.com/demo/sparkline):
yAxis: {
startOnTick: false,
endOnTick: false,
tickPositions: [],
}
for all other lines here is what worked for me, in some cases using line transparency as the color was the only solution I could find.
$(function() {
$('#container').highcharts({
colors: ['#00f900', '#ffff3c', '#ff2600'],
credits: {
enabled: false
},
exporting: {
enabled: false
},
legend: {
itemDistance: 60
},
lineColor: 'red',
chart: {
type: 'column',
backgroundColor: 'transparent'
},
title: {
text: ''
},
legend: {
itemStyle: {
color: 'white',
fontWeight: 'normal',
fontFamily: 'helvetica',
fontSize: '12px'
}
}
// ....rest in js fiddle
http://jsfiddle.net/fv50sLkj/23/

Resources