Howto show absolute number in Apexcharts pie chart - apexcharts

The pie chart I created with Apexcharts shows relative (percentage) numbers at the circle (like the "99.9%" in the screenshot below).
Instead of the relative number I'd like to show the absolute value like what's in the tooltip (see example: "6752").
I tried a formatter function with signature function(value, {seriesIndex,dataPointIndex,w}), but value is the relative value (e.g. 99.9), dataPointIndex is undefined, seriesIndex is always 1 and w contains the whole chart config without being specific to this slice of the pie.
How can I show absolute numbers?

You have the right strategy, but probably not the right formatter. The one you need is dataLabels.formatter:
let options = {
series: [10, 20, 15],
chart: {
width: 350,
type: 'pie'
},
labels: ['Label 1', 'Label 2', 'Label 3'],
dataLabels: {
formatter: (val, { seriesIndex, w }) => w.config.series[seriesIndex] // <--- HERE
}
};
let chart = new ApexCharts(document.querySelector('#chart'), options);
chart.render();
<script src="https://cdn.jsdelivr.net/npm/apexcharts"></script>
<div id="chart"></div>

Related

how to show text inside a chart - pie and doughnut?

I have tried a lot of it, but nothing seems to be working as expected.
I need to show the text inside the pie chart.
For the above, I tried using chartjs-plugin-datalabels but then used a formatter to change a value to a value with a percentage.
formatter: function(value:any, context:Context) {
return Math.floor(value) + '%';
},
But that affected both the data point (i.e: [11,200] is by data, I only need to add a percentage to the first data point and not to the second. Show 11% and 200.)
Code:
import ChartDataLabels,{Context} from 'chartjs-plugin-datalabels';
ChartJS.register(ArcElement, Tooltip, Legend, ChartDataLabels);
export const options = {
responsive: true,
maintainAspectRatio: false,
plugins: {
datalabels: {
formatter: function(value:any, context:Context) {
return Math.floor(value) + '%';
},
color:"white",
font: {
size: 16,
weight:'bold'
}
},
title: {
display: true,
},
legend: {
display: false,
},
},
};
function MyChart(){
return(
<Pie data={dataChart} options={options} />
)
}
In the above code options in the Pie, the component shows a typescript error while using chartjs-plugin-datalabels library.
The expected type comes from property 'options' which is declared here on type 'IntrinsicAttributes & Omit<ChartProps<"doughnut", number[], unknown>, "type"> & { ref?: ForwardedRef<ChartJSOrUndefined<"doughnut", number[], unknown>> | undefined; }'
2: I need to show text in the center of a Doughnut chart but seems impossible with the library and reactchartjs2 don't have a feature to show text in charts. Tried a possible solution at Add text inside the Doughnut chart of the React-Chartjs-2 box to react but none helped.

chart.js 3 stacked bar chart - tooltip showing for zero values

I have a stacked bar chart, and when I hover the mouse near the bottom of bars the tooltip shows zero values like so:
... I only want the tooltip to show on non-zero bars like this:
The JSON for the chart looks like this:
... i.e. "6-10 hours" is a dataset, and the data has 0's in it where there are no values (so it aligns with the correct bar)
Other than the tooltips, the chart functions correctly.
Is there any way to remove 0 values from tooltips?
You can define a tooltip.filter callback function that returns false for zero values, true otherwise.
Please take a look at below runnable code snippet and see how it works.
new Chart('myChart', {
type: 'bar',
data: {
labels: ['A', 'B', 'C', 'D'],
datasets: [{
label: 'Dataset',
data: [0, 2, 0, 3],
}]
},
options: {
responsive: false,
plugins: {
tooltip: {
mode: 'dataset',
filter: tooltipItem => tooltipItem.dataset.data[tooltipItem.dataIndex] > 0
}
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.6.2/chart.min.js"></script>
<canvas id="myChart"></canvas>

How to show the complete number on the Y-axis in Google Chart?

I am using Google Chart to display a bar chart. Please see the screen shot below. Problem is, the highest number on the y-axis is always getting chopped off. In the screenshot, the highest number is supposed to be 55; but, as you can see, only the lower portion of 55 is showing. I have tried changing the height of my div and changing the height of the chart. They didn't solve the problem. I have also tried changing the max value of the y-axis but that does not solve the problem in the sense that the highest number would get chopped off (for example, for the chart in my screen shot, if I were to change the max value to 60, it is true that 55 would show completely but 60 would be chopped off).
How can I show the complete number on the highest value on y-axis in Google Charts?
google.charts.load('current', {packages: ['bar']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.arrayToDataTable([
["", ""],
["Col_1", <?php echo $col1Count; ?>],
["Col_2", <?php echo $col2Count; ?>],
["Col_3", <?php echo $col3Count; ?>],
["Col_4", <?php echo $col4Count; ?>]
]);
var options = {
width: 720,
height: 550,
legend: { position: 'none' },
vAxis: {
viewWindow: {
min: 5,
max: 55
},
ticks: [5,10,15,20,25,30,35,40,45,50,55]
}
};
// Instantiate and draw the chart.
var chart = new google.charts.Bar(document.getElementById('myChart'));
chart.draw(data, google.charts.Bar.convertOptions(options));
google.visualization.events.addListener(chart, 'ready', function () {
html2canvas(document.getElementById('myChart')).then(function(canvas) {
// console.log(canvas.toDataURL('image/png'));
//document.getElementById('myChart').appendChild(canvas);
jQuery.ajax({
type: 'POST',
url: 'https://myURL.com/saveimage.php',
data: {
// send image string as data
imgstr: canvas.toDataURL('image/png')
},
success: function(response) {
alert(response);
}
});
});
});
}
The material Bar chart has far fewer options than the classic charts. I suspect that if you add a title, even if it is just a space character, that will reserve enough space above the chart to show the topmost axis tick label without truncation.

Put tooltip on the middle of two bars

I'm trying to position a custom Chart.js tooltip on the middle of two bars. I made a research on the chart.js docs and different posts but didn't found any different approach than position it using the following snippet (I'm using jquery and doing a toggle class to hide/show the tooltip, please focus on the values I'm using to position the tooltip):
function setupTooltipPosition(config) {
const { tooltipElement, tooltipModel } = config;
const leftOffset = this._chart.canvas.offsetLeft;
const topOffset = this._chart.canvas.offsetTop;
tooltipElement.removeClass(tooltipSelectors.hide);
tooltipElement.css('left', `${tooltipModel.caretX - leftOffset}px`);
tooltipElement.css('top', `${tooltipModel.carteY - topOffset}px`);
}
Using this approach on this particular case I got this result:
[
I also tried using the x and y values of the tooltipModel , however , it doesn't add more sense of how to put the tooltip in the middle. If you tried to add a custom offset to put it on the middle , it works for just this case, but when you add more data it doesn't work. I can have at most 2 datasets, however, the user can add at most 10 data values that means 10 groups of bars.
The question is: There is a way to put the tooltip in the middle of the group of bars (or a single bar in case the user has just 1 dataset) using the values that Chart.js provide for tooltips? Or in other case, do you know any custom approach to have this tooltip centered?
Thanks!!
You don't specify if 'middle' means on the x- and/or y-axis. But since you wrote:
...on the middle of two bars...
I assume you mean on the x-axis. In this case you need to set the options.tooltips.mode property to index. Below is a working example.
let myChart = new Chart(document.getElementById('myChart'), {
type: 'bar',
data: {
labels: ['x', 'y', 'z'],
datasets: [{
label: '1993',
data: [50, 30, 65],
backgroundColor: '#503291'
}, {
label: '1994',
data: [60, 15, 65],
backgroundColor: '#1bbecd'
}]
},
options: {
tooltips: {
mode: 'index'
},
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}],
xAxes: [{
barPercentage: 1
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"></script>
<canvas id="myChart"></canvas>
For future questions please provide a MCVE as that makes it much quicker and easier to help you.

How to show an Empty Google Chart when there is no data?

Consider drawing a column chart and I don't get any data from the data source, How do we draw an empty chart instead of showing up a red colored default message saying "Table has no columns"?
What I do is initialize my chart with 1 column and 1 data point (set to 0). Then whenever data gets added I check if there is only 1 column and that it is the dummy column, then I remove it. I also hide the legend to begin so that it doesn't appear with the dummy column, then I add it when the new column gets added.
Here is some sample code you can plug in to the Google Visualization Playground that does what I am talking about. You should see the empty chart for 2 seconds, then data will get added and the columns will appear.
var data, options, chart;
function drawVisualization() {
data = google.visualization.arrayToDataTable([
['Time', 'dummy'],
['', 0],
]);
options = {
title:"My Chart",
width:600, height:400,
hAxis: {title: "Time"},
legend : {position: 'none'}
};
// Create and draw the visualization.
chart = new google.visualization.ColumnChart(document.getElementById('visualization'));
chart.draw(data,options);
setTimeout('addData("12:00",10)',2000);
setTimeout('addData("12:10",20)',3000);
}
function addData(x,y) {
if(data.getColumnLabel(1) == 'dummy') {
data.addColumn('number', 'Your Values', 'col_id');
data.removeColumn(1);
options.legend = {position: 'right'};
}
data.addRow([x,y]);
chart.draw(data,options);
}​
A even better solution for this problem might be to use a annotation column instead of a data column as shown below. With this solution you do not need to use any setTimeout or custom function to remove or hide your column. Give it a try by pasting the given code below into Google Code Playground.
function drawVisualization() {
var data = google.visualization.arrayToDataTable([
['', { role: 'annotation' }],
['', '']
]);
var ac = new google.visualization.ColumnChart(document.getElementById('visualization'));
ac.draw(data, {
title : 'Just a title...',
width: 600,
height: 400
});
}
​
The way I did this was by disabling the pie slices, turning off tooltips, stuffing in a pretend value and making it gray. I'm sure there are more clever ways to do this, but this worked for me where the other methods didn't.
The only drawback is that it sets both items in the legend to gray as well. I think you could perhaps just add a third item, and make it invisible on the legend only. I liked this way though.
function drawChart() {
// Define the chart to be drawn.
data = new google.visualization.DataTable();
data.addColumn({type: 'string', label: 'Result'});
data.addColumn({type: 'number', label: 'Count'});
data.addRows([
['Value A', 0],
['Value B', 0]
]);
var opt_pieslicetext = null;
var opt_tooltip_trigger = null;
var opt_color = null;
if (data.getValue(1,1) == 0 && data.getValue(0,1) == 0) {
opt_pieslicetext='none';
opt_tooltip_trigger='none'
data.setCell(1,1,.1);
opt_color= ['#D3D3D3'];
}
chart = new google.visualization.PieChart(document.getElementById('mydiv'));
chart.draw(data, {sliceVisibilityThreshold:0, pieSliceText: opt_pieslicetext, tooltip: { trigger: opt_tooltip_trigger }, colors: opt_color } );
}