Cannot change label from percentage to number in amchart5 - amcharts

I am using the new amcharts5 and I cannot seem to change my pie chart "slice" and label to a pure number despite referencing my old code and other links.
Basically my code and chart loads, but the issue is my values is depicted in percentages instead of numbers. This is my code below where I tried to address this.
Any assistance will be appreciated.
// Set data
series.data.setAll([
{ value: Type[0], category: "Type 1" },
{ value: Type[1], category: "Type 2" },
{ value: Type[2], category: "Type 3" },
]);
// Create legend
var legend = chart.children.push(am5.Legend.new(root, {
centerX: am5.percent(50),
x: am5.percent(50),
marginTop: 15,
marginBottom: 15
}));
legend.labels.template.text = "{category}: {value.value}";
legend.slices.template.tooltipText = "{category}: {value.value}";
chart.legend.valueLabels.template.text = "{value.value}";
legend.data.setAll(series.dataItems);
Regards

v5 is completely different from v4, API-wise. In order to configure the pie chart's legend, you have to set it inside the series as documented here:
let series = chart.series.push(
am5percent.PieSeries.new(root, {
name: "Series",
categoryField: "country",
valueField: "sales",
legendLabelText: "{category}",
legendValueText: "{value}"
})
);
Tooltips need to be set on the slices using set or setAll (see the settings documentation for more info):
series.slices.template.set('tooltipText', '{category}: {value}');
Similarly for the slice labels, set the text property using the above functions:
series.labels.template.set('text', '{category}: {value}');
Demo:
var root = am5.Root.new("chartdiv");
root.setThemes([
am5themes_Animated.new(root)
]);
var chart = root.container.children.push(
am5percent.PieChart.new(root, {
layout: root.verticalLayout
})
);
var data = [{
country: "France",
sales: 100000
}, {
country: "Spain",
sales: 160000
}, {
country: "United Kingdom",
sales: 80000
}];
var series = chart.series.push(
am5percent.PieSeries.new(root, {
name: "Series",
valueField: "sales",
categoryField: "country",
legendLabelText: "{category}",
legendValueText: "{value}"
})
);
series.slices.template.set('tooltipText', '{category}: {value}');
series.labels.template.set('text', '{category}: {value}');
series.data.setAll(data);
var legend = chart.children.push(am5.Legend.new(root, {
centerX: am5.percent(50),
x: am5.percent(50),
marginTop: 15,
marginBottom: 15
}));
legend.data.setAll(series.dataItems);
#chartdiv {
width: 100%;
height: 500px;
}
<script src="//cdn.amcharts.com/lib/5/index.js"></script>
<script src="//cdn.amcharts.com/lib/5/percent.js"></script>
<script src="//cdn.amcharts.com/lib/5/themes/Animated.js"></script>
<div id="chartdiv"></div>

Related

Amcharts 5 Separate Label into points with the same date

