How to invert scale display on radar chart (chart.js) - javascript

hello does anyone has any idea on how to invert the scale display on my graph? i want it to start from 100, ending with 0
i tried with scale:reverse but it didnt work
var scaling = [10, 10, 10, 10, 10, 10];
var barData = {
labels: [["PH"],
["Heavy Metals"],
["Chemical Oxygen Demand"],
["Transparency"],
"Ammonia Nitrogen",
["Dissolved", "Oxygen"],],
datasets: [
{
fillColor: "#48A497",
strokeColor: "#48A4D1",
data: [2, 10, 7, 10, 7, 10].map(function (e, i) {
return e * scaling[i];
}),
},
],
};
var income = document.getElementById("income").getContext("2d");
new Chart(income).Radar(barData, {
tooltipTemplate: function (valueObject) {
return (
valueObject.value / scaling[data.labels.indexOf(valueObject.label)]
);
},
});
enter image description here

Not sure if this works,
var scaling = [10, 10, 10, 10, 10, 10];
[2, 10, 7, 10, 7, 10].map(function (e, i) {
return scaling[i] = e * scaling[i];
})
var barData = {
labels: [
["PH"],
["Heavy Metals"],
["Chemical Oxygen Demand"],
["Transparency"],
"Ammonia Nitrogen",
["Dissolved", "Oxygen"],
],
datasets: [
{
fillColor: "#48A497",
strokeColor: "#48A4D1",
data: scaling.sort(function(a, b) {
return b-a;
}),
},
],
};
var income = document.getElementById("income").getContext("2d");
new Chart(income).Radar(barData, {
tooltipTemplate: function (valueObject) {
return (
valueObject.value / scaling[data.labels.indexOf(valueObject.label)]
);
},
});

Related

How to get the index of the barchart label that has been clicked with react-chart js-2?

I have tried the events provided in the documentation as well as some suggestions in some answers but they only work when the bar is clicked not the label. When I click on the label I only get an empty array on "element".
Here is what worked for me so far from clicking on the data bar but doesn't work on label click :
setOptions({
...
onClick: function (evt, element) {
// Get the index clicked:
const index = element[0]?.index;
},
});
Any help would be appreciated.
You can use a custom plugin to achieve this:
const findLabel = (labels, evt) => {
let found = false;
let res = null;
labels.forEach(l => {
l.labels.forEach(label => {
if (evt.x > label.x && evt.x < label.x2 && evt.y > label.y && evt.y < label.y2) {
res = {
label: label.label,
index: label.index
};
found = true;
}
});
});
return [found, res];
};
const getLabelHitboxes = (scales) => (Object.values(scales).map((s) => ({
scaleId: s.id,
labels: s._labelItems.map((e, i) => ({
x: e.translation[0] - s._labelSizes.widths[i] / 2,
x2: e.translation[0] + s._labelSizes.widths[i] / 2,
y: e.translation[1] - s._labelSizes.heights[i] / 2,
y2: e.translation[1] + s._labelSizes.heights[i] / 2,
label: e.label,
index: i
}))
})));
const options = {
type: 'line',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
borderColor: 'pink'
},
{
label: '# of Points',
data: [7, 11, 5, 8, 3, 7],
borderColor: 'orange'
}
]
},
options: {},
plugins: [{
id: 'customHover',
afterEvent: (chart, event, opts) => {
const evt = event.event;
if (evt.type !== 'click') {
return;
}
const [found, labelInfo] = findLabel(getLabelHitboxes(chart.scales), evt);
if (found) {
console.log(labelInfo);
}
}
}]
}
const ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.1/chart.js"></script>
</body>

Chart js 2 bars with one customize label on top

I have few values like A and B now I have pair of them I am showing them on chart-js like this
Now for my use case, I am calculating the third value using A and B. E.g a=100 and b=50, and dividing them will give me c=2.0. Now I want to show this c value on top of A and B bar as a common label like this
"chart.js": "^3.3.0",
react-js
const newChartInstance = new Chart(chartContainer.current, {
type: "bar",
options: {
scales: {
yAxes: [
{
ticks: {
beginAtZero: true,
},
},
],
},
...config.options,
onClick: (e) => {
const points = newChartInstance.getElementsAtEventForMode(
e,
"nearest",
{ intersect: true },
true
);
if (points.length) {
const firstPoint = points[0];
var type =
newChartInstance.data.datasets[firstPoint.datasetIndex].label;
var label = newChartInstance.data.labels[firstPoint.index];
var value =
newChartInstance.data.datasets[firstPoint.datasetIndex].data[
firstPoint.index
];
// This is the result that you will use to breakdown the chart
//console.log(label, value, type);
dispatch(setClickedBar({ label, value, type, tile: props.tile }));
}
},
},
data: data,
});
You can use a custom plugin for that:
var options = {
type: 'bar',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
backgroundColor: 'red'
},
{
label: '# of Points',
data: [7, 11, 5, 8, 3, 7],
backgroundColor: 'blue'
}
]
},
options: {
plugins: {
customValue: {
name: 'ROI',
}
}
},
plugins: [{
id: 'customValue',
afterDraw: (chart, args, opts) => {
const {
ctx,
data: {
datasets
},
_metasets
} = chart;
datasets[0].data.forEach((dp, i) => {
let barValue = `${(datasets[1].data[i] + dp) / 2}%`;
const lineHeight = ctx.measureText('M').width;
const textVal = opts.name || 'fill'
ctx.textAlign = 'center';
ctx.fillText(barValue, _metasets[0].data[i].x, (_metasets[0].data[i].y - lineHeight * 1.5), _metasets[0].data[i].width);
ctx.fillText(textVal, _metasets[0].data[i].x, (_metasets[0].data[i].y - lineHeight * 3), _metasets[0].data[i].width);
});
}
}]
}
var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.4.1/chart.js"></script>
</body>

