How to return only value in pie on apexcharts.js won't convert percent - pie-chart

I'm developing a website for a society and I am using apexCharts.js, I want to show a simple pie chart but when I display this, the value on dataLabel is a percent.
I don't want to convert them into values, of course the true value is display when we hover the pie chart.
I have already read the documentation and searched on datalabels options. The way I think is:
formatter: function(val) { return val }
but it does not work...
So I did not find an example neither on github nor here solving the issue.
Below my script :
var options = {
chart: {
width: 650,
type: 'pie',
},
labels: ['Date formation',
'Date formation 1',
'Date formation 2',
'Date formation 3',
'Nombre de jours restant ',
'Nombre de formations restantes'
],
series: [202, 80, 62, 250, 52, 30],
/* this portion NEED custom ???? */
formatter: function (val) {
return val
},
title: {
text: "Jours de formation produits ou plannifiés"
},
responsive: [{
breakpoint: 480,
options: {
chart: {
width: 200
},
legend: {
position: 'center'
}
}
}]
}
var chart = new ApexCharts(
document.querySelector("#chart"),
options);
chart.render();

The formatter property needs to be nested inside dataLabels property. Like this:
var options = {
chart: {
width: 650,
type: 'pie',
},
labels: ['Date formation',
'Date formation 1',
'Date formation 2',
'Date formation 3',
'Nombre de jours restant ',
'Nombre de formations restantes'
],
series: [202, 80, 62, 250, 52, 30],
dataLabels: {
formatter: function (val, opts) {
return opts.w.config.series[opts.seriesIndex]
},
},
}
var chart = new ApexCharts(
document.querySelector("#chart"),
options);
chart.render();
You will be able to get the default values of the series in the 2nd param (opts) of formatter function. You can use that param and get the original value instead of percentage.

Its simple here is the code-->
options={{
dataLabels: {
formatter: function (val) {
const percent = (val/1);
return percent.toFixed(0)
},
},

Related

Google Charts Bar Chart avoid overlappin annotations [duplicate]

I'm creating a stacked bar graph and need to show the label inside the stack. But Few of the label's are getting overlapped. for reference image
Can you please help me how to avoid overlapping using google charts ?
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
<script type="text/javascript">
google.charts.load('current', {packages: ['corechart', 'bar']});
google.charts.setOnLoadCallback(drawStacked);
function drawStacked() {
var data = new google.visualization.arrayToDataTable([['Time Period','XYZ',{ role: 'annotation'},'ABC',{ role: 'annotation'},{ role: 'annotation'},'Average'],
['Aug', 3754,'3754', 2089,'2089','5,843',4000],
['Sept', 900,'900', 200,'200', '100',4000],
['Oct', 2000,'2000', 4900,'4900', '6000',4000],
['Nov', 1700,'1700', 2200,'2200', '3900',4000],
['Dec', 2400,'2400', 2089,'2200', '4600',4000]
]);
var options = {
title: 'Overview of the Tickets',
isStacked: true,
orientation: 'horizontal',
hAxis: {
title: 'Time Period',
annotations: {}
},
vAxis: {
title: 'Number of Tickets'
},
seriesType: 'bars',
series: {2: {type: 'line'}}
};
var chart = new google.visualization.ComboChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
</html>
Regards,
Srikanth
first, it appears you have an extra annotation column in your data,
that doesn't appear to belong to a specific column
copied from question above...
var data = new google.visualization.arrayToDataTable([
[
'Time Period',
'XYZ',
{role: 'annotation'},
'ABC',
{role: 'annotation'},
{role: 'annotation'}, // <-- extra annotation?
'Average'
],
[
'Aug',
3754,
'3754',
2089,
'2089',
'5,843', // <-- extra annotation?
4000
],
...
]);
this could be part of the reason it's so cluttered
regardless, use the annotations configuration option for adjustments
the config option can be used for the entire chart, or just for a specific series
var options = {
// entire chart
annotations: {
textStyle: {
fontSize: 10
}
},
series: {
0: {
// series 0
annotations: {
stem: {
length: 0
},
},
},
1: {
// series 1
annotations: {
stem: {
length: 16
}
},
},
}
...
};
specifically, you can use a combination of annotations.textStyle.fontSize and annotations.stem.length to prevent overlapping
see following working snippet...
annotations.textStyle.fontSize is reduced for the entire chart
this allows the first annotation on the second column to fit within the bar
annotations.stem.length is set to zero (0) on the first series,
and 16 on the second...
(the extra annotation from the question has been removed)
google.charts.load('current', {
callback: drawStacked,
packages: ['corechart']
});
function drawStacked() {
var data = new google.visualization.arrayToDataTable([
['Time Period', 'XYZ', {role: 'annotation'}, 'ABC', {role: 'annotation'}, 'Average'],
['Aug', 3754, '3754', 2089, '2089', 4000],
['Sept', 900, '900', 200, '200', 4000],
['Oct', 2000, '2000', 4900, '4900', 4000],
['Nov', 1700, '1700', 2200, '2200', 4000],
['Dec', 2400, '2400', 2089, '2200', 4000]
]);
var options = {
annotations: {
textStyle: {
fontSize: 10
}
},
series: {
0: {
annotations: {
stem: {
length: 0
},
},
},
1: {
annotations: {
stem: {
length: 16
}
},
},
2: {
type: 'line'
}
},
hAxis: {
title: 'Time Period'
},
isStacked: true,
seriesType: 'bars',
title: 'Overview of the Tickets',
vAxis: {
title: 'Number of Tickets'
}
};
var chart = new google.visualization.ComboChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
EDIT
since the third annotation is needed as the total of the other two stacks,
recommend adding the series value for the total, in addition to the annotation column
and setting the total series type to 'line'
this will place the total annotation above the rest, for sure
so long as there is enough room on the chart to display the annotation above the bars
to ensure enough room above bars, find the max vAxis value, and add a value that will create enough room for the annotation
then set that value as vAxis.viewWindow.max
you can turn off the line and point, and hide the total series from the legend if needed
in my experience, it takes quite a bit of manipulation to get a complex google chart to display nicely
see the following working snippet, which incorporates the third, 'total', annotation...
google.charts.load('current', {
callback: drawStacked,
packages: ['corechart']
});
function drawStacked() {
var data = new google.visualization.arrayToDataTable([
['Time Period', 'XYZ', {role: 'annotation'}, 'ABC', {role: 'annotation'}, 'TOTAL', {role: 'annotation'}, 'Average'],
['Aug', 3754, '3,754', 2089, '2,089', 5843, '5,843', 4000],
['Sept', 900, '900', 200, '200', 1100, '1,100', 4000],
['Oct', 2000, '2,000', 4900, '4,900', 6900, '6,900', 4000],
['Nov', 1700, '1,700', 2200, '2,200', 3900, '3,900', 4000],
['Dec', 2400, '2,400', 2089, '2,089', 4489, '4,489', 4000]
]);
// find max for all columns to set top vAxis number
var maxVaxis = 0;
for (var i = 1; i < data.getNumberOfColumns(); i++) {
if (data.getColumnType(i) === 'number') {
maxVaxis = Math.max(maxVaxis, data.getColumnRange(i).max);
}
}
var options = {
annotations: {
textStyle: {
fontSize: 10
}
},
series: {
0: {
annotations: {
stem: {
length: 0
},
}
},
1: {
annotations: {
stem: {
length: 2
}
}
},
2: {
annotations: {
stem: {
color: 'transparent',
length: 16
}
},
color: 'black',
lineWidth: 0,
pointShape: 'square',
pointSize: 0,
type: 'line',
visibleInLegend: false
},
3: {
type: 'line'
}
},
hAxis: {
title: 'Time Period'
},
isStacked: true,
seriesType: 'bars',
title: 'Overview of the Tickets',
vAxis: {
title: 'Number of Tickets',
viewWindow: {
max: maxVaxis + 2000
}
}
};
var chart = new google.visualization.ComboChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
I think it happens because there's not enough vertical space for the labels.
Try this:
Save the highest value of the graph (let's call it maxNumber)
In the "options" set vAxis maxValue to be maxNumber plus a little more.
I have 4 horizontal lines in my graph so I wrote:
var options = {
title: chartTitle,
....... //Your options
vAxis: {
//Add more space in order to make sure the annotations are not overlapping
maxValue: maxNumber + maxNumber/4,
},

google charts dataView format differently from the dataSource?

I've created a dataView in order to put a label on my Google bar chart like :
options = {
title: arr[0][0],
titleTextStyle: { fontSize: '12', color: '#666' },
colors: ['#50c0ed'],
backgroundColor: { fill: 'transparent' },
height: 220,
width: '100%',
is3D: true,
fontSize: '11',
hAxis: { format: '$###,###,###.00' },
vAxis: {
format: '$###,###,###.##',
viewWindow: {
min: 0
}
},
chartArea: { width: '100%', height: '60%', top: '40', left: '65', right: '10' },
tooltip: { textStyle: { color: '#333', fontSize: '11' } }
};
formatter = new google.visualization.NumberFormat({ pattern: '$###,###.##/SF/year' });
formatter.format(data, 1);`enter code here`
view = new google.visualization.DataView(data);
view.setColumns([0, 1,
{
calc: "stringify",
sourceColumn: 1,
type: "string",
role: "annotation",
}]);
chart = new google.visualization.ColumnChart(container[0]);
and the result is enter image description here , but i want to exclude from the label the /SF/year ending but still keep it when i hoover over the bar ,
I tried to set formatter only after i initialize the dataVIew but this doesen't work , Is there i way i can remove /SF/year from the label but keep it when i hoover over ?
use another formatter without --> /SF/year
formatterNumberOnly = new google.visualization.NumberFormat({ pattern: '$###,###.##' });
then in view, use custom calc function instead of "stringify"
use formatValue method to format the value of each row
view = new google.visualization.DataView(data);
view.setColumns([0, 1, {
calc: function (dt, row) {
return formatterNumberOnly.formatValue(dt.getValue(row, 1));
},
type: "string",
role: "annotation",
}]);

Google Charts focusTarget: 'category' not working

Google Charts focusTarget: 'category' works when I draw the chart in one way but not in the other one.
In the example below, the BAR I has a broken tooltip (not triggering the way intended) and it's working perfectly fine with the BAR II
google.charts.load('current', {
'packages': ['corechart', 'bar']
});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
// _____ BAR I ______
var data = google.visualization.arrayToDataTable([
['Form', 'Visitors', 'Starters', 'Conversions'],
['Form 1', 1000, 650, 490],
['Form 2', 485, 460, 350],
['Form 3', 335, 250, 105]
]);
var options = {
chart: {
title: 'Company Performance',
subtitle: 'Sales, Expenses, and Profit: 2014-2017',
focusTarget: 'category',
},
focusTarget: 'category',
};
var chart = new google.charts.Bar(document.getElementById('columnchart_material'));
chart.draw(data, google.charts.Bar.convertOptions(options));
// ______ BAR II ______
var data = google.visualization.arrayToDataTable([
['Form', 'Visitors', 'Starters', 'Conversions'],
['Form 1', 1000, 650, 490],
['Form 2', 485, 460, 350],
['Form 3', 335, 250, 105]
]);
var options = {
title: 'Company Performance',
subtitle: 'Sales, Expenses, and Profit: 2014-2017',
// This line makes the entire category's tooltip active.
focusTarget: 'category',
// Use an HTML tooltip.
tooltip: {
isHtml: true
}
};
// Create and draw the visualization.
new google.visualization.ColumnChart(document.getElementById('columnchart_material_2')).draw(data, options);
}
Please also take a look at this JSFiddle of the problem.
Besides different tooltip behavior, the charts also look rather different, what is the cause?
one is considered a Classic chart, the other Material
Classic --> google.visualization.ColumnChart -- requires package: 'corechart'
Material --> google.charts.Bar -- requires package: 'bar'
Material charts are newer, but also do not support several options...
see --> Tracking Issue for Material Chart Feature Parity
which includes...
focusTarget
there is an option for Classic charts, to style them similar to Material
theme: 'material'
Here is the codepen link for using google charts
google.charts.load('visualization', '1', {
'packages': ['corechart'],
"callback": drawChart
});
function drawChart() {
var data = google.visualization.arrayToDataTable([
["Year", "Relevance", {
role: "style"
}],
["Forward ref..", 108, "#25C16F"],
["Case ref..", 20, "#25C16F"],
["Approved", 30, "#25C16F"],
["Disapproved", 50, "#25C16F"],
["Distinguish", 25.67, "#25C16F"],
["Followed", 28.9, "color: #25C16F"]
]);
var view = new google.visualization.DataView(data);
view.setColumns([0, 1]);
var options = {
title: "Case Relevance",
width: 350,
height: 300,
bar: {
groupWidth: "50%",
},
hAxis: {
title: 'Relevance',
viewWindow: {
min: 0,
max: 120
},
ticks: [0, 30, 60, 90, 120] // display labels every 25
},
legend: {
position: "none"
},
};
var chart = new google.visualization.BarChart(document.getElementById("barchart_values"));
chart.draw(vieenter code herew, options);
google.visualization.events.addListener(chart, 'select', function() {
var row = chart.getSelection()[0].row;
if (row == 0) {
$("#right_panel h2").children(".small-font").html("Forward Reference in");
} else if (row == 1) {
$("#right_panel h2").children(".small-font").html("Case Reference");
} else if (row == 2) {
$("#right_panel h2").children(".small-font").html("Approved");
} else if (row == 3) {
$("#right_panel h2").children(".small-font").html("Disapproved");
} else if (row == 4) {
$("#right_panel h2").children(".small-font").html("Distinguish");
} else if (row == 5) {
$("#right_panel h2").children(".small-font").html("Followed");
}
});
}
});
https://codepen.io/shray04/pen/Poogmjq?editors=1000

Which chart type should i choose to show change in values between 2 dates?

I am using Highcharts, but my question is in general. I want to know which chart is a perfect match to show change in values between 2 dates.
E.g The lending rate e.g
29-Aug : 21.2
30-Aug : 21.3
The change is 0.1 million.
Which chart type should i choose to show this little difference clearly noticeable .?
If you're comparing two dates/values, I would recommend using a bar chart. (If you're comparing values over months or years, I would suggest using a line or area chart.) You can better emphasize the difference between the two lending rate values by specifying the minimum, maximum, and step scale values so that the 0.1 million difference can be clearly illustrated. See the below demo:
var myConfig = {
type: 'bar',
title: {
text: 'Lending Rate',
fontFamily: 'Georgia'
},
utc: true,
timezone: 0,
scaleX: {
transform: {
type: 'date',
all: '%M %d, %Y'
},
step: 86400000,
item: {
fontSize: 10
}
},
scaleY: {
values: '21.1:21.4:0.1',
format: '%vM',
decimals: 1,
item: {
fontSize: 10
},
guide: {
lineStyle: 'dotted'
}
},
plot: {
barWidth: '50%',
borderWidth: 1,
borderColor: 'gray',
backgroundColor: '#99ccff',
valueBox: {
text: '%v million',
fontSize: 12,
fontColor: 'gray',
fontWeight: 'normal'
},
tooltip: {
text: '%v million'
}
},
series: [
{
values: [
[1472428800000, 21.2],
[1472515200000, 21.3],
]
}
]
};
zingchart.render({
id : 'myChart',
data : myConfig,
height: 400,
width: 600
});
<script src= "https://cdn.zingchart.com/zingchart.min.js"></script>
<div id='myChart'></div>
For more on scale customization and formatting, see this X/Y-Axis Scales Tutorial. The value boxes and tooltips can also be used to provide further information about the node values.
Hope that helps. I'm a member of the ZingChart team, and happy to answer further questions.
A simple bar chart with data labels to indicate the respective values would be helpful to show users there is a very small change in value.
See the code snippet below. I modified one of the basic Highcharts demos for a bar chart with your example values.
I hope this is helpful for you!
$(function () {
$('#container').highcharts({
chart: { type: 'bar' },
title: { text: 'Sample Chart' },
xAxis: {
categories: ['29-Aug','30-Aug'],
title: { text: null }
},
yAxis: { min: 0 },
tooltip: { valueSuffix: ' million' },
plotOptions: {
bar: {
dataLabels: {
crop: false,
overflow: 'none',
enabled: true,
style: { fontSize: '18px' }
}
}
},
legend: { enabled: false },
credits: { enabled: false },
series: [{
name: 'Sample Series',
data: [21.2,21.3]
}]
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<div id="container" style="width: 450px; height: 250px; margin: 0 auto"></div>

Highcharts Timeline xAxis

I've been round and round with this one and I can't seem to drop on an answer.
I've essentially done all I need except for the XAxis as the bottom - This is a timeline chart and I can't get it to render dates at all. (for each point of data for the delivered line, I have a sql datatime entry).
I have tried the various options, UTC, converting to millieseconds etc. but to no avail. Can anyone tell me how I can advance this?
My goal is to have a chart that can display in minutes (up to 2 hours worth = 160 points across) and to automatically scale to hours and days if need be - if poss).
My current setup is as follows :
(asp.net / vb.net / SQL) - although I am happy to receive c# help and I will convert)
Markup :
<script type="text/javascript">
$(function () {
Highcharts.setOptions({
global: { useUTC: true } });
$('#container').highcharts({
chart: { type: 'spline' },
title: { text: 'Delivered vs CTR' },
subtitle: {text: 'Source: Campaign Name'},
xAxis: [{
type:'datetime',
tickInterval: 20,
dateTimeLabelFormats:{
hour: '%H:%M<br>%p',
minute: '%l%M<br>%p',
second: '%H:%M:%S'
}
}],
yAxis: [{ // Primary yAxis
max: 20,
labels: {
formatter: function () {
return this.value;
},
style: {
color: '#DE4527'
}
},
title: {
text: 'Clicked',
style: {
color: '#DE4527'
}
},
opposite: true
}, { // Secondary yAxis
lineWidth: 1,
gridLineWidth: 0,
title: {
text: 'Delivered',
style: {
color: '#4572A7'
}
},
labels: {
formatter: function () {
return this.value ;
},
style: {
color: '#4572A7'
}
}
}],
tooltip: {
shared: true
},
tooltip: {
crosshairs: true,
shared: true
},
plotOptions: {
spline: {
marker: {
radius: 4,
lineColor: '#666666',
lineWidth: 1
}
}
},
legend: {
layout: 'vertical',
align: 'left',
x: 120,
verticalAlign: 'top',
y: 20,
floating: true,
backgroundColor: '#FFFFFF'
},
series: [{
name: 'Delivered',
data: <%= DeliveredChartData%>,
color: '#4572A7',
lineWidth: 1,
yAxis: 1,
marker: { radius: 2, symbol:'circle'}
}, {
name: 'Clicked',
color: '#DE4527',
marker: { radius: 2},
data: <%= ClickedChartData%>,
}]
});
});
</script>
Code behind :
Dim dt As DataTable = dsAreaChart.Tables(0)
Dim _dataDelivered As New List(Of Integer)()
Dim _dataClicked As New List(Of Integer)()
Dim sb As New StringBuilder
For Each row As DataRow In dt.Rows
Dim tmil As DateTime = CDate(row("campTableTimeStamp"))
'need to somehow add campTableTimeStamp as XAxis timeline
_dataDelivered.Add(CInt(row("campQtyDelivered")))
_dataClicked.Add(CInt(row("campQtyClicked")))
Next
Dim jss As New JavaScriptSerializer()
DeliveredChartData = jss.Serialize(_dataDelivered)
ClickedChartData = jss.Serialize(_dataClicked)
As you can see I have the campTableTimeStamp field in sql already to go - but how to pass it in with the other.
Can anyone advise ?
Many thanks for any assistance.
Peter
This would be easier to answer with a fiddle, or with an example of the data that results from your function.
One thing you will need to do: remove the 'tickInterval:20' - this is telling the chart to add a label every 20 milliseconds.
Next, make sure your data is structured properly.
should look like data:[[timestamp, numeric value],[timestamp,numerica value],[timestamp,numerica value]...]
or, if your timestamps are at regular intervals, you can set the pointStart and pointInterval properties, and skip providing the timestamp values in the data array, so you would have only data:[y value, yvalue, yvalue...]
http://api.highcharts.com/highcharts#plotOptions.series.pointStart
http://api.highcharts.com/highcharts#plotOptions.series.pointInterval
If that doesn't help, please clarify, and add data output sample.