Echart configuration for Pie legends in a particular way - javascript

I want to display pie legends along with its value in a different format. I am attaching the image. I am looking for it but did not find how to do it till now.
If you see the image, legends and the value corresponding to it are shown that i am unable to replicate.

You want to display value instead percentages? If yes then this is a little work that need to do because by default legend component don't know about another dimensions of you data. Try to start with this code:
var option = {
//...
legend: {
formatter: name => {
var series = myChart.getOption().series[0];
var value = series.data.filter(row => row.name === name)[0].value
return name + ' ' + value;
},
}
}
var myChart = echarts.init(document.getElementById('main'));
var option = {
tooltip: {
trigger: 'item',
formatter: '{a} <br/>{b}: {c} ({d}%)'
},
legend: {
orient: 'vertical',
left: 10,
data: ['Category1', 'Category2', 'Category3', 'Category4', 'Category5'],
formatter: (name) => {
var series = myChart.getOption().series[0];
var value = series.data.filter(row => row.name === name)[0].value;
return name + ' ' + value;
},
},
series: [
{
name: 'Series',
type: 'pie',
label: { show: false },
labelLine: { show: false },
data: [
{value: 335, name: 'Category1'},
{value: 310, name: 'Category2'},
{value: 234, name: 'Category3'},
{value: 135, name: 'Category4'},
{value: 1548, name: 'Category5'}
]
}
]
};
myChart.setOption(option);
<script src="https://cdn.jsdelivr.net/npm/echarts#4.7.0/dist/echarts.min.js"></script>
<div id="main" style="width: 600px;height:400px;"></div>

Related

Layer in Leaflet JS doesnt show again when check the control layer

I use the leaflet control layer to show up and remove the layer when I didn't wanna show the layer. when I uncheck my control layer it worked properly. the layer can disappear, but when I check again the control layer, the layer didn't show again. but there is no error in the console .
var pieChartGroup = L.featureGroup().addTo(map);
vals.forEach(val => {
var pictures = L.marker(val.location, {
icon: L.divIcon({
className: 'leaflet-echart-icon',
iconSize: [160, 160],
html: '<div id="marker' + val.id + '" style="width: 160px; height: 160px; position: relative; background-color: transparent;"></div>'
})
}).addTo(pieChartGroup);
// Based on the prepared dom, initialize the echarts instance
var myChart = echarts.init(document.getElementById('marker' + val.id));
// Specify chart configuration items and data
option = {
tooltip: {
trigger: 'item',
formatter: "{a} <br/>{b}: {c} ({d}%)"
},
series: [{
name: val.nama,
type: 'pie',
radius: ['10', '25'],
avoidLabelOverlap: false,
label: {
normal: {
show: false,
position: 'center'
},
emphasis: {
show: true,
textStyle: {
fontSize: '18',
fontWeight: 'bold'
}
}
},
labelLine: {
normal: {
show: false
}
},
data: [{
value: val.MB,
name: 'Masih Bersekolah'
}, {
value: val.TBL,
name: 'Tidak Bersekolah Lagi'
}, {
value: val.TBPS,
name: 'Tidak/Belum Pernah Bersekolah'
}]
}]
};
// Use the configuration items and data you just specified to display the chart.
myChart.setOption(option);
}
)
var baseLayers = {
"OpenStreetMap": LayerKita,
"OpenCycleMap": L.tileLayer('http://{s}.tile.opencyclemap.org/cycle/{z}/{x}/{y}.png'),
"Outdoors": L.tileLayer('http://{s}.tile.thunderforest.com/outdoors/{z}/{x}/{y}.png')
};
var overlays = {
"Bersekolah" : pieChartGroup
};
L.control.layers(baseLayers, overlays).addTo(map);

Highcharts - Sunburst Module - series.data : Same var but one work, the other one not

