Amcharts to display only even numbers in Y-axis - amcharts

I am trying to have only even numbers from 0 and up on the Y-axis of a amcharts5 Line chart but i cannot figure it out how to.
Example: if the biggest value is 5 my Y-axis should how: 0, 2, 4, 6.
Is it possible to achieve this?
What I'm currently having:
var yAxis = chart.yAxes.push(
am5xy.ValueAxis.new(root, {
min: 0,
maxPrecision: 0,
maxDeviation: 0.1,
renderer: am5xy.AxisRendererY.new(root, {})
})
);
Result:
What I need to achieve:

Have you tried to play with the minGridDistance property referenced here?
var yAxis = chart.yAxes.push(am5xy.ValueAxis.new(root, {
renderer: am5xy.AxisRendererY.new(root, {
minGridDistance: 20
})
}));
Full example:
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.ValueAxis.new(root, {
renderer: am5xy.AxisRendererX.new(root, {})
}));
var yAxis = chart.yAxes.push(am5xy.ValueAxis.new(root, {
renderer: am5xy.AxisRendererY.new(root, {
minGridDistance: 20 // Play with it and see what happens...
})
}));
var series = chart.series.push(am5xy.LineSeries.new(root, {
name: "Series",
xAxis: xAxis,
yAxis: yAxis,
valueXField: "valueX",
valueYField: "valueY"
}));
var data = [],
valueX = 0,
valueY = 0;
for (var i = 0; i < 20; i++) {
data.push({ valueX: i, valueY: i });
}
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

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 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

google piechart pie background image

I am using google charts and here is my piechart code...I want to use background repeating image instead of colors. Is that possible with google charts?
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Task', 'Hours per Day'],
['Work', 1],
['Eat', 1],
['Commute', 1],
['Watch TV', 1],
['Sleep', 1]
]);
var options = {
pieSliceBorderColor : 'none',
chartArea:{left:5,top:5,width:390,height:390},
enableInteractivity:false,
pieStartAngle:30,
pieHole: 0.6,
slices: {
0: { color: 'brown', offset: 0.01 },
1: { color: 'brown', offset: 0.01 },
2: { color: 'brown', offset: 0.01 },
3: { color: 'brown', offset: 0.01 },
4: { color: 'brown', offset: 0.01 },
}
};
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
options.slices[sliceCount].color = 'transparent';
chart.draw(data, options);
}
there are no standard options to fill slices with repeating image
however, you can modify the chart's svg after it finishes drawing
on the 'ready' event,
create an image pattern and add to svg defs
then replace the 'fill' attribute on the chart elements that should have the image
pie chart slices are typically drawn with <path> elements
when there is only one slice (100%), a <rect> element is used
the legend is drawn with <circle>
keep in mind, if you need to create an image of the chart,
custom modifications such as these will not work when using method --> getImageURI
see following working snippet...
google.charts.load('current', {
callback: drawChart,
packages: ['corechart']
});
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Task', 'Hours per Day'],
['Work', 1],
['Eat', 1],
['Commute', 1],
['Watch TV', 1],
['Sleep', 1]
]);
var options = {
pieSliceBorderColor: 'none',
pieSliceText: 'none',
chartArea: {
bottom: 12,
left: 12,
top: 12,
width: 390,
height:390
},
enableInteractivity: false,
pieStartAngle: 30,
pieHole: 0.6,
slices: {
0: { color: 'brown', offset: 0.1 },
1: { color: 'brown', offset: 0.1 },
2: { color: 'brown', offset: 0.1 },
3: { color: 'brown', offset: 0.1 },
4: { color: 'brown', offset: 0.1 },
}
};
var container = $('#piechart')[0];
var chart = new google.visualization.PieChart(container);
google.visualization.events.addListener(chart, 'ready', function () {
// create image pattern
var svgNS = $('svg')[0].namespaceURI;
var pattern = document.createElementNS(svgNS, 'pattern');
pattern.setAttribute('id', 'whiteHat');
pattern.setAttribute('patternUnits', 'userSpaceOnUse');
pattern.setAttribute('width', 16);
pattern.setAttribute('height', 16);
var image = document.createElementNS(svgNS, 'image');
image.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', 'http://findicons.com/files/icons/512/star_wars/16/clone_old.png');
image.setAttribute('x', 0);
image.setAttribute('y', 0);
image.setAttribute('width', 16);
image.setAttribute('height', 16);
pattern.appendChild(image);
$('#defs')[0].appendChild(pattern);
// add image to pie slices
$('svg path').attr('fill', 'url(#whiteHat)');
// add image to legend circles
$('svg circle').attr('fill', 'url(#whiteHat)');
// test chart image
$(container.parentNode).append('<img alt="Chart" src="' + chart.getImageURI() + '">');
});
chart.draw(data, options);
}
div {
padding: 6px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div>piechart</div>
<div id="piechart"></div>
<div>image</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