I use AmCharts 5 and sometimes the data can come with a different value but with the same date
Result example:
[
{"result":"AAA","date":"2022-06-09T23:00:00","value":155},
{"result":"BBB","date":"2022-06-10T07:00:00","value":25},
{"result":"CCC","date":"2022-06-11T07:00:00","value":85},
{"result":"DDD","date":"2022-06-12T07:00:00","value":65},
{"result":"EEE","date":"2022-06-12T08:00:00","value":198},
]
But when there is more than one record on the same date, it shows the points, but there is an equal Label for all points.
My code is:
https://jsfiddle.net/sNniffer/9xk6q3eu/17/
I need each point to have its Label, even if they are on the same date
In your example, date strings are all unique!
The easiest solution here is to use hour as timeUnit in the settings of your DateAxis.
am5.ready(function() {
var root = am5.Root.new("chartdiv");
var chart = root.container.children.push(am5xy.XYChart.new(root, {}));
var xAxis = chart.xAxes.push(am5xy.DateAxis.new(root, {
baseInterval: {
timeUnit: "hour", // Put "hour" instead of "day"
count: 1
},
renderer: am5xy.AxisRendererX.new(root, {}),
tooltip: am5.Tooltip.new(root, {})
}));
var yAxis = chart.yAxes.push(am5xy.ValueAxis.new(root, {
renderer: am5xy.AxisRendererY.new(root, {})
}));
var cursor = chart.set("cursor", am5xy.XYCursor.new(root, {
xAxis: xAxis
}));
cursor.lineY.set("visible", false);
var series = chart.series.push(am5xy.SmoothedXLineSeries.new(root, {
name: "Series",
xAxis: xAxis,
yAxis: yAxis,
categoryXField: "result",
valueXField: "date",
valueYField: "value",
tooltip: am5.Tooltip.new(root, {
labelText: "[bold]Result:[/] {categoryX}\n[bold]Date:[/] {valueX.formatDate()}\n[bold]Value:[/] {valueY}"
})
}));
series.fills.template.setAll({
visible: true,
fillOpacity: 0.2
});
series.bullets.push(function() {
return am5.Bullet.new(root, {
sprite: am5.Circle.new(root, {
radius: 8,
stroke: root.interfaceColors.get("background"),
strokeWidth: 2,
interactive: false,
fill: series.get("fill")
})
});
});
var data = [
{result: "AAA", date: new Date("2022-06-09T23:00:00").getTime(), value: 155},
{result: "BBB", date: new Date("2022-06-10T07:00:00").getTime(), value: 25},
{result: "CCC", date: new Date("2022-06-11T07:00:00").getTime(), value: 85},
{result: "DDD", date: new Date("2022-06-12T07:00:00").getTime(), value: 65},
{result: "EEE", date: new Date("2022-06-12T08:00:00").getTime(), value: 198}
];
series.data.setAll(data);
});
#chartdiv {
width: 100%;
height: 350px;
}
<script src="https://cdn.amcharts.com/lib/5/index.js"></script>
<script src="https://cdn.amcharts.com/lib/5/xy.js"></script>
<div id="chartdiv"></div>

How to add CLICK events on AMCHARTS 5 labels (x and y axis)?

I am trying to add basic interactivity to my AMCHARTS 5 labels. Take this chart as an example:
I need to be able to click on the names at the left of the chart. That is actually yAxis because I use an inverted chart.
In the function that creates the series, I placed this code:
series.columns.template.events.once("click", function(ev) {
console.log("Clicked on a column", ev.target);
});
And it makes my bars to be clickable. I don't know how to refer to the labels on the left.
Labels as interactive elements in amCharts 5 are tricky. Basically, it's super hard to determine hover/click over just text because it's impossible to completely eradicate antialising, and the actual colored area is super tiny.
Therefore, if we need tooltip to be interactive - have a hover tooltip or handle click events - we need to add a background to it.
The background does not necessarily have to be visible: we can just set its fillOpacity: 0 to make it completely transparent.
Source: Labels – amCharts 5 Documentation
After the declaration and initialization of your yAxis, you can put this piece of code:
yAxis.get("renderer").labels.template.setup = target => {
target.setAll({
cursorOverStyle: "pointer",
background: am5.Rectangle.new(root, {
fill: am5.color(0x000000),
fillOpacity: 0
})
});
};
yAxis.get("renderer").labels.template.events.on("click", e => {
console.log(e.target.dataItem.dataContext.category);
});
Full example:
am5.ready(() => {
let root = am5.Root.new("chartdiv");
let chart = root.container.children.push(am5xy.XYChart.new(root, {}));
let data = [{
category: "Category 1",
value: 10
}, {
category: "Category 2",
value: 20
}, {
category: "Category 3",
value: 15
}];
let yAxis = chart.yAxes.push(am5xy.CategoryAxis.new(root, {
categoryField: "category",
renderer: am5xy.AxisRendererY.new(root, {
inversed: true,
cellStartLocation: 0.1,
cellEndLocation: 0.9
})
}));
yAxis.data.setAll(data);
yAxis.get("renderer").labels.template.setup = target => {
target.setAll({
cursorOverStyle: "pointer",
background: am5.Rectangle.new(root, {
fill: am5.color(0x000000),
fillOpacity: 0
})
});
};
yAxis.get("renderer").labels.template.events.on("click", e => {
console.log(e.target.dataItem.dataContext.category);
});
let xAxis = chart.xAxes.push(am5xy.ValueAxis.new(root, {
min: 0,
renderer: am5xy.AxisRendererX.new(root, {})
}));
let series = chart.series.push(am5xy.ColumnSeries.new(root, {
name: "Series",
xAxis: xAxis,
yAxis: yAxis,
valueXField: "value",
categoryYField: "category"
}));
series.data.setAll(data);
});
#chartdiv {
width: 100%;
height: 350px;
}
<script src="https://cdn.amcharts.com/lib/5/index.js"></script>
<script src="https://cdn.amcharts.com/lib/5/xy.js"></script>
<div id="chartdiv"></div>