I'm struggling with a very strange problem using Highcharts Sunburst.
Before all, keep in mind that I've validate my JSON and test it in the JSFiddle demo (find in the documentation), everything works fine.
Here's my problem :
I get my data like that :
var data = sessionStorage.getItem('data_fap');
var parsed_data = JSON.parse(data);
var chart_data = parsed_data.data;
( My JSON look like : {data: [{id: "0", parent: "", name: " ", desc: " ", value: " "},...]} )
If a used chart_data in the chart constructor, no chart, no error.
If I set my var this way :
var data = [{id: "0", parent: "", name: " ", desc: " ", value: " "},...]};
And use it in the chart constructor, everything works fine.
I was thinking it could come from my graph options so I copy/paste the one from JSFiddle, still not working...
Here's my complete chart generation code :
var data = sessionStorage.getItem('data_fap');
var parsed_data = JSON.parse(data);
var new_data = parsed_data.data;
// Splice in transparent for the center circle
Highcharts.getOptions().colors.splice(0, 0, 'transparent');
Highcharts.chart('graph_metier', {
chart: {
height: '100%'
},
title: {
text: 'Domaines et familles professionnels'
},
subtitle: {
text: ''
},
series: [{
type: "sunburst",
data: new_data,
allowDrillToNode: true,
cursor: 'pointer',
dataLabels: {
format: '{point.name}',
filter: {
property: 'innerArcLength',
operator: '>',
value: 16
}
},
levels: [{
level: 1,
levelIsConstant: false,
levelSize: {
unit: 'percentage',
value: 30
}
},{
level: 2,
colorByPoint: true
},
{
level: 3,
colorByPoint: true
}]
}],
plotOptions: {
series: {
events: {
click: function (event) {
if(event.point.parent != "0"){
}
}
}
}
},
tooltip: {
formatter: function(e){
if(e.chart.hoverPoint.options.id == 0){
return false;
}
else
{
return '<b>' + e.chart.hoverPoint.options.name + '</b> (code: ' + e.chart.hoverPoint.options.id + ')<br>' + e.chart.hoverPoint.options.desc;
}
}
}
});
If anyone could help me to understand this mess, I'll be infinitely grateful :)

Highcharts not showing string value

I'm trying to add localstorage values into highchart series but it doesn't work.
When i print the "newString" value on the console and replace the value for "newString" at the code it works but it doesn't when I use var newString.
Here is the code:
$(document).ready(function () {
var archive,
j = "",
keys = Object.keys(localStorage),
x = keys.length;
var i = 0;
while (i < x) {
archive = JSON.parse(localStorage.getItem(keys[i]));
j += "{ name: " + keys[i] + ", data: [" + archive.username + ", " + archive.email + ", " + archive.password + "]},";
i++;
}
var newString = j.substr(0, j.length - 1);
console.log('newString: ', newString);
Highcharts.chart('container', {
title: {
text: 'Datos ingresados'
},
subtitle: {
text: 'Localstorage'
},
yAxis: {
title: {
text: 'Datos ingresados'
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'middle'
},
plotOptions: {
series: {
label: {
connectorAllowed: false
},
pointStart: 2017
}
},
series: [
newString
],
responsive: {
rules: [{
condition: {
maxWidth: 500
},
chartOptions: {
legend: {
layout: 'horizontal',
align: 'center',
verticalAlign: 'bottom'
}
}
}]
}
});
});
This is what console.log shows:
{ name: 2, data: [12345, 23456, 34567]},{ name: 3, data: [23456, 34567, 45678]},{ name: 4, data: [34567, 45678, 56789]},{ name: 5, data: [45678, 56789, 67890]}
When I change the value of newString for that, it works properly.
Because in the second case, Highcharts see your data as a pure string. So, you need to parse your string.
But first of all, we should create valid json for parsing correctly:
var newString = "{ name: 2, data: [12345, 23456, 34567]}"; //bad json
var json = newString.replace(/(['"])?([a-zA-Z0-9]+)(['"])?:/g, '"$2":');
var goodJson = "[" + json + "]"; //valid json
Now we can create options for the Highcharts:
var options = {
chart: {
renderTo: 'container',
type: 'spline'
},
series: []
};
And push data to series as follows:
$.each(JSON.parse(goodJson), function(i, item) {
options.series.push({
name: item.name,
data: item.data
});
});
And finally initialize Highcharts:
var chart = new Highcharts.Chart(options);
See at Plunker

How to get percentage axes in a Highcharts Treemap?

I have a HighCharts Treemap showing a set of categories containing subcategories. The point of the graph is to show how much of the data is in Category A, and how much of Category A is in Subcategory A1.
I have created this as follows:
http://jsfiddle.net/jbcfk93m/
$(function () {
$('#container').highcharts({
series: [{
colorByPoint: true,
layoutAlgorithm: "stripes",
alternateStartingDirection: true,
allowPointSelect: true,
point: {
events: {
click: function () {
alert(this.name + ": " + this.value);
}
}
},
dataLabels: {
},
type: "treemap",
levels: [{
level: 1,
dataLabels: {
enabled: true,
align: 'right',
rotation: 30,
crop: false,
overflow: 'none',
inside: false,
style: {
fontSize: '15px',
fontWeight: 'bold'
}
}
}, {
level: 2,
dataLabels: {
style: {
}
},
layoutAlgorithm: "stripes",
}],
data: [{
// Add parents without values
id: 'CategoryA',
name: 'Category A'
}, {
id: 'CategoryB',
name: 'Category B',
}, {
// And the children with values
name: 'Subcat A1',
value: 4,
parent: 'CategoryA'
}, {
name: 'Subcat A2',
value: 6,
parent: 'CategoryA'
}, {
name: 'Subcat B1',
value: 6,
parent: 'CategoryB'
}, {
name: 'Subcat B2',
value: 2,
parent: 'CategoryB'
}
]
}],
title: {
text: 'Treemap',
margin: 100
},
xAxis: {
min: 0,
max: 100
}
});
});
I want to get both the X- and Y axes in the graph to show percentages so I can more easily see how much of my data is in a certain category.
Does anyone know how to do this?
I didn't find anything about axis on treemaps and i'm not really sure if showing a percentage on X and Y axis would help you that much, because you basically have to multiply the values on X and Y(eg. if your subcat B1 is from 20% to 100% on X axis and from 60% to 100% on the Y axis then you would have to do (100% - 20%) * (100% - 60%) = 32%).
I did implement however a tooltip formatter that will show you the percentage when you hover over the subcategories.
formatter: function () {
var total = 0;
for (var i = 0; i < this.series.data.length; i++)
{
if (this.series.data[i].node.children.length == 0)
total+=this.series.data[i].node.val;
}
var value;
if (this.point.node.children.length == 0)
{
value = this.point.options.value;
}
else
{
value = this.point.node.childrenTotal;
}
return this.key + " " + (value / total) *100 + " %";
}
Here is the working fiddle http://jsfiddle.net/jbcfk93m/4/

Highcharts visualize, style series

I'm using Highcharts.visualize to draw the graph from a table containing the data.
You can test my working code here: http://jsfiddle.net/S2XM8/1/
I have two questions:
I want to have a separate styling for my "Additional value". How do I go about it?
Can I add data for the X-axis via the javascript? For example if I need to fill in the gap between 2014-05-27 and 2014-05-25 in the table.
Highcharts.visualize = function (table, options, tableClass) {
// the categories
options.xAxis.categories = [];
$('tbody th', table).each( function () {
options.xAxis.categories.push(this.innerHTML);
});
// the data series
options.series = [];
$('tr', table).each( function (i) {
var tr = this;
$('.graph', tr).each( function (j) {
if (i === 0) { // get the name and init the series
options.series[j] = {
name: this.innerHTML,
data: []
};
} else { // add values
options.series[j].data.push(parseFloat(this.innerHTML));
console.log(this.innerHTML);
}
});
});
options.title = { text: 'Some graph' };
$('#' + tableClass + '-graph').highcharts(options);
};
var tableNumber = document.getElementById('rank-table'),
options = {
chart: {
zoomType: 'x'
},
xAxis: {
tickInterval: 30,
reversed: true,
labels: {
rotation: 45
},
type: 'datetime',
dateTimeLabelFormats: { // don't display the dummy year
month: '%e. %b',
year: '%b'
}
},
yAxis: {
title: {
text: 'Rank'
},
min: 1,
reversed: true
},
legend: {
layout: 'vertical',
align: 'middle',
verticalAlign: 'bottom',
borderWidth: 0
}
};
Highcharts.visualize(tableNumber, options, 'number');
Both things are possible, but require to modify visualize method, see: http://jsfiddle.net/S2XM8/4/
You can set series options in a chart and then merge with data:
series: [{
// nothing special
}, {
type: 'column' // set series type for example
}]
And merging:
options.series[j] = options.series[j] || {};
options.series[j].name = this.innerHTML,
options.series[j].data = [];
Check parsed value before passing as point value:
var value = parseFloat(this.innerHTML);
if(isNaN(value)) { //null value - produces NaN when parsing
options.series[j].data.push(10);
} else {
options.series[j].data.push(value); // push value to the series
}

Categories

Resources