AmCharts5: get active dataItem on click LineSeries - amcharts

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

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>

How to assign different colors to chart labels on graph interface in amChart 5?

I have a simple amChart5 chart.
I would like to change the colors of the text that displays on the axes and assign a different color to each of these elements.
What I have:
What I want:
The documentation explains that you can change the color but it applies to the whole axis, to all elements at the same time.
Do you know if there is a way to treat each element individually?
A nice solution is to use an adapter like so:
xAxis.get("renderer").labels.template.adapters.add("fill", (fill, target) => {
if (target.dataItem && target.dataItem.dataContext) {
let category = target.dataItem.dataContext.category;
if (category === "Category 1") {
return "#ff0000";
} else if (category === "Category 2") {
return "#00ff00";
} else {
return "#0000ff";
}
}
return fill;
});
Full code:
am5.ready(() => {
let root = am5.Root.new("chartdiv");
let chart = root.container.children.push(am5xy.XYChart.new(root, {}));
let legend = chart.children.push(am5.Legend.new(root, {
centerX: am5.p50,
x: am5.p50
}));
let data = [
{
"category": "Category 1",
"value1": 10,
"value2": 1
},
{
"category": "Category 2",
"value1": 20,
"value2": 7
},
{
"category": "Category 3",
"value1": 15,
"value2": 3
}
];
let xAxis = chart.xAxes.push(am5xy.CategoryAxis.new(root, {
categoryField: "category",
renderer: am5xy.AxisRendererX.new(root, {})
}));
xAxis.data.setAll(data);
// ==================================================
xAxis.get("renderer").labels.template.adapters.add("fill", (fill, target) => {
if (target.dataItem && target.dataItem.dataContext) {
let category = target.dataItem.dataContext.category;
if (category === "Category 1") {
return "#ff0000";
} else if (category === "Category 2") {
return "#00ff00";
} else {
return "#0000ff";
}
}
return fill;
});
// ==================================================
let yAxis = chart.yAxes.push(am5xy.ValueAxis.new(root, {
renderer: am5xy.AxisRendererY.new(root, {})
}));
function makeSeries(name, fieldName) {
let series = chart.series.push(am5xy.ColumnSeries.new(root, {
name: name,
xAxis: xAxis,
yAxis: yAxis,
categoryXField: "category",
valueYField: fieldName
}));
series.data.setAll(data);
legend.data.push(series);
}
makeSeries("Series 1", "value1");
makeSeries("Series 2", "value2");
});
#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>

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>

Jq-Plot x-Axis Spacing

I am having an issue using a line chart getting the calculated labels in the x-axis to space properly. If I want to have 5 data points with a few missing (e.g. [1,50.1],[2,49.2],[5,20.4],[6,17],[7,23.3]), the x-axis will show 1 then 2 then a space where 3 and 4 should have been then 5, 6, and 7. What I would like is to have the 5th data point beside the 2nd data point (in the position where the 3rd data point would ideally be). Basically I am trying to hide a data point yet keep the x-axis value in the grid.
Any assistance is much appreciated.
Try this:
<script type="text/javascript">
$(document).ready(function () {
var plot2 = $.jqplot('chart2', [[[1,50],[2,49],[5,20],[6,17],[7,23]]], {
title: 'Plot',
axesDefaults: {
labelRenderer: $.jqplot.CanvasAxisLabelRenderer
},
axes: {
xaxis: {
label: "X Axis",
pad: 0,
ticks:[1,2,5,6,7] //you can create this dynamically
},
yaxis: {
label: "Y Axis"
}
}
});
});
UPDATE:
<script type="text/javascript">
$(document).ready(function () {
var producciones = [];
for (var i = 0; i < 2000; i++) { producciones.push(new Number(i),new Number(i)) }
var plot2 = $.jqplot('chart2', [producciones], {
title: 'Plot',
axesDefaults: {
labelRenderer: $.jqplot.CanvasAxisLabelRenderer
},
axes: {
xaxis: {
label: "X Axis",
pad: 0,
numberTicks: 100
},
yaxis: {
label: "Y Axis"
}
}
});
});

Resources