AmCharts5: get active dataItem on click LineSeries

How I can get dataContext from point by click on free area?
When you hover the mouse cursor, a tooltip appears, can I determine who has it currently active?
I am not sure to understand your question properly, but if you want to get the data behind a bullet when you click on it, this is the way to go:
am5.ready(() => {
let root = am5.Root.new("chartdiv");
let chart = root.container.children.push(am5xy.XYChart.new(root, {}));
let data = [
{
category: "Category 1",
value: 10
},
{
category: "Category 2",
value: 20
},
{
category: "Category 3",
value: 15
}
];
let xAxis = chart.xAxes.push(am5xy.CategoryAxis.new(root, {
categoryField: "category",
renderer: am5xy.AxisRendererX.new(root, {})
}));
xAxis.data.setAll(data);
let yAxis = chart.yAxes.push(am5xy.ValueAxis.new(root, {
renderer: am5xy.AxisRendererY.new(root, {})
}));
let series = chart.series.push(am5xy.LineSeries.new(root, {
name: "Series",
xAxis: xAxis,
yAxis: yAxis,
categoryXField: "category",
valueYField: "value"
}));
series.strokes.template.set("strokeWidth", 3);
series.data.setAll(data);
let bulletTemplate = am5.Template.new(root, {});
bulletTemplate.events.on("click", e => {
let context = e.target.dataItem.dataContext;
console.log(`${context.category} | ${context.value}`);
});
series.bullets.push(() => {
return am5.Bullet.new(root, {
sprite: am5.Circle.new(root, {
strokeWidth: 3,
stroke: series.get("stroke"),
radius: 5,
fill: root.interfaceColors.get("background")
}, bulletTemplate)
});
});
});
#chartdiv {
width: 100%;
height: 350px;
}
<script src="https://cdn.amcharts.com/lib/5/index.js"></script>
<script src="https://cdn.amcharts.com/lib/5/xy.js"></script>
<div id="chartdiv"></div>
You can read the documentation here: Bullets – amCharts 5 Documentation

Change grid color in C3.js

