amCharts pie chart how to customize the balloon text - javascript

I am using amCharts pie chart (v3) and I want to customize the pop up balloon that comes on mouseover on a slice: in addition to routine text like [[value]] [[percent]],
(a) a text that depends on the data item, and
(b) provide different click options to the user depending on data item. Every data row might not have these possibilities in which case the options should not appear.
For example, the pie chart might show wine consumption by country. On hover, I want to provide the user two different click options - one to see consumption by season if available, plus another to see consumption by age group if available.
Is it possible to do so in amCharts? I saw an exit for event clickSlice() here http://docs.amcharts.com/3/javascriptcharts/AmPieChart but nothing on how to modify the balloon text on the fly and add behavior to the balloon that comes on hover.
Will greatly appreciate your help.

For writing dynamic text in the balloon you can also do the folowing:
"graphs": [{
"balloonFunction": function(graphDataItem, graph) {
var value = graphDataItem.values.value;
if (value < 500) {
return value + "<br>(Little)";
} else {
return value + "<br>(A Lot)";
}
}
}],

You can use the following tags: [[title]], [[description]], [[value]] and [[percent]]. says the documentation.
I have used description for a custom field, it works fine.

You can add any custom field to your data provider and then display it in your balloon in the same way as value:
{value:15, title:"slice title", someCustomField:"some custom data"}
and then:
chart.balloonText = "[[someCustomField]]";

Related

How I can manipulate with legend items on the chart from AgChartsReact?

I use a standalone chart from the Ag Grid library and want to manipulate manually which legend items should be shown/selected by default. I didn't find any specific API/property which can cover this use-case.
E.g., I want to see selected only the diesel legend item (and petrol should be shown unselected),
AgChartsReact always shows all legend items.
What did I investigate and try?
The chart is a canvas element, so I thought that it is possible to manipulate legend items from the canvas context, which I can get with useRef hook. But I cannot find how exactly it can be done and is it possible? Here is a ref to Plunker
UPD:
if someone is looking for how to store the data which legends is active or not, here is a function to get this (the same function you will find in Plunker):
const getLegendStatuses = () => {
const [changeEvent] = chartRef.current.chart.legend.allEventListeners.get("change");
const [, data] = changeEvent;
const [event] = data;
console.log(
event.data.map(({ enabled, label }) => ({ label: label.text, enabled }))
);
}
I think you want to use visible: false on the Petrol series.
This will still show up as greyed out in the legend, but you can click it to open it again.
You can also add showInLegend: false if you want to remove it from the legend.
If you want it greyed out in the legend but NOT clickable on the legend to make it visible, you might be able to make a custom listener for nodeClick, but I haven't tried that.

Amcharts drill-down to countries, adding clickable links

Adding hyperlinks to maps was already addressed here :
amcharts drill-down map countries clickable
But I am wondering what I would need to change if I were to instead add clickable hyperlinks to the states or provinces within the countries in the 'drill down to countries' example?
https://www.amcharts.com/demos/drill-down-to-countries/
For instance, if I were to click on China and view the provinces, how would I assign a URL to its most southern province, Guangxi Zhuang, by using both the methods that you mentioned above?
The ID for that territory is "CN-GX", and can be found in this file :
https://github.com/amcharts/amcharts4-geodata/blob/master/dist/es2015/chinaHigh.js
Thanks for your help!
As indicated in the linked answer, you can set a url propertyField for the PolygonSeries so that it can apply the URL from the data provided to the series. You can combine this with the done event handler in the countrySeries (the drilled down map) to populate the series' data with the desired information based on the loaded geodata url. For example:
countrySeries.mapPolygons.template.propertyFields.url = "url";
countrySeries.geodataSource.events.on("done", function(ev) {
worldSeries.hide();
countrySeries.show();
if (ev.target.url.indexOf('china') != -1) {
countrySeries.data = [{
id: "CN-GX",
url: "https://en.wikipedia.org/wiki/Guangxi"
}];
}
});
Obviously you'll want to make this more robust in your application, but you get the idea.
Demo of your Guangxi scenario

add message on hover series name highcharts

i'm trying to add a message when hover a series name and i just cant find the way to do it,
this is what i want want to happen:
when the user hover the "all your locations" series name the red box will apear.
as for now the only way i found to do it is to search div contains the same words but its a really bad practice and im pretty sure there is a better way to do it..
is it possible to do it via highcharts ?
A popup like that is not in the Highchart API for the legend. The closet thing is Legend.ItemOnHover
legend: {
itemHoverStyle: {
color: '#FF0000'
}
}
But that really only styles it.
The way you are currently doing it is probably fine if you are careful about it.
You can try to add tooltip to the legend item, like in the related topic Add tooltip to legend in highcharts when hovering
the only way i have found to do this popup is by adding this function in the end of the function building the chart :
var titles = $("tspan");
$("tspan").each(function(index) {
if( (this.textContent.indexOf("cashiers data") !== -1) ){
$(titles[index]).click(function(){
alert('to use our new cashiers bars \n'
+'please contact us at our contact page');
return false;
})
}
});

Persisting flot legend label checkbox on un-check

I have a scenario where I want to toggle series based on checkbox selection. I have added the checkbox to the legend using labelFormatting in legend option like:
var otherOptions = {
legend: {
container: legend,
labelFormatter: function (label, series) {
var cb = '<input type="checkbox" name="' + label + '" checked="checked" id="id' + label + '"> ' + label;
return cb;
}
},
};
And I have added the click event for the legend so that I can manipulate the series based on checked items. It all works fine except when I uncheck a label in legend, on re-draw it removes that series line from the legend as well. So for ex., below is the before and after image:
Before
After
Notice that in after image "USA" checkbox is missing.
Is there any way I can still show the unchecked "USA" checkbox in legend?
I looked at the suggestion here: flot graph, use legend to turn on/off series
But the only problem is that I don't want to have legend AND checkbox legend separate. The question on the given link was answered 1+ year ago so I thought I am gonna take a chance and ask the question again in case someone knows a way to do this.
Please let me know.
Thanks!
Instead of removing the series all together if the checkbox is unchecked, add it with empty data.
Something like this:
function plotByChoice(doAll)
{
$('#legend .legendCB').each(
function(){
if (this.checked)
{
data.push(datasets[someLabel]);
}
else
{
data.push({label: someLabel, data: []})
}
}
);
// plot call etc...
}
Working fiddle is here.
For anyone looking for a clean solution AND for Chart.js v3 :
This is unfortunately not possible for Chart.js v3 as legends are generated with text (no HTML can be appended to the legend itself, unfortunately).
We have to use generateLabels function to render the legend labels.
I suggest using the pointStyle option to render an image (checkbox, actually), instead of a rectangle by default, so we can rerender automatically everytime the user checks or not the legend (it's dynamic, ofc, and we don't have to do something complicated programmatically).
So, first, generate the 2 images, corresponding to the checkboxes (I'm using FontAwesome icons that I've generated in PNG from SVG files) :
let checkboxYes = new Image(14, 14);
checkboxYes.src = '/static/img/check_yes.png';
let checkboxNo = new Image(14, 14);
checkboxNo.src = '/static/img/check_no.png';
Then, we can use it in the Chart.js options:
legend: {
labels: {
usePointStyle: true,
generateLabels: function(chart) {
labels = Chart.defaults.plugins.legend.labels.generateLabels(chart);
for (var key in labels) {
labels[key].pointStyle = labels[key].hidden ? checkboxNo : checkboxYes
}
return labels;
}
}
},
Explanations
I'm setting usePointStyle to true so that I can customize the point style
later
Chart.defaults.plugins.legend.labels.generateLabels(chart) kind of pre generate the labels for me (and store it into labels), so it's like a function override!
Then for each label, I'm changing its pointStyle to the checkbox image depending on the hidden parameter (if the user checked the box)
Finally, return the labels
It's perhaps not the best solution, but works amazingly well for me:
Click here to see the animated result in GIF :)

Google visualization geomap

I know from reading the assoc. Google group that there is not currently an event for clicking a specific point when using the marker map (only regionClick is implemented).
But was reading the docs and noticed the event Select which says:
select Fired when the user clicks a visual entity. To learn what has
been selected, call getSelection(). None
and
setSelection() none Selects the specified chart entities. Cancels any
previous selection. Selectable entities are regions with an assigned
value. A region correlates to a row in the data table (column index is
null). For this chart, only one entity can be selected at a time.
Extended description.
Would I be able to use this to get the entry that was clicked?
Example:
data.addRows([
['Rome', 2761477, 1285.31],
['Milan', 1324110, 181.76],
['Naples', 959574, 117.27],
['Turin', 907563, 130.17],
['Palermo', 655875, 158.9],
['Genoa', 607906, 243.60],
['Bologna', 380181, 140.7],
['Florence', 371282, 102.41]
]);
Somehow get that Milan was clicked? How would I do this? Or am I reading this wrong?
Google API for Geomaps: http://code.google.com/apis/chart/interactive/docs/gallery/geochart.html
Google Group stating there is no click event in Marker mode:
https://groups.google.com/forum/?fromgroups#!topic/google-visualization-api/K8uJoes8ZH0
You need call getSelection function when the select event is called. This function returns an array of objects. Each object have row and column attributes (if any). Use the row and the first column (0) to retrieve the label name (Rome, Milan, ...).
Example (http://jsfiddle.net/VtZQh/):
google.visualization.events.addListener(chart, 'select', function() {
var selection = chart.getSelection()[0];
var label = data.getValue(selection.row, 0);
alert(label);
});
Please refer to documentation to know more about getSelection.

Categories