Multiline Legend Label with Pie Chartjs - javascript

I'm trying to have multiline labels with a pie chart on ChartJS. I've read on multiple questions that using an array of strings should get the job done, yet I'm not seeing it. My code is as follows:
var ctx = document.getElementById("pie-inversiones");
window.myBar = new Chart(ctx, {
type: 'pie',
data: pieInversiones,
options: {
legend: {
position: 'left',
onClick: function (e) {
e.stopPropagation();
},
labels: {
fontColor: "#15467D",
fontFamily: "Neo Sans Std",
fontSize: 10
}
},
animation: {
animateRotate: getParameterByName("action") == "print" ? false : true
},
plugins: {
datalabels: {
color: '#15467D',
anchor: "end",
align: "end",
formatter: (value, ctx) => {
return value + "%";
}
}
}
},
});
With the data object having two properties, dataset (data with the background color) and labels, which is just an array of arrays, each having 1+ strings in it.
Most questions I see ask about bar charts, how would I go about achieving this on a pie one?
Here's an example of the code I'm using https://jsfiddle.net/04zcy2hu/

Related

Chart.js - Override inherited colors when coloring graphs

I'm creating graphs with ChartJS, but they seem to inherit the default colors of some parent element. The graphs look like this:
I am dynamically creating the charts, depending on selections from the user. The ChartJS chart takes in an array of either primitives, or objects to use as the chart data. I'm using the following function to create the chart objects, and then using an array of these objects as the parameter for ChartJS:
function getChartDataObject(data){
var title = data['metadata']['title'];
var color = random_rgba();
console.log(`Color: ${color}`);
var dataObject = {
label: title,
data: data['scaled_interval'],
color: color,
fill: false,
lineTension: 0,
radius: 1,
}
return dataObject;
}
Then I create the master chart with this function:
function createIntervalChart(intervalDataObjects, datetimeInterval) {
const cnvs = document.createElement('canvas');
const ctx = $(cnvs);
var data = {
labels: datetimeInterval,
datasets: intervalDataObjects,
}
var options = {
responsive: true,
title: {
display: true,
position: "top",
text: "Projected Load Profiles",
fontSize: 18,
fontColor: "#111",
},
legend: {
display: true,
position: "bottom",
labels: {
fontColor: "#333",
fontSize: 16
}
},
elements: {
point: {
radius: 0
}
},
plugins: {
zoom: {
zoom: {
wheel: {
enabled: true
},
pinch: {
enabled: true
},
mode: 'xy',
}
},
title: {
text: "Estimated Load Profiles"
}
}
};
var chart = new Chart(ctx, {
type: "line",
data: data,
options: options
});
return cnvs;
}
When I check the console, I see distinct colors created by the random_rgb() function, but they all turn out grey.
Color: rgba(215,231,183,0.6)
Color: rgba(253,61,199,0.1)
Color: rgba(27,15,88,0.1)
Does anyone know how to create a ChartJS chart with custom colors? Or how to override inherited styling for these charts? Thank you
color is not a valid dataset property for a line chart. Use borderColor and optionally also backgroundColor (will be used for drawing the legend label box).
function getChartDataObject(data){
var title = data['metadata']['title'];
var color = random_rgba();
console.log(`Color: ${color}`);
var dataObject = {
label: title,
data: data['scaled_interval'],
borderColor: color, // <- to be changed
fill: false,
lineTension: 0,
radius: 1,
}
return dataObject;
}
For further information, please consult Dataset Properties from the Chart.js documentation.

Changing tootip data on pie chart in highcharts

