Amcharts 5 Separate Label into points with the same date - amcharts

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>

Related

amcharts5 - chart above another chart using same xaxis?

I am attempting to show a column chart (or a line chart would work too) above a gannt chart using the same xaxis (timestamp) and having trouble with spacing as well as getting any data to show in the column chart. I don't even know if this is possible to do, but the help docs made it sound like it was so I am more than likely missing quite a few things in the configuration or doing things wrong.
I've created a codepen with what I have so far. The original gannt chart shows fine, then I am able to get the column chart's yaxis to show (although it overlaps the gannt instead of being above it and does not show any data).
Any assistance/explanation with this would be appreciated.
// Set data
var data = [{
"State": "Idle",
"Start": 1424321864000,
"End": 1424321875000,
"Duration": 11
}, {
"State": "Idle",
"Start": 1424322649000,
"End": 1424322669000,
"Duration": 20
}, {
"State": "Idle",
"Start": 1424322970000,
"End": 1424322981000,
"Duration": 11
}, {
"State": "Idle",
"Start": 1424323093000,
"End": 1424323139000,
"Duration": 46
}, {
"State": "Active",
"Start": 1424323250000,
"End": 1424323268000,
"Duration": 18
}, {
"State": "Idle",
"Start": 1424323680000,
"End": 1424323703000,
"Duration": 23
}];
var mousekeys = [{
"Timestamp": 1424318400000,
"Clicks": "20",
"Keypresses": "30"
}];
/**
* ---------------------------------------
* This demo was created using amCharts 5.
*
* For more information visit:
* https://www.amcharts.com/
*
* Documentation is available at:
* https://www.amcharts.com/docs/v5/
* ---------------------------------------
*/
// Create root element
// https://www.amcharts.com/docs/v5/getting-started/#Root_element
var root = am5.Root.new("chartdiv");
//font size theme
var myTheme = am5.Theme.new(root);
myTheme.rule("Label").setAll({
fontSize: 12
});
root.setThemes([
am5themes_Animated.new(root),
myTheme
]);
root.locale = am5locales_en_US;
//chartReg['chart'].utc = true; //force chart to show in UTC instead of device timezone
root.timezone = am5.Timezone.new('UTC'); //user timezone
//duration format
root.durationFormatter.setAll({
baseUnit: "second",
durationFormat: "hh'h' mm'm' ss's'"
});
//create chart
var chart = root.container.children.push(am5xy.XYChart.new(root, {
panX: false,
panY: false,
wheelX: false,
wheelY: false,
layout: root.verticalLayout,
marginTop: 0,
marginRight: 0,
marginBottom: 0,
marginLeft: 0,
paddingTop: 0,
paddingRight: 20,
paddingBottom: 20,
paddingLeft: 10,
}));
//zoom button
//chart.zoomOutButton.setAll({
// forceHidden: true, //disables zoom button
//});
chart.zoomOutButton.get("background").setAll({
fill: am5.color("#BDBDBD"),
});
chart.zoomOutButton.get("background").states.create("hover", {}).setAll({
fill: am5.color("#8a8a8a"),
});
chart.zoomOutButton.get("background").states.create("down", {}).setAll({
fill: am5.color("#707070"),
});
chart.zoomOutButton.get("background").states.create("active", {}).setAll({
fill: am5.color("#707070"),
});
//create axes
var yAxis = chart.yAxes.push(am5xy.CategoryAxis.new(root, {
text: "State",
fontWeight: "500",
height: am5.percent(70),
categoryField: "State",
renderer: am5xy.AxisRendererY.new(root, {}),
tooltip: am5.Tooltip.new(root, {}),
}));
var yAxis2 = chart.yAxes.push(am5xy.ValueAxis.new(root, {
text: "Clicks",
fontWeight: "500",
height: am5.percent(30),
min: 0, //min 'hint', but not forced
//strictMinMax: true, //forces the min/max
//extraMax: 0.1, //extra 10% to the value range which acts as 'padding' to the yaxis
renderer: am5xy.AxisRendererY.new(root, {})
}));
//the order is top to bottom ends up bottom to top on the chart
yAxis.data.setAll([
{ State: "Idle" },
{ State: "Active" }
]);
//y-axis dash lines
var yRenderer = yAxis.get("renderer");
yRenderer.grid.template.setAll({
strokeDasharray: [6]
});
var xAxis = chart.xAxes.push(am5xy.DateAxis.new(root, {
baseInterval: { timeUnit: "second", count: 1 },
renderer: am5xy.AxisRendererX.new(root, {}),
tooltip: am5.Tooltip.new(root, {}),
tooltipDateFormat: "EEE, MMM dd # h:mm:ss a"
}));
//x-axis dash lines
var xRenderer = xAxis.get("renderer");
xRenderer.grid.template.setAll({
strokeDasharray: [6],
});
//series
var series = chart.series.push(am5xy.ColumnSeries.new(root, {
xAxis: xAxis,
yAxis: yAxis,
openValueXField: "Start",
valueXField: "End",
categoryYField: "State",
sequencedInterpolation: true,
tooltip: am5.Tooltip.new(root, {
//labelText: "[bold {Color} fontSize: 16px]{State}[/]\n[bold]Start :[/] {openValueX.formatDate(\"EEE',' MM'/'dd'/'yyyy '#' h':'mm':'ss a\")}\n[bold]End :[/] {valueX.formatDate(\"EEE',' MM'/'dd'/'yyyy '#' h':'mm':'ss a\")}\n[bold]Duration :[/] {Duration.formatDuration(\"hh'h' mm'm' ss's'\")}",
labelText: "[bold]Start :[/] {openValueX.formatDate(\"EEE',' MM'/'dd'/'yyyy '#' h':'mm':'ss a\")}\n[bold]End :[/] {valueX.formatDate(\"EEE',' MM'/'dd'/'yyyy '#' h':'mm':'ss a\")}\n[bold]Duration :[/] {Duration.formatDuration(\"hh'h' mm'm' ss's'\")}",
getFillFromSprite: false
})
}));
series.get("tooltip").get("background").setAll({
fill: am5.color("#ffffff"),
fillOpacity: 1,
strokeWidth: 2,
stroke: am5.color("#bbbbbb"),
});
//series columns
series.columns.template.setAll({
fillOpacity: 1,
stroke: 0,
strokeWidth: 0, //doesn't seem to work use 'stroke:0'
tooltipText: "{State}:\n[bold]{openValueX}[/] - [bold]{valueX}[/]"
});
series.columns.template.adapters.add("fill", function (text, target, key) {
//console.log(target);
//have to check for empty
//if(target.dataItem) {
if(target.dataItem.dataContext.State == "Active") {
return am5.color("#7bc07b"); //active
} else {
return am5.color("#55bfe6"); //idle
}
//} else {
// return null;
//}
});
//series
var series2 = chart.series.push(am5xy.ColumnSeries.new(root, {
name: "Clicks",
fill: am5.color("#679fd0"),
xAxis: xAxis,
yAxis: yAxis2,
valueYField: "Clicks",
valueXField: "Timestamp",
tooltip: am5.Tooltip.new(root, {
labelText: "{valueY}",
getFillFromSprite: false
})
}));
series2.get("tooltip").get("background").setAll({
fill: am5.color("#ffffff"),
fillOpacity: 1,
strokeWidth: 2,
stroke: am5.color("#bbbbbb"),
});
//series columns
series2.columns.template.setAll({
fillOpacity: 1,
stroke: 0,
strokeWidth: 0, //doesn't seem to work use 'stroke:0'
});
series2.get("tooltip").label.adapters.add("text", function (text, target, key) {
//console.log(target);
//have to check for empty
if(target.dataItem) {
return "Total : [bold]{Clicks}[/]\nTimestamp : [bold]{Timestamp}[/]";
} else {
return null;
}
});
//title
var title = chart.children.unshift(am5.Label.new(root, {
fontSize: 12,
textAlign: "left",
x: am5.percent(0),
y: am5.percent(0),
marginTop: 0,
marginRight: 0,
marginBottom: 30,
marginLeft: 0,
paddingTop: 0,
paddingRight: 0,
paddingBottom: 0,
paddingLeft: 0,
text: "some label"
}));
//cursor
var cursor = chart.set("cursor", am5xy.XYCursor.new(root, {
snapToSeries: [ series ],
snapToSeriesBy: "x",
behavior: "zoomX"
}));
cursor.lineX.set("visible", false);
cursor.lineY.set("visible", false);
//formatting
series.data.processor = am5.DataProcessor.new(root, {
dateFields: ["Start", "End"],
dateFormat: "xxxxxxxxxxxxx"
});
//formatting
series2.data.processor = am5.DataProcessor.new(root, {
numericFields: ["Clicks"],
dateFields: ["Timestamp"],
dateFormat: "xxxxxxxxxxxxx"
});
//scrollbar
chart.set("scrollbarX", am5.Scrollbar.new(root, {
orientation: "horizontal",
marginTop: 0,
marginRight: 0,
marginBottom: 30,
marginLeft: 0,
paddingTop: 0,
paddingRight: 0,
paddingBottom: 0,
paddingLeft: 0,
}));
//exporting
exporting = am5plugins_exporting.Exporting.new(root, {
dataSource: data,
dataFields: {
State: 'State', Start: 'Start', End: 'End', Duration: 'Duration'
},
dateFields: ["Start", "End"],
dateFormat: "MM/dd/yyyy hh:mm:ss a",
durationFields: ["Duration"],
durationFormat: "hh'h' mm'm' ss's'",
filePrefix: 'User Activity'
});
//add data
series.data.setAll(data);
series2.data.setAll(mousekeys);
//make stuff animate on load
series.appear(1000);
series2.appear(1000);
chart.appear(1000, 100);
yAxis and yAxis2 are not stacked. You have to be more explicit and add this line of code:
chart.leftAxesContainer.set("layout", root.verticalLayout);
If you want to place your column chart above, you need to push yAxis2 before yAxis or use unshift():
var yAxis2 = chart.yAxes.unshift(am5xy.ValueAxis.new(root, {
// ...
}));
I put your code below with these two little modifications:
// Set data
var data = [{
"State": "Idle",
"Start": 1424321864000,
"End": 1424321875000,
"Duration": 11
}, {
"State": "Idle",
"Start": 1424322649000,
"End": 1424322669000,
"Duration": 20
}, {
"State": "Idle",
"Start": 1424322970000,
"End": 1424322981000,
"Duration": 11
}, {
"State": "Idle",
"Start": 1424323093000,
"End": 1424323139000,
"Duration": 46
}, {
"State": "Active",
"Start": 1424323250000,
"End": 1424323268000,
"Duration": 18
}, {
"State": "Idle",
"Start": 1424323680000,
"End": 1424323703000,
"Duration": 23
}];
var mousekeys = [{
"Timestamp": 1424318400000,
"Clicks": "20",
"Keypresses": "30"
}];
/**
* ---------------------------------------
* This demo was created using amCharts 5.
*
* For more information visit:
* https://www.amcharts.com/
*
* Documentation is available at:
* https://www.amcharts.com/docs/v5/
* ---------------------------------------
*/
// Create root element
// https://www.amcharts.com/docs/v5/getting-started/#Root_element
var root = am5.Root.new("chartdiv");
//font size theme
var myTheme = am5.Theme.new(root);
myTheme.rule("Label").setAll({
fontSize: 12
});
root.setThemes([
am5themes_Animated.new(root),
myTheme
]);
root.locale = am5locales_en_US;
//chartReg['chart'].utc = true; //force chart to show in UTC instead of device timezone
root.timezone = am5.Timezone.new('UTC'); //user timezone
//duration format
root.durationFormatter.setAll({
baseUnit: "second",
durationFormat: "hh'h' mm'm' ss's'"
});
//create chart
var chart = root.container.children.push(am5xy.XYChart.new(root, {
panX: false,
panY: false,
wheelX: false,
wheelY: false,
layout: root.verticalLayout,
marginTop: 0,
marginRight: 0,
marginBottom: 0,
marginLeft: 0,
paddingTop: 0,
paddingRight: 20,
paddingBottom: 20,
paddingLeft: 10,
}));
chart.leftAxesContainer.set("layout", root.verticalLayout); // <--- HERE
//zoom button
//chart.zoomOutButton.setAll({
// forceHidden: true, //disables zoom button
//});
chart.zoomOutButton.get("background").setAll({
fill: am5.color("#BDBDBD"),
});
chart.zoomOutButton.get("background").states.create("hover", {}).setAll({
fill: am5.color("#8a8a8a"),
});
chart.zoomOutButton.get("background").states.create("down", {}).setAll({
fill: am5.color("#707070"),
});
chart.zoomOutButton.get("background").states.create("active", {}).setAll({
fill: am5.color("#707070"),
});
//create axes
var yAxis = chart.yAxes.push(am5xy.CategoryAxis.new(root, {
text: "State",
fontWeight: "500",
height: am5.percent(70),
categoryField: "State",
renderer: am5xy.AxisRendererY.new(root, {}),
tooltip: am5.Tooltip.new(root, {}),
}));
var yAxis2 = chart.yAxes.unshift(am5xy.ValueAxis.new(root, { // <--- HERE
text: "Clicks",
fontWeight: "500",
height: am5.percent(30),
min: 0, //min 'hint', but not forced
//strictMinMax: true, //forces the min/max
//extraMax: 0.1, //extra 10% to the value range which acts as 'padding' to the yaxis
renderer: am5xy.AxisRendererY.new(root, {})
}));
//the order is top to bottom ends up bottom to top on the chart
yAxis.data.setAll([
{ State: "Idle" },
{ State: "Active" }
]);
//y-axis dash lines
var yRenderer = yAxis.get("renderer");
yRenderer.grid.template.setAll({
strokeDasharray: [6]
});
var xAxis = chart.xAxes.push(am5xy.DateAxis.new(root, {
baseInterval: { timeUnit: "second", count: 1 },
renderer: am5xy.AxisRendererX.new(root, {}),
tooltip: am5.Tooltip.new(root, {}),
tooltipDateFormat: "EEE, MMM dd # h:mm:ss a"
}));
//x-axis dash lines
var xRenderer = xAxis.get("renderer");
xRenderer.grid.template.setAll({
strokeDasharray: [6],
});
//series
var series = chart.series.push(am5xy.ColumnSeries.new(root, {
xAxis: xAxis,
yAxis: yAxis,
openValueXField: "Start",
valueXField: "End",
categoryYField: "State",
sequencedInterpolation: true,
tooltip: am5.Tooltip.new(root, {
//labelText: "[bold {Color} fontSize: 16px]{State}[/]\n[bold]Start :[/] {openValueX.formatDate(\"EEE',' MM'/'dd'/'yyyy '#' h':'mm':'ss a\")}\n[bold]End :[/] {valueX.formatDate(\"EEE',' MM'/'dd'/'yyyy '#' h':'mm':'ss a\")}\n[bold]Duration :[/] {Duration.formatDuration(\"hh'h' mm'm' ss's'\")}",
labelText: "[bold]Start :[/] {openValueX.formatDate(\"EEE',' MM'/'dd'/'yyyy '#' h':'mm':'ss a\")}\n[bold]End :[/] {valueX.formatDate(\"EEE',' MM'/'dd'/'yyyy '#' h':'mm':'ss a\")}\n[bold]Duration :[/] {Duration.formatDuration(\"hh'h' mm'm' ss's'\")}",
getFillFromSprite: false
})
}));
series.get("tooltip").get("background").setAll({
fill: am5.color("#ffffff"),
fillOpacity: 1,
strokeWidth: 2,
stroke: am5.color("#bbbbbb"),
});
//series columns
series.columns.template.setAll({
fillOpacity: 1,
stroke: 0,
strokeWidth: 0, //doesn't seem to work use 'stroke:0'
tooltipText: "{State}:\n[bold]{openValueX}[/] - [bold]{valueX}[/]"
});
series.columns.template.adapters.add("fill", function (text, target, key) {
//console.log(target);
//have to check for empty
//if(target.dataItem) {
if(target.dataItem.dataContext.State == "Active") {
return am5.color("#7bc07b"); //active
} else {
return am5.color("#55bfe6"); //idle
}
//} else {
// return null;
//}
});
//series
var series2 = chart.series.push(am5xy.ColumnSeries.new(root, {
name: "Clicks",
fill: am5.color("#679fd0"),
xAxis: xAxis,
yAxis: yAxis2,
valueYField: "Clicks",
valueXField: "Timestamp",
tooltip: am5.Tooltip.new(root, {
labelText: "{valueY}",
getFillFromSprite: false
})
}));
series2.get("tooltip").get("background").setAll({
fill: am5.color("#ffffff"),
fillOpacity: 1,
strokeWidth: 2,
stroke: am5.color("#bbbbbb"),
});
//series columns
series2.columns.template.setAll({
fillOpacity: 1,
stroke: 0,
strokeWidth: 0, //doesn't seem to work use 'stroke:0'
});
series2.get("tooltip").label.adapters.add("text", function (text, target, key) {
//console.log(target);
//have to check for empty
if(target.dataItem) {
return "Total : [bold]{Clicks}[/]\nTimestamp : [bold]{Timestamp}[/]";
} else {
return null;
}
});
//title
var title = chart.children.unshift(am5.Label.new(root, {
fontSize: 12,
textAlign: "left",
x: am5.percent(0),
y: am5.percent(0),
marginTop: 0,
marginRight: 0,
marginBottom: 30,
marginLeft: 0,
paddingTop: 0,
paddingRight: 0,
paddingBottom: 0,
paddingLeft: 0,
text: "some label"
}));
//cursor
var cursor = chart.set("cursor", am5xy.XYCursor.new(root, {
snapToSeries: [ series ],
snapToSeriesBy: "x",
behavior: "zoomX"
}));
cursor.lineX.set("visible", false);
cursor.lineY.set("visible", false);
//formatting
series.data.processor = am5.DataProcessor.new(root, {
dateFields: ["Start", "End"],
dateFormat: "xxxxxxxxxxxxx"
});
//formatting
series2.data.processor = am5.DataProcessor.new(root, {
numericFields: ["Clicks"],
dateFields: ["Timestamp"],
dateFormat: "xxxxxxxxxxxxx"
});
//scrollbar
chart.set("scrollbarX", am5.Scrollbar.new(root, {
orientation: "horizontal",
marginTop: 0,
marginRight: 0,
marginBottom: 30,
marginLeft: 0,
paddingTop: 0,
paddingRight: 0,
paddingBottom: 0,
paddingLeft: 0,
}));
//exporting
exporting = am5plugins_exporting.Exporting.new(root, {
dataSource: data,
dataFields: {
State: 'State', Start: 'Start', End: 'End', Duration: 'Duration'
},
dateFields: ["Start", "End"],
dateFormat: "MM/dd/yyyy hh:mm:ss a",
durationFields: ["Duration"],
durationFormat: "hh'h' mm'm' ss's'",
filePrefix: 'User Activity'
});
//add data
series.data.setAll(data);
series2.data.setAll(mousekeys);
//make stuff animate on load
series.appear(1000);
series2.appear(1000);
chart.appear(1000, 100);
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";
}
#chartdiv {
width: 100%;
height: 500px;
}
<script src="https://cdn.amcharts.com/lib/5/index.js"></script>
<script src="https://cdn.amcharts.com/lib/5/xy.js"></script>
<script src="https://cdn.amcharts.com/lib/5/themes/Animated.js"></script>
<script src="https://cdn.amcharts.com/lib/5/locales/en_US.js"></script>
<script src="https://cdn.amcharts.com/lib/5/plugins/exporting.js"></script>
<div id="chartdiv"></div>
You can see a column if you use the horizontal scrollbar and go completely to the left. The reason is there:
var xAxis = chart.xAxes.push(am5xy.DateAxis.new(root, {
baseInterval: { timeUnit: "second", count: 1 },
// ...
}));
Your interval is tiny (one second), so your column width is tiny. You have to tweak timeUnit or count in baseInterval if you want a wider column.

am chart 5 Stacked column chart with line chart

I am trying to create a stacked column chart and trying to integrate a line chart on Y axis, Chart is rendering but line is not visible which is using opposite y axis value.
latitudeSeries should create a line chart using the opposite y axis that is Y axis value on the right side. But it's not rendering the line chart though opposite y axis is rendered.
<!-- Styles -->
<style>
#chartdiv {
width: 100%;
height: 500px;
}
</style>
<!-- Resources -->
<script src="https://cdn.amcharts.com/lib/5/index.js"></script>
<script src="https://cdn.amcharts.com/lib/5/xy.js"></script>
<script src="https://cdn.amcharts.com/lib/5/themes/Animated.js"></script>
<!-- Chart code -->
<script>
am5.ready(function() {
// Create root element
// https://www.amcharts.com/docs/v5/getting-started/#Root_element
var root = am5.Root.new("chartdiv");
// Set themes
// https://www.amcharts.com/docs/v5/concepts/themes/
root.setThemes([
am5themes_Animated.new(root)
]);
// Create chart
// https://www.amcharts.com/docs/v5/charts/xy-chart/
var chart = root.container.children.push(am5xy.XYChart.new(root, {
panX: false,
panY: false,
wheelX: "panX",
wheelY: "zoomX",
layout: root.verticalLayout
}));
// Add legend
// https://www.amcharts.com/docs/v5/charts/xy-chart/legend-xy-series/
var legend = chart.children.push(am5.Legend.new(root, {
centerX: am5.p50,
x: am5.p50
}));
var data = [{
"year": "2021",
"europe": 2.5,
"namerica": 2.5,
"asia": 2.1,
"lamerica": 1,
"meast": 0.8,
"africa": 0.4,
"latitude": 40.00
}, {
"year": "2022",
"europe": 2.6,
"namerica": 2.7,
"asia": 2.2,
"lamerica": 0.5,
"meast": 0.4,
"africa": 0.3,
"latitude": 45.74
}, {
"year": "2023",
"europe": 2.8,
"namerica": 2.9,
"asia": 2.4,
"lamerica": 0.3,
"meast": 0.9,
"africa": 0.5,
"latitude": 39.74
}];
// Create axes
// https://www.amcharts.com/docs/v5/charts/xy-chart/axes/
var xAxis = chart.xAxes.push(am5xy.CategoryAxis.new(root, {
categoryField: "year",
renderer: am5xy.AxisRendererX.new(root, {
cellStartLocation: 0.1,
cellEndLocation: 0.9
}),
tooltip: am5.Tooltip.new(root, {})
}));
var yAxis = chart.yAxes.push(am5xy.ValueAxis.new(root, {
min: 0,
renderer: am5xy.AxisRendererY.new(root, {})
}));
var latitudeAxisRenderer = am5xy.AxisRendererY.new(root, {opposite:true});
var latitudeAxis = chart.yAxes.push(am5xy.ValueAxis.new(root, {
renderer: latitudeAxisRenderer
}));
var latitudeSeries = chart.series.push(am5xy.LineSeries.new(root, {
xAxis: xAxis,
yAxis: latitudeAxis,
valueYField: "latitude",
valueXField: "year",
tooltip:am5.Tooltip.new(root, {
labelText:"latitude: {valueY}"
})
}));
latitudeSeries.strokes.template.setAll({ strokeWidth: 2 });
// Add circle bullet
// https://www.amcharts.com/docs/v5/charts/xy-chart/series/#Bullets
latitudeSeries.bullets.push(function() {
var graphics = am5.Circle.new(root, {
strokeWidth: 2,
radius: 5,
stroke: latitudeSeries.get("stroke"),
fill: root.interfaceColors.get("background"),
});
graphics.adapters.add("radius", function(radius, target) {
return target.dataItem.dataContext.townSize;
})
return am5.Bullet.new(root, {
sprite: graphics
});
});
latitudeSeries.data.setAll(data);
// Add series
// https://www.amcharts.com/docs/v5/charts/xy-chart/series/
function makeSeries(name, fieldName, stacked) {
var series = chart.series.push(am5xy.ColumnSeries.new(root, {
stacked: stacked,
name: name,
xAxis: xAxis,
yAxis: yAxis,
valueYField: fieldName,
categoryXField: "year"
}));
series.columns.template.setAll({
tooltipText: "{name}, {categoryX}:{valueY}",
width: am5.percent(90),
tooltipY: am5.percent(10)
});
xAxis.data.setAll(data);
series.data.setAll(data);
// Make stuff animate on load
// https://www.amcharts.com/docs/v5/concepts/animations/
series.appear();
series.bullets.push(function () {
return am5.Bullet.new(root, {
locationY: 0.5,
sprite: am5.Label.new(root, {
text: "{valueY}",
fill: root.interfaceColors.get("alternativeText"),
centerY: am5.percent(50),
centerX: am5.percent(50),
populateText: true
})
});
});
legend.data.push(series);
}
makeSeries("Europe", "europe", true);
makeSeries("North America", "namerica", true);
makeSeries("Asia", "asia", true);
makeSeries("Latin America", "lamerica", true);
makeSeries("Middle East", "meast", true);
makeSeries("Africa", "africa", true);
// Make stuff animate on load
// https://www.amcharts.com/docs/v5/concepts/animations/
chart.appear(1000, 100);
}); // end am5.ready()
</script>
<!-- HTML -->
<div id="chartdiv"></div>
Your xAxis is a category axis, not a value axis. Thus, in your latitudeSeries settings, you must use categoryXField instead of valueXField.
For more readability, I recommend you to synchronize latitudeAxis and yAxis using syncWithAxis. You should also set transparency on your column series.
I edited your code and added these little corrections (with comments).
<!-- Styles -->
<style>
#chartdiv {
width: 100%;
height: 500px;
}
</style>
<!-- Resources -->
<script src="https://cdn.amcharts.com/lib/5/index.js"></script>
<script src="https://cdn.amcharts.com/lib/5/xy.js"></script>
<script src="https://cdn.amcharts.com/lib/5/themes/Animated.js"></script>
<!-- Chart code -->
<script>
am5.ready(function() {
// Create root element
// https://www.amcharts.com/docs/v5/getting-started/#Root_element
var root = am5.Root.new("chartdiv");
// Set themes
// https://www.amcharts.com/docs/v5/concepts/themes/
root.setThemes([
am5themes_Animated.new(root)
]);
// Create chart
// https://www.amcharts.com/docs/v5/charts/xy-chart/
var chart = root.container.children.push(am5xy.XYChart.new(root, {
panX: false,
panY: false,
wheelX: "panX",
wheelY: "zoomX",
layout: root.verticalLayout
}));
// Add legend
// https://www.amcharts.com/docs/v5/charts/xy-chart/legend-xy-series/
var legend = chart.children.push(am5.Legend.new(root, {
centerX: am5.p50,
x: am5.p50
}));
var data = [{
"year": "2021",
"europe": 2.5,
"namerica": 2.5,
"asia": 2.1,
"lamerica": 1,
"meast": 0.8,
"africa": 0.4,
"latitude": 40.00
}, {
"year": "2022",
"europe": 2.6,
"namerica": 2.7,
"asia": 2.2,
"lamerica": 0.5,
"meast": 0.4,
"africa": 0.3,
"latitude": 45.74
}, {
"year": "2023",
"europe": 2.8,
"namerica": 2.9,
"asia": 2.4,
"lamerica": 0.3,
"meast": 0.9,
"africa": 0.5,
"latitude": 39.74
}];
// Create axes
// https://www.amcharts.com/docs/v5/charts/xy-chart/axes/
var xAxis = chart.xAxes.push(am5xy.CategoryAxis.new(root, {
categoryField: "year",
renderer: am5xy.AxisRendererX.new(root, {
cellStartLocation: 0.1,
cellEndLocation: 0.9
}),
tooltip: am5.Tooltip.new(root, {})
}));
var yAxis = chart.yAxes.push(am5xy.ValueAxis.new(root, {
min: 0,
renderer: am5xy.AxisRendererY.new(root, {})
}));
var latitudeAxisRenderer = am5xy.AxisRendererY.new(root, {opposite:true});
var latitudeAxis = chart.yAxes.push(am5xy.ValueAxis.new(root, {
syncWithAxis: yAxis, // Synchronize axes to get a more readable grid
renderer: latitudeAxisRenderer
}));
var latitudeSeries = chart.series.push(am5xy.LineSeries.new(root, {
xAxis: xAxis,
yAxis: latitudeAxis,
valueYField: "latitude",
categoryXField: "year", // Use categoryXField instead of valueXField
tooltip:am5.Tooltip.new(root, {
labelText:"latitude: {valueY}"
})
}));
latitudeSeries.strokes.template.setAll({ strokeWidth: 2 });
// Add circle bullet
// https://www.amcharts.com/docs/v5/charts/xy-chart/series/#Bullets
latitudeSeries.bullets.push(function() {
var graphics = am5.Circle.new(root, {
strokeWidth: 2,
radius: 5,
stroke: latitudeSeries.get("stroke"),
fill: root.interfaceColors.get("background"),
});
graphics.adapters.add("radius", function(radius, target) {
return target.dataItem.dataContext.townSize;
})
return am5.Bullet.new(root, {
sprite: graphics
});
});
latitudeSeries.data.setAll(data);
// Add series
// https://www.amcharts.com/docs/v5/charts/xy-chart/series/
function makeSeries(name, fieldName, stacked) {
var series = chart.series.push(am5xy.ColumnSeries.new(root, {
stacked: stacked,
name: name,
xAxis: xAxis,
yAxis: yAxis,
valueYField: fieldName,
categoryXField: "year"
}));
series.columns.template.setAll({
tooltipText: "{name}, {categoryX}:{valueY}",
width: am5.percent(90),
tooltipY: am5.percent(10),
// Set column and stroke transparency for more readability
opacity: 0.75,
stroke: "transparent"
});
xAxis.data.setAll(data);
series.data.setAll(data);
// Make stuff animate on load
// https://www.amcharts.com/docs/v5/concepts/animations/
series.appear();
series.bullets.push(function () {
return am5.Bullet.new(root, {
locationY: 0.5,
sprite: am5.Label.new(root, {
text: "{valueY}",
fill: root.interfaceColors.get("alternativeText"),
centerY: am5.percent(50),
centerX: am5.percent(50),
populateText: true
})
});
});
legend.data.push(series);
}
makeSeries("Europe", "europe", true);
makeSeries("North America", "namerica", true);
makeSeries("Asia", "asia", true);
makeSeries("Latin America", "lamerica", true);
makeSeries("Middle East", "meast", true);
makeSeries("Africa", "africa", true);
// Make stuff animate on load
// https://www.amcharts.com/docs/v5/concepts/animations/
chart.appear(1000, 100);
}); // end am5.ready()
</script>
<!-- HTML -->
<div id="chartdiv"></div>

How to create gauge diagram with amchart 5 with arabic text in it

I want to create a gauge diagram with amcharts 5 with persian text on it. All the code sample I found is working correctly with english text on it. But when I want to use persian or arabic text (rtl languages), it doesn't show texts correct. How can I solve this problem?
Here is my code:
<script>
var root = am5.Root.new("chartdiv");
root.setThemes([
am5themes_Animated.new(root)
]);
var chart = root.container.children.push(am5radar.RadarChart.new(root, {
panX: false,
panY: false,
startAngle: 160,
endAngle: 380
}));
var axisRenderer = am5radar.AxisRendererCircular.new(root, {
innerRadius: -40
});
axisRenderer.grid.template.setAll({
stroke: root.interfaceColors.get("background"),
visible: true,
strokeOpacity: 0.8
});
var xAxis = chart.xAxes.push(am5xy.ValueAxis.new(root, {
maxDeviation: 0,
min: -40,
max: 100,
strictMinMax: true,
renderer: axisRenderer
}));
var axisDataItem = xAxis.makeDataItem({});
var clockHand = am5radar.ClockHand.new(root, {
pinRadius: am5.percent(20),
radius: am5.percent(100),
bottomWidth: 40
})
var bullet = axisDataItem.set("bullet", am5xy.AxisBullet.new(root, {
sprite: clockHand
}));
xAxis.createAxisRange(axisDataItem);
var label = chart.radarContainer.children.push(am5.Label.new(root, {
fill: am5.color(0xffffff),
centerX: am5.percent(50),
textAlign: "center",
centerY: am5.percent(50),
fontSize: "3em"
}));
axisDataItem.set("value", 50);
bullet.get("sprite").on("rotation", function () {
var value = axisDataItem.get("value");
var text = Math.round(axisDataItem.get("value")).toString();
var fill = am5.color(0x000000);
xAxis.axisRanges.each(function (axisRange) {
if (value >= axisRange.get("value") && value <= axisRange.get("endValue")) {
fill = axisRange.get("axisFill").get("fill");
}
})
label.set("text", Math.round(value).toString());
clockHand.pin.animate({ key: "fill", to: fill, duration: 500, easing: am5.ease.out(am5.ease.cubic) })
clockHand.hand.animate({ key: "fill", to: fill, duration: 500, easing: am5.ease.out(am5.ease.cubic) })
});
var i = 0;
var a = setInterval(function() {
if (i === 9) {
axisDataItem.animate({
key: "value",
to: Math.round(28),
duration: 100,
easing: am5.ease.out(am5.ease.cubic)
});
}
else if (i === 25) {
clearInterval(a);
}
else {
axisDataItem.animate({
key: "value",
to: Math.round(Math.random() * 140 - 40),
duration: 2000,
easing: am5.ease.out(am5.ease.cubic)
});
i++;
}
}
, 100);
var bandsData = [{
title: "لاغری مفرط",
direction: "rtl",
position: "right",
orientation: "rtl",
color: "#ee1f25",
lowScore: -40,
highScore: -20
}, {
title: 'لاغر',
color: "#f04922",
lowScore: -20,
highScore: 0
}, {
title: "نرمال",
color: "#fdae19",
lowScore: 0,
highScore: 20
}, {
title: "اضافه وزن",
color: "#f3eb0c",
lowScore: 20,
highScore: 40
}, {
title: "چاق",
color: "#b0d136",
lowScore: 40,
highScore: 60
}, {
title: "چاقی زیاد",
color: "#54b947",
lowScore: 60,
highScore: 80
}, {
title: "چاقی مفرط",
color: "#0f9747",
lowScore: 80,
highScore: 100
}];
am5.array.each(bandsData, function (data) {
var axisRange = xAxis.createAxisRange(xAxis.makeDataItem({}));
axisRange.setAll({
value: data.lowScore,
endValue: data.highScore
});
axisRange.get("axisFill").setAll({
visible: true,
fill: am5.color(data.color),
fillOpacity: 0.8
});
axisRange.get("label").setAll({
text: data.title,
inside: true,
radius: 15,
fontSize: "0.9em",
fill: root.interfaceColors.get("background")
});
});
chart.rtl = true;
chart.appear(1000, 100);
chart.rtl = true;
</script>
Final result is like this image:
amcharts5 result
I also searched about it in documentation of amcharts 5 but I couldn't find the answer.

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

Cannot change label from percentage to number in amchart5

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>

Resources