How to customize annotation's layout in HighCharts - javascript

I have been using HighCharts extensively for one of my project. Recently I started using Annotation.js along with it.
ALthough, the library works well but I can't configure its usage at all. The link here provides options but they are not working for me
My issues:
I have multiple charts on a page. As soon as I use annotation.js , each of them shows annotation. how do I show them on desired charts. I tried
annotations :[{ enabledButtons : false}]
and
annotationOptions :{ enabledButtons : false}
Both of them had no affect.
2.I want to display the pallette (containing icons like square, circle etc..) at top-right.
I used xValue, yValue attribute,
I used x, y attribute,
I used 'anchorX and anchorY` attribute.
None of the above works for me.
I want just to show the text icon. How can I hide other icons (line, square and circle). Didn't get any way to try for this one.
Am I missing something here. Kindly suggest. My basic way of using chart config is as below:
chart: {
type: chartData.Type.toLowerCase()
//annotations: [],
},
annotationsOptions: {
xValue: 234,
yValue:12
},
title: {
text: chartData.xTitle ? chartData.xTitle : ""
},
xAxis: {
categories: chartData.Categories
},
yAxis: {
allowDecimals: false,
min: 0,
title: {
text: chartData.yTitle ? chartData.yTitle : ""
},
plotLines: [{
value: 0,
width: 1,
color: "#808080"
}]
},
annotations: [{
xValue: 40,
yValue: 15
}],
plotOptions: {
line: {
marker: {
enabled: true
}
}
},
series: chartData['Series'][opt] ? chartData['Series'][opt] : chartData['Series'][opt.replace(/-|\s/g, "")],
}
I have tried annotations inside charts object as well.

You should be able to hide annotations buttons using:
annotationsOptions: {
enabledButtons: false
},
You can use annotationsOptions.buttons for changing the buttons you would like to display. Here you can see the code that will show only text butotn:
annotationsOptions: {
buttons: [{
annotationEvents: {
step: function() {}, // to be called during mouse drag for new annotation
stop: function(e) {
var ann = this,
chart = ann.chart,
index = chart.annotationInputIndex = chart.annotationInputIndex ? chart.annotationInputIndex : 1,
input = document.createElement('span'),
button;
input.innerHTML = '<input type="text" class="annotation-' + index + '" placeholder="Add text"><button class=""> Done </button>';
input.style.position = 'absolute';
input.style.left = e.pageX + 'px';
input.style.top = e.pageY + 'px';
document.body.appendChild(input);
input.querySelectorAll('input')[0].focus();
button = input.querySelectorAll('button')[0];
button.onclick = function() {
var parent = this.parentNode;
ann.update({
title: {
text: parent.querySelectorAll('input')[0].value
}
});
parent.parentNode.removeChild(parent);
};
chart.annotationInputIndex++;
} // to be called after mouse up / release
},
annotation: { // standard annotation options, used for new annotation
anchorX: 'left',
anchorY: 'top',
xAxis: 0,
yAxis: 0,
shape: {
// type: 'text'
}
},
symbol: { // button symbol options
shape: 'text', // shape, taken from Highcharts.symbols
size: 12,
style: {
'stroke-width': 2,
'stroke': 'black',
fill: 'red',
zIndex: 121
}
},
style: { // buton style itself
fill: 'black',
stroke: 'blue',
strokeWidth: 2,
},
size: 12, // buton size
states: { // states for button
selected: {
fill: '#9BD'
},
hover: {
fill: '#9BD'
}
}
}]
}
Here you can find an example how it may work: http://jsfiddle.net/7m3Mr/261/
You can move your buttons using:
annotationsOptions: {
buttonsOffsets: [0, -50],
},
Here you can find demo showing how it may work:
http://jsfiddle.net/7m3Mr/263/

Related

Chart.js - change which data the legend uses for the coloured box

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)
}];
}
}
}
}
}

old yAxis ticks do not get removed (chartjs, react-chartjs-2 wrapper)

When i draw a chart with 4 lines, each with its own data ofc, i programmatically create the options for the LineChart that has 4 Yaxis, first one on the left and the rest on the right side. Now, after the chart is drawn and i de-select some datasources from the list (less lines to draw), the now-obsolete yAxis ticks stay there, even when the chart correctly draws only the selected lines, and the options are updated as well correctly. I cant think of a way to remove them!
I have googled for 2 days and cant find a solution. I am using react in functional style and it makes things more complicated because every advice seems to be in the classic style.
I am using react-chartjs-2 wrapper as well, if this helps.
I am also quite new to react, and asking in Stackoverflow, so please cut me some slack :)
I assume the chart is being re-rendered or something because the amount of lines etc do change.
In the images, the "createYaxis" that is shown in the console.log is the generated yAxes- part of the options object (which is functional otherwise). The problem yAxises are on the right side in red and yellow. Images show before and after situation.
Image of the options-object generated by the code below the img:
var yAxisItems = [];
function createYaxises (num){
var arr = [];
for (var i=0;i<num.length;i++){
if (i===0){
arr.push({
display: true,
id: i,
type: 'linear',
position: 'left',
gridLines: {
display:false,
//color: 'blue'
},
ticks: {
fontColor: lineColourArray[i],
fontSize: 14,
}
})
}
else {
arr.push({
display: true,
id: i,
type: 'linear',
position: 'right',
gridLines: {
display:false,
//color: 'blue'
},
ticks: {
display:true,
fontColor: lineColourArray[i],
fontSize: 14,
}
})
}}
yAxisItems = arr;
console.log("createyaxis arr: " , arr);
console.log("createyaxis: " , yAxisItems); //JSON.stringify(yAxisItems));
}
//get data for selected sensors and set it to chart data
const handleGetSelectedSensorData = function () {
var d = getSelectedSensorData();
console.log("d: ", d);
var dSets = [];
if (d[0]){
d.map((dItem,index)=> {
var newDsetData =[];
if (dItem.data){
dItem.data.map((innerDataItem)=> {
var dSet = {};
dSet.x = innerDataItem.timestamp;
dSet.y = innerDataItem.v;
newDsetData.push(dSet);
})
var newset = {
data: newDsetData,
label: dItem.sensorTag,
borderColor: lineColourArray[index],
fill: false,
pointRadius: 1.5,
backgroundColor:lineColourArray[index],
borderWidth: 2,
showLine: true,
pointHoverRadius: 5,
lineTension: 1,
};
dSets.push(newset);
}})
var dDataTemp = {};
var optionsTemp = new Object();
dDataTemp.datasets =dSets;
//create yaxises only once
createYaxises(dDataTemp.datasets);
//more than one set (TODO)
//console.log("dDataTemp.datasets : ", dDataTemp.datasets)
if (dDataTemp.datasets.length >1){
console.log("dset > 1");
for(var i=0;i< dDataTemp.datasets.length;i++) {
dDataTemp.datasets[i].yAxisID = i;
console.log("setting options");
optionsTemp ={
tooltips: {
enabled: true,
intersect:false,
mode:'x',
callbacks: {
title: function(tooltipItem, data) {
var toSplit = tooltipItem[0].label.split(",");
return (toSplit[0]);
},
label: function (tooltipItem) {
var split = tooltipItem.xLabel.split(',');
//return ( Number(tooltipItem.yLabel).toFixed(3));
return (split[2] + " : " + Number(tooltipItem.yLabel).toFixed(3));
}
},
},
hover: {
mode: 'nearest',
intersect: true,
},
title:{
display:true,
text:'Valittu sensoridata',
fontSize:20
},
legend:{
display:true,
position:'right'
},
scales: {
xAxes: [{
display: true,
type: 'time',
ticks: {
}
}],
yAxes:
yAxisItems
}
}
}
setOptions(optionsTemp);
console.log("options: " , optionsTemp);
setdData(dDataTemp);
}}
else {
console.log("error in handleGetSelectedSensorData()");
}
}
And the Line is just added like this:
<Line data={dData} options = {options} />
Instead of setting display: true set display: 'auto', this will make the axis dissapear as long as there is no dataset visable that is linked to that scale, as soon as a dataset becomes visable that is linked to that scale it will show the scale again.
Doc: https://www.chartjs.org/docs/master/axes/cartesian/#common-options-to-all-axes

Dynamically change startAngle value in HighCharts

I want to dynamically change the startAngle value on my polar chart from JSON 'Wind_direction' value.
The code is below:
$(function() {
$.getJSON('wind_graph.php?callback=?', function(dataWind) {
var direction = Wind_direction;
var polarOptions = {
chart: {
polar: true,
events : {
load : function () {
setInterval(function(){
RefreshDataWind();
}, 1000);
}
}
},
title: {
text: 'Wind Direction'
},
pane: {
startAngle: direction,
},
xAxis: {
tickInterval: 15,
min: 0,
max: 360
},
plotOptions: {
series: {
pointStart: 0,
pointInterval: 30,
},
}
};
// The polar chart
$('#graph-1').highcharts(Highcharts.merge(polarOptions, {
yAxis: {
tickInterval: 5,
min: 0,
max: 25,
visible: false
},
series: [{
type: 'line',
name: 'Direction',
data: [
[0, 0],
[direction, 20]
],
}
]
}));
function RefreshDataWind()
{
var chart = $('#graph-1').highcharts();
$.getJSON('wind_graph.php?callback=?', function(dataWind)
{
var direction = Wind_direction;
chart.series[0].setData([[0,0],[direction, 20]]);
});
}
});
});
In the last function, below 'chart.series[0].setData... I was trying to add something like this:
chart.pane.setStartAngle(direction);
but this throws the error: "Cannot read property 'startAngle' of undefined"
Also was trying another one idea:
polarOptions.pane({ startAngle: direction });
but here is error: "polarOptions.pane is not a function".
So I'm stack. Please for help.
You should be able to update all chart options with Chart.update(). Unfortunately, it looks that it does not have any effect on pane - I reported the issue here.
Now you can update the pane in old-fashioned way - by destroying and creating a new chart - http://jsfiddle.net/highcharts/qhY8C/
The other possibility is trying the workaround - set options for pane, remove the pane and update the axis - it should create a new pane with new options.
const xAxis = chart.xAxis[0];
chart.options.pane.startAngle = 45;
Highcharts.erase(chart.panes, xAxis.pane);
chart.yAxis[0].update(null, false);
xAxis.update();
example: http://jsfiddle.net/v8L381Lj/

Extending Highmaps Side Effect

I am trying to create a dot density map of the state of Florida. While I know that Highmaps doesn't support color axis with mappoints. I extended it and it works but it comes with a side affect. When I click on one of the categories in the legend no hiding occurs. For example if I click on '>10', all values greater than 10 don't hide. When I open up the Chrome debugger it states that: a.setVisible is not a function What can I do to solve this problem. This is a requirement, while it may seem minor. I would appreciate any sort of tips or maybe some sort of example would be perfect. I can't show more code than what is shown. If you need me to explain more about the problem I will be glad to do so.
(function (H) {
H.seriesTypes.mappoint.prototype.axisTypes = [ 'xAxis', 'yAxis', 'colorAxis'];
H.wrap(H.seriesTypes.mappoint.prototype, "translate", function (p) {
p.call(this);
H.seriesTypes.mappoint.prototype.translateColors.call(this);
});
H.seriesTypes.mappoint.prototype.translateColors = H.seriesTypes.heatmap.prototype.translateColors;
H.seriesTypes.mappoint.prototype.colorKey = 'value';
})(Highcharts);
// Initiate the chart
$('#container').highcharts('Map', {
title: {
text: title
},
mapNavigation: {
enabled: false,
},
colorAxis: {
dataClasses: [{
from: 0,
to: 3,
color: "#66FFFF"
}, {
from: 4,
to: 9,
color: "#0099FF"
}, {
from: 10,
color: "#0000FF"
}
]
},
tooltip:
{
enabled: true
}
,
series: [{
mapData: Highcharts.maps['countries/us/us-fl-all'],
name: 'Basemap',
borderColor: '#A0A0A0',
nullColor: 'rgba(200, 200, 200, 0.3)',
showInLegend: false,
},
{
// Specify points using lat/lon
type: 'mappoint',
name: 'A',
turboThreshold: 2000000,
data: p_data,
dataLabels: {
enabled: false
}
},
{
// Specify points using lat/lon
type: 'mappoint',
name: 'B',
turboThreshold: 2000000,
data: m_data,
dataLabels: {
enabled: false
}
},
{
// Specify points using lat/lon
type: 'mappoint',
name: 'C',
turboThreshold: 2000000,
data: h_data,
dataLabels: {
enabled: false
}
}
]});
A sample to play with: http://jsfiddle.net/dlope073/4mabw6zr/2/
Use setVisible method from default map series. Like this: http://jsfiddle.net/4mabw6zr/3
(function (H) {
H.seriesTypes.mappoint.prototype.axisTypes = ['xAxis', 'yAxis', 'colorAxis'];
H.seriesTypes.mappoint.prototype.pointClass.prototype.setVisible = H.seriesTypes.map.prototype.pointClass.prototype.setVisible; // use the same setVisible method as map type.
H.wrap(H.seriesTypes.mappoint.prototype, "translate", function (p) {
p.call(this);
H.seriesTypes.mappoint.prototype.translateColors.call(this);
});
H.seriesTypes.mappoint.prototype.translateColors = H.seriesTypes.heatmap.prototype.translateColors;
H.seriesTypes.mappoint.prototype.colorKey = 'value';
})(Highcharts);

Highcharts stacking bar chart border not displaying on right side

When I create a stacking bar chart, the rightmost 'box' doesn't have the border drawn on the right hand side.
Is there an option or something that I can set in Highcharts to force the white border line to be drawn around the 75% box in the image seen below?
Here is a link to the jsfiddle I used for testing:
http://jsfiddle.net/zKgsF/
Please note: Setting the borderWidth property to higher than 1 works in displaying, but the rightmost border is much thinner than the others. See the image below.
Here is the javascript for the chart:
$(function () {
var chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'bar',
backgroundColor: 'rgba(0,0,0,.3)',
margin: [15,6,15,15],
},
xAxis: {
categories: ['']
},
credits: {
enabled: false
},
yAxis: {
gridLineColor: "#FF0000",
labels:
{
align: 'right',
formatter: function()
{
return this.value + "%";
}
},
},
tooltip: {
formatter: function()
{
return "<b>" + this.series.name + '</b>: ' + this.y + ' (' + Math.round(this.percentage,1) + "%)";
}
},
plotOptions: {
bar: {
animation: false,
stacking: 'percent',
borderWidth: '1',
dataLabels: {
enabled: true,
color: 'white',
formatter: function() {
if (this.percentage < 10)
{
return ""
}
else
{
return Math.round(this.percentage,1) + "%";
}
},
style: {
fontSize: '18px'
}
}
}
},
series: [{
data: [30]
},{
data: [10]
}]
});
});
EDIT:
Looks like it's not related to the bar chart being "stackable". It might just be related to the fact that the chart goes to the max 'y' value axis... as seen here in another example: http://jsfiddle.net/zKgsF/1/
As suggested by Cubbuk, you can tweak it with by adding the max value of yAxis.
In addition, you can specify a endOnTick property too.
max: 100.1,
endOnTick: false
For API navigate here and for here is an example.

Categories

Resources