amcharts customized label position

3.5k Views Asked by At

Right now my graph's label is placed in a default position, but my label texts are rather long and its sticking out from the graph.

If possible, I want to place it so that the labels don't stick out from the graph.

Pic of Current situation & Ideal graph

Or if the above is not possible, I want to fix the visible labels. Is this possible? right now, the "best" label gets lost/hidden when the graph width is reduced. The "too much" label also gets lost when the width is largely reduced.

I have been searching all over stackoverflow and amcharts website but I can't seem to find a good solution. Is there any way to solve either of the problems...?

// tried these but doesnt work for what I want to do
va.labelOffset = -5;
va.position = "bottom";
va.inside = false;

full code in JSfiddle

1

There are 1 best solutions below

0
On BEST ANSWER

In order to keep the chart from hiding the labels on resize, you need to disable the valueAxis' autoGridCount and set the gridCount to the number of tick marks you want to see. You'll also need to remove the labelFrequency setting.

va.autoGridCount = false;
va.gridCount = 3;
//va.labelFrequency = 5;

As for label positioning, you are limted to rotating and vertical offsets out of the box. As a workaround, you can position the labels by modifying the SVG nodes directly through the drawn event, for example:

// prior to chart.write
chart.addListener("drawn", function(e) {
  var textNodes = e.chart.valueAxes[0].labelsSet.node.childNodes;
  var transform;

  //Position "too little"
  transform = parseTransform(textNodes[0].getAttribute('transform'));
  transform.translate[0] = parseFloat(transform.translate[0]) + 25;
  textNodes[0].setAttribute('transform', serializeTransform(transform));
  // Position "too much"
  transform = parseTransform(textNodes[2].getAttribute('transform'));
  transform.translate[0] = parseFloat(transform.translate[0]) - 25;
  textNodes[2].setAttribute('transform', serializeTransform(transform));

});

// ...

// from http://stackoverflow.com/questions/17824145/parse-svg-transform-attribute-with-javascript
function parseTransform(a) {
  var b = {};
  for (var i in a = a.match(/(\w+\((\-?\d+\.?\d*e?\-?\d*,?)+\))+/g)) {
    var c = a[i].match(/[\w\.\-]+/g);
    b[c.shift()] = c;
  }
  return b;
}

//serialize transform object back to an attribute string
function serializeTransform(transformObj) {
  var transformStrings = [];
  for (var attr in transformObj) {
    transformStrings.push(attr + '(' + transformObj[attr].join(',') + ')');
  }
  return transformStrings.join(',');
}

Updated fiddle