Echart: How to set mark area to fill sections in xAxis

I have a problem with marking area: i need to be able to select a bar area based on xAxis, for example from 0 to 1, from 1 to 2, etc. But when i try to provide options for bar like
[{xAxis: 0, itemStyle: {color: red}},{xAxis: 1}]
it marks an area from a middle of xAxis area with an index of 0 to a middle of xAxis area with an index of 1. Is there a way to make it mark from start of an area to an end. Currently i managed to do so only with x option in pixels:
https://codesandbox.io/s/react-echart-markarea-ksj31?file=/src/index.js:714-726
Is there a better way to do it?
I can't imagine a method that would cover your requirements. It seems there is no such but nothing prevents to do it ourselves, see below.
When call function with join = true markedArea will calc as range from first to last.
calcMarkAreaByBarIndex(myChart, join = true, [4, 9])
When call function with join = false markedArea will calc for each bar.
calcMarkAreaByBarIndex(myChart, join = true, [4, 5, 6, 9])
var myChart = echarts.init(document.getElementById('main'));
var option = {
tooltip: {},
xAxis: {
data: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
},
yAxis: {},
series: [
{
id: 'myBar',
name: 'Series',
type: 'bar',
data: [11, 11, 11, 11, 12, 13, 110, 123, 113, 134, 93, 109],
markArea: {
data: [
[{x: 184},{x: 216}],
[{x: 224},{x: 256}],
]
},
},
]
};
myChart.setOption(option);
function calcMarkAreaByBarIndex(chartInstance, join = false, barIdx){
var series = chartInstance.getModel().getSeriesByType('bar');
var seriesData = series.map((s, idx) => s.getData())[0];
var barNum = seriesData.count();
var barCoors = [];
var layout = idx => seriesData.getItemLayout(idx);
for(var i = 0; i < barNum; i++){
if(!barIdx.includes(i)) continue;
barCoors.push([
{ x: layout(i).x },
{ x: layout(i).x + layout(i).width },
])
}
if(join){
return [
[
{ x: barCoors[0][0].x },
{ x: barCoors[barCoors.length - 1][1].x }
]
]
} else {
return barCoors
}
}
var markedAreas = {
series: {
id: 'myBar',
markArea: {
data: calcMarkAreaByBarIndex(myChart, join = true, [4,9])
}
}
};
myChart.setOption(markedAreas);
<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>
I found a solution, that worked for me:
Basically, you need to manually set yAxis's max props, add another xAxis, make it invisible, create a custom series with type 'bar' and set xAxisIndex to 1:
data: [maxYaxisValue,maxYaxisValue...], //length === xAxis.data.length
type: 'bar',
barWidth: '100%',
color: transparent,
xAxisIndex: 1,
And style a bar by index with background color and borderWidth
You can check the working example here
https://codesandbox.io/s/react-echart-markarea-m0mgq?file=/src/index.js

How to show more than one "dataMax" in Highcharts?