How can I achieve this grid and label colors. I can find some answers on label colors but nothing on changing the grid color to the one shown in the screenshot, instead of the default black one.
Just in case you need my working code:
var chart = c3.generate({
bindto: '#chart',
data: {
x: 'x',
columns: [
['x', ...xAxis],
['total', ...yAxis],
],
type: 'bar',
colors: {
total: d3.rgb(40,162,245)
},
empty: { label: { text: "No Data Available" }}
},
axis: {
x: {
tick: {
culling: {
max: 31,
},
},
},
y: {
tick: {
format: (x) => x / 1000 + 'k',
},
},
},
grid: {
y: {
show: true,
color: '#fff'
},
},
})
Try to use selector .c3 path, .c3 line:not([stroke-width="10"]) for lines, and tspan for text.
.c3 line[stroke-width="10"] is used for legend squares, it needs be excluded.
Also see How to get rounded corner in c3js bar charts
const xAxis = [10, 20, 40];
const yAxis = [2000, 1420, 1000];
var chart = c3.generate({
bindto: '#chart',
data: {
x: 'x',
columns: [
['x', ...xAxis],
['total', ...yAxis],
],
type: 'bar',
colors: {
total: d3.rgb(40,162,245)
},
empty: { label: { text: "No Data Available" }}
},
axis: {
x: {
tick: {
culling: {
max: 31,
},
},
},
y: {
tick: {
format: (x) => x / 1000 + 'k',
},
},
},
grid: {
y: {
show: true,
color: '#fff'
},
},
})
.c3 path, .c3 line:not([stroke-width="10"]) {
stroke: gold !important;
}
tspan {
stroke: green !important;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.16.0/d3.min.js" integrity="sha512-FHsFVKQ/T1KWJDGSbrUhTJyS1ph3eRrxI228ND0EGaEp6v4a/vGwPWd3Dtd/+9cI7ccofZvl/wulICEurHN1pg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/c3/0.7.20/c3.min.js" integrity="sha512-+IpCthlNahOuERYUSnKFjzjdKXIbJ/7Dd6xvUp+7bEw0Jp2dg6tluyxLs+zq9BMzZgrLv8886T4cBSqnKiVgUw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/c3/0.7.20/c3.min.css" integrity="sha512-cznfNokevSG7QPA5dZepud8taylLdvgr0lDqw/FEZIhluFsSwyvS81CMnRdrNSKwbsmc43LtRd2/WMQV+Z85AQ==" crossorigin="anonymous" referrerpolicy="no-referrer" />
<div id="chart">

How to change the labels to the image (icon) in bar chart.js

Help me, please.
How to change the labels to the image (icon) in bar chart.js ?
I mean, change from this
change labels: "LifeWall_files/logo.png","Bodily Functions","Sleep"
to this
bottom icons
The easiest way to do this would be to get a font that includes these icons and then set the font family for the ticks
...
options: {
scales: {
xAxes: [{
ticks: {
fontFamily: 'FontAwesome'
}
}]
}
}
};
and then specify the appropriate character codes in your labels
labels: ["\uf24e", "\uf1b9", "\uf242", "\uf0fc", "\uf236"],
With the FontAwesome CSS, the above would give you
The Plugin Core API offers a range of hooks that may be used for performing custom code. You can use the afterDraw hook to draw images (icons) instead of tick labels directly on the canvas using CanvasRenderingContext2D.
You'll also have to instruct Chart.js not to display the default tick labels. This can be done through the following definition inside the chart options.
scales: {
xAxes: [{
ticks: {
display: false
}
}],
Further you need to define some padding at the bottom of the chart, otherwise you'll see only part of the images.
layout: {
padding: {
bottom: 30
}
},
Please have a look at the runnable code snippet below.
const labels = ['red vans', 'blue vans', 'green vans', 'gray vans'];
const images = ['https://i.stack.imgur.com/2RAv2.png', 'https://i.stack.imgur.com/Tq5DA.png', 'https://i.stack.imgur.com/3KRtW.png', 'https://i.stack.imgur.com/iLyVi.png'];
const values = [48, 56, 33, 44];
new Chart(document.getElementById("myChart"), {
type: "bar",
plugins: [{
afterDraw: chart => {
var ctx = chart.chart.ctx;
var xAxis = chart.scales['x-axis-0'];
var yAxis = chart.scales['y-axis-0'];
xAxis.ticks.forEach((value, index) => {
var x = xAxis.getPixelForTick(index);
var image = new Image();
image.src = images[index],
ctx.drawImage(image, x - 12, yAxis.bottom + 10);
});
}
}],
data: {
labels: labels,
datasets: [{
label: 'My Dataset',
data: values,
backgroundColor: ['red', 'blue', 'green', 'lightgray']
}]
},
options: {
responsive: true,
layout: {
padding: {
bottom: 30
}
},
legend: {
display: false
},
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}],
xAxes: [{
ticks: {
display: false
}
}],
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="myChart" height="90"></canvas>

Resources