I have been trying to edit the pie chart on this website using the config method:
Change colours (working)
Show legend (working)
Click legend to activate chart section (working)
Donut sizing (working)
Tooltip different data (not working)
Legend showing percentages (not working)
I can't, for the life of me, get the legend to show the percentages and I can't get the tooltip data to change.
Currently, the tooltip says, for example:
Australian equities
Percentage: 40%
I need the tooltip to say:
Australian equities: 40%
Currently, the legend says, for example:
Australian equities
I need the legend to say:
40% Australian equities
<script type="text/javascript">
jQuery(window).on('load',function(){
if( typeof wpDataChartsCallbacks == 'undefined' ){ wpDataChartsCallbacks = {}; }
wpDataChartsCallbacks[1] = function(obj){
obj.options.plotOptions = {
series: {
dataLabels: {
enabled: false
}
},
pie: {
colors: [
'#006769',
'#00b8af',
'#28c3e8',
'#0ee4da',
'#2a97a6'
],
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: false
},
size: 340,
innerSize: '50%',
showInLegend: true,
point: {
events: {
legendItemClick: function () {
this.select();
return false;
}
}
}
},
tooltip: {
formatter: function() {
return this.point.name + ': <b>' + Highcharts.numberFormat(this.y, 1) +'%</b>';
}
},
legend: {
labelFormatter: function() {
return '<strong style="display:inline-block;width:45px;">'+Highcharts.numberFormat(this.y, 1) +'%</strong> ' + this.name ;
},
title: {
style: {
fontSize: '18px',
fontFamily: "'neuzeit-grotesk', sans-serif",
color: '#20242b'
},
text : 'By industry'
},
squareSymbol: true,
},
};
};
});
</script>
This chart is feeding from a locally stored excel spreadsheet to reflect live data which is why the config method must be used.
I have read other threads and the highcharts forums but when I copy the codes into the above it still doesn't change the legend and tooltop.
Any help would be greatly appreciated.
You should implement legend and tooltip configuration on the highest level:
{
...,
tooltip: {
formatter: function() {
...
}
},
legend: {
labelFormatter: function() {
...
},
...
}
}
Live demo: http://jsfiddle.net/BlackLabel/9sp4m1cf/
API Reference:
https://api.highcharts.com/highcharts/tooltip.formatter
https://api.highcharts.com/highcharts/legend.labelFormatter

How to display several labels in Highchart.js?

I have basic Waterfall chart (HighChart.js) basic Waterfall chart image example
How display two labels on each column? Besides, first label must be at top of column and another label must be on bottom of column. So it should be exactly like on image.
Now I have two ideas:
First label is rendered on first chart, second value will be rendered on additional hidden chart (link to example: [http://jsfiddle.net/gk14kh3q/1/][3])
$(function () {
$('#container').highcharts({
chart: {
type: 'waterfall'
},
title: {
text: 'Highcharts Waterfall'
},
xAxis: {
type: 'category'
},
yAxis: {
title: {
text: 'USD'
}
},
legend: {
enabled: false
},
series: [{
dataLabels: {
enabled: true,
// here need align label
}
}, {
dataLabels: {
enabled: true,
// here need align label
}
}]
});
});
Combine two label in one by using formatting function and useHTML property. And after that set position to labels by using css or external js
May be some others practices exist? I'll be very pleased for help. Even discussion can be usefull. Thank you!
P.S. How I could insert icons to chart like on provided image?
You can use chart.renderer.label for adding new dataLabels for your column points. You can also use chart.renderer.image for adding arrows to your chart:
var addLabels = function(chart) {
$('.custom').remove();
var series = chart.series[0],
url;
Highcharts.each(series.data, function(p, i) {
if (i) {
chart.renderer.label(p.secondLabel, p.plotX + chart.plotLeft, p.yBottom + chart.plotTop).attr({
'text-anchor': 'middle'
}).addClass('custom').add();
if (p.y > 0) {
url = 'https://upload.wikimedia.org/wikipedia/commons/thumb/d/d1/Arrow_up.svg/1000px-Arrow_up.svg.png';
} else {
url = 'https://upload.wikimedia.org/wikipedia/en/f/f1/Down_Arrow_Icon.png'
}
chart.renderer.image(url, p.plotX + chart.plotLeft, chart.plotTop + chart.plotHeight - 15, 8, 13).addClass('custom').add()
}
});
};
Here you can find an example how it can work:
http://jsfiddle.net/zc2fb8vt/

Customize Stacked column chart in highChart

I am trying to customize stacked column chart like this
Here i did all the remaining things but i Don't know how to give that bar lines above every column........I need that bar lines in both positive and negative axis
My code
$(document).ready(function () {
$('#div1').highcharts({
chart: { type: 'column', backgroundColor: 'transparent' },
title: { text: null },
subtitle: { text: null },
credits: {
enabled: false
},
xAxis: {
categories: categories,
labels: {
rotation: 0,
style: {
fontWeight: 'normal',
fontSize: '0.9vw',
fontFamily: 'Verdana, sans-serif',
color: "black"
}
}
},
yAxis: {
title: {
enabled: false
},
lineWidth: 0,
gridLineWidth: 1,
labels: {
enabled: true
},
// gridLineColor: 'transparent',
plotLines: [{
color: '#ddd',
width: 1,
value: 0
}],
},
plotOptions: {
series: {
stacking: 'normal'
}
},
series:seriesforSeniorUPT
});
});
});
Link
Fiddle
To elaborate on Sebastian Bochan's helpful comment, here's an updated version of your fiddle with two "dummy" series to serve as the patterned background: https://jsfiddle.net/brightmatrix/hc8rLy18/2/
A few items to note:
There are two "dummy" series: one for the positive numbers and one for the negative numbers.
Both series have showInLegend and enableMouseTracking set to false so the user cannot interact with them.
Both series have stacking set to false so they will not be part of the "real" data you want to show.
Both series have zIndex set to 0. I explain why below the code block.
The code for the "dummy" series is as follows.
// background for positive values
obj = {};
obj["name"] = 'patternFill';
obj["data"] = [120, 120];
obj["color"] = 'url(#highcharts-default-pattern-3)';
obj["grouping"] = false;
obj["zIndex"] = 0;
obj["enableMouseTracking"] = false;
obj["stacking"] = false;
obj["showInLegend"] = false;
seriesforSeniorUPT.push(obj);
// background for negative values
obj = {};
obj["name"] = 'patternFill';
obj["data"] = [-80, -80];
obj["color"] = 'url(#highcharts-default-pattern-3)';
obj["grouping"] = false;
obj["zIndex"] = 0;
obj["enableMouseTracking"] = false;
obj["stacking"] = false;
obj["showInLegend"] = false;
seriesforSeniorUPT.push(obj);
For the three "real" data series, I set zIndex to 10 to they will appear over the "dummy" series we're using for our patterend backgrounds.
For all of the series, I set grouping to false so they will appear one atop the other, not next to one another.
Here's a screenshot of the output. I hope this is helpful!