Currently, I'm showing a max point in the line chart. But I want to change dataMax to top 5 max value points in chart.How can I achieve this in Highcharts?
var defaultData = 'urlto.csv';
var urlInput = document.getElementById('fetchURL');
var pollingCheckbox = document.getElementById('enablePolling');
var pollingInput = document.getElementById('pollingTime');
function createChart() {
Highcharts.chart('closed5', {
chart: {
type: 'area',
zoomType: 'x'
},
plotOptions: {
series: {
dataLabels: {
enabled: true,
style: {},
formatter: function() {
if (this.y === this.series.dataMax) {
return this.y;
}
}
}
}
},
title: {
text: 'Chart for charting'
},
data: {
csvURL: urlInput.value,
enablePolling: pollingCheckbox.checked === true,
dataRefreshRate: parseInt(pollingInput.value, 10)
}
});
if (pollingInput.value < 1 || !pollingInput.value) {
pollingInput.value = 1;
}
}
urlInput.value = defaultData;
// We recreate instead of using chart update to make sure the loaded CSV
// and such is completely gone.
pollingCheckbox.onchange = urlInput.onchange = pollingInput.onchange = createChart;
// Create the chart
createChart();
As #ewolden rightly noticed, you can sort your data and show only the five highest values:
var data = [11, 22, 33, 44, 55, 66, 15, 25, 35, 45, 55, 65],
sortedData = data.slice().sort(function(a, b){
return b - a
});
Highcharts.chart('container', {
series: [{
data: data,
dataLabels: {
enabled: true,
formatter: function() {
if (sortedData.indexOf(this.y) < 5) {
return this.y;
}
}
}
}]
});
Live demo: http://jsfiddle.net/BlackLabel/xkf2w5tb/
API: https://api.highcharts.com/highmaps/series.mapbubble.dataLabels.formatter
As far as I know formatter callback is the way to format the data labels. If you want to show the top N points you should sort the data in a new array and pull the top 5 values. This is an example of how to clone and sort the array and extract the top 5 elements in the formatter call.
let data = [32, 10, 20, 99, 30, 54, 85, 56, 11, 26, 15, 45, 55, 65];
//Copy the array
let temp = data.slice();
// Sort the temp array in descending order
temp.sort((a, b) => b - a);
Highcharts.chart('closed5', {
chart: {
type: 'area',
zoomType: 'x'
},
title: {
text: 'Chart for charting'
},
series: [{
data: data,
dataLabels: {
enabled: true,
formatter: function() {
if (temp.indexOf(this.y) < 5) {
return this.y;
}
},
},
}]
});
<script src="https://code.highcharts.com/highcharts.js"></script>
<div id="closed5"></div>

Different labels in tooltip with chartjs

I am making a radar chart with chartjs. The labels on the side of the radar I have given numbers (so the dataset Labels are numbers, 1 to 10). In the tooltip I do not want to these numbers, but a text linked to it (the text the number refers to). These are in a difrent array.
Is there a way to do this?
At the moment I have the following code:
$scope.drawGraph = function() {
radarOptions = {
scaleShowLabels : false,
scaleFontSize: 10,
pointLabelFontSize : 14,
scaleBeginAtZero: true,
showScale: true,
scaleOverride: true,
scaleSteps: 10,
scaleStepWidth: 10,
scaleStartValue: 0,
showTooltips: true,
customTooltips: false,
tooltipTemplate: "<%if (datasetLabel){%><%=datasetLabel%>: <%}%><%= value + '%'%>"
};
var tempComp = []
for (var i = 0; i < $scope.competencesDB.length; i++) {
tempComp.push({
number: i + 1,
competence: $scope.competencesDB[i]
})
}
var tempLabels = [];
var tempData = [];
var tempName = [];
for (var i = 0; i < tempComp.length; i++) {
// console.log($scope.competencesDB[i])
tempName.push(tempComp[i].competence.name)
tempLabels.push(tempComp[i].number);
if (tempComp[i].competence.progress.length === 0) {
tempData.push(0)
} else{
tempData.push(tempComp[i].competence.progress[tempComp[i].competence.progress.length -1].value);
}
}
radarData = {
//names : tempName
labels : tempLabels,
datasets : [
{
label: tempName,
fillColor : "rgba(173, 209, 244, 0.54)",
strokeColor : "rgba(49, 137, 225, 0.94)",
data : tempData
},
]
};
//Get the context of the Radar Chart canvas element we want to select
var ctx = document.getElementById("radarChart").getContext("2d");
// Create the Radar Chart
var myRadarChart = new Chart(ctx).Radar(radarData, radarOptions);
}
I think I need to change something in the following part:
tooltipTemplate: "<%if (datasetLabel){%><%=datasetLabel%>: <%}%><%= value + '%'%>"
But I don't know how this part of the code works. Can I but some kind of forloop in this to loop through the second datasetLabel part?
Thanks!
You can do this using a function instead of a template string. As you guessed you need to figure out the name from the number.
Here is a generic sample
var numberNames = [
{ number: 1, name: "Eating" },
{ number: 2, name: "Drinking" },
{ number: 3, name: "Sleeping" },
{ number: 4, name: "Designing" },
{ number: 8, name: "Coding" },
{ number: 9, name: "Cycling" },
{ number: 10, name: "Running" }
];
var data = {
labels: numberNames.map(function(e) { return e.number }),
datasets: [
{
label: "My First dataset",
fillColor: "rgba(220,220,220,0.2)",
strokeColor: "rgba(220,220,220,1)",
pointColor: "rgba(220,220,220,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(220,220,220,1)",
data: [65, 59, 9, 10, 56, 55, 40]
}
]
};
var ctx = document.getElementById("myChart").getContext("2d");
var myChart = new Chart(ctx).Radar(data, {
tooltipTemplate: function (valueObject) {
return numberNames.filter(function (e) { return e.number === valueObject.label })[0].name + ': ' + valueObject.value;
}
});
I used numberNames but you should be able to replace that with tempComp (after adjusting the labels property and the tooltipTemplate function body slightly).
Fiddle - http://jsfiddle.net/80wdhbwo/

Categories

Resources