Highcharts X-Axis New Values

I am using highcharts to draw a column chart as following:
var chart;
var count = 0;
$(function () {
$(document).ready(function() {
chart = new Highcharts.Chart({
chart: {
renderTo: 'graph',
type: 'column',
margin: [ 50, 50, 100, 80]
},
title: {
text: 'Random Data'
},
xAxis: {
categories: [
'T1',
'T2'
],
startOnTick: true,
endOnTick: true,
labels: {
rotation: -45,
align: 'right',
style: {
fontSize: '13px',
fontFamily: 'Verdana, sans-serif'
}
}
},
yAxis: {
min: 0,
title: {
text: 'Y-Axis'
}
},
legend: {
enabled: false
},
tooltip: {
formatter: function() {
return '<b>'+ this.x +'</b><br/>'+
'Tip is: '+ Highcharts.numberFormat(this.y, 1);
}
},
series: [{
name: 'Population',
data: [34.4, 21.8],
dataLabels: {
enabled: true,
rotation: -90,
color: '#FFFFFF',
align: 'right',
x: 4,
y: 10,
style: {
fontSize: '13px',
fontFamily: 'Verdana, sans-serif'
}
}
}]
});
});
});
I added the following function in order to add new points to the chart
function addPoints(name,acc)
{
var series = chart.series[0];
series.addPoint(acc, false, true);
categories = chart.xAxis[0].categories;
categories.push(name+count);
count++;
chart.xAxis[0].setCategories(categories, false);
chart.redraw();
}
The problem is that everytime I add a new point, one column shifts out of the chart. I would like to keep all columns in the chart view, so when I add a new point the chart just zooms out.
Check it on JSFiddle
Thanks in Advance ....
addPoint (Object options, [Boolean redraw], [Boolean shift], [Mixed animation])
Add a point to the series after render time.
Parameters
options: Number|Array|Object
The point options. If options isa single number, a point with that y value is appended to the series.If it is an array, it will be interpreted as x and y values respectively, or inthe case of OHLC or candlestick, as [x, open, high, low, close]. If it is an object, advanced options as outlined under series.data are applied.
redraw: Boolean
Defaults to true. Whether to redraw the chart after the point is added. When adding more thanone point, it is highly recommended that the redraw option beset to false, and instead chart.redraw() is explicitly calledafter the adding of points is finished.
shift: Boolean
Defaults to false. When shift is true, one point is shifted off the start of the series as one is appended to the end. Use this option for live charts monitoring a value over time.
animation: Mixed
Defaults to true. When true, the graph will be animated with default animationoptions. The animation can also be a configuration object with properties durationand easing.
series.addPoint(acc, false, true);
/\ here's the problem, it should be false
Reference
http://api.highcharts.com/highstock#Series
Updated demo

Categories