2013-05-22 71 views
0

我已经把我的y轴标题放在轴的顶部,以可读的方式(所以,转过90°;像here)。但问题是,y轴标题越长,图形被推开的越多。我可以用“偏移”来纠正。具有不同长度的Y轴标题时,可以在Highcharts中自动实现y轴标题偏移?

title: 
{ 
    text: "Very important data here", 
    align: 'high', 
    rotation: 0, 
} 

现在,我有相当多的图表。它们都在同一个图表中有三个翻译(de,en,fr)作为文本元素。所以,代码总是一样的。没有可能为每个翻译手动调整偏移量。

因此,我试图找到一个计算短期和长期标题(如here)的正确偏移量的公式。现在,我正在使用“偏移量:txt.length * -5.5”;但是标题越长越好。试图使用SQRT,但不是真的成功。

offset: txt.length * -5.5, 

有没有人有一个干净的方式来做到这一点?

回答

1

你可以让Highcharts绘制默认图表与错偏移,然后计算出什么是标题和更新的简单偏移宽度:

chart: { 
     events: { 
      load: function() { 
       var chart = this, 
        yAxis = chart.yAxis[0], 
        firstLabel = yAxis.ticks[yAxis.tickPositions[0]].labelBBox.width, 
        lastLabel = yAxis.ticks[yAxis.tickPositions[yAxis.tickAmount - 1]].labelBBox.width, 
        bb = yAxis.axisTitle.getBBox(); 
       yAxis.update({ 
        title: { 
         offset: -bb.width + (firstLabel > lastLabel ? firstLabel : lastLabel) //make sure that will be enough space for yAxis labels 
        } 
       }); 
      } 
     } 
    } 

而且的jsfiddle:http://jsfiddle.net/kL5md/6/

Highcharts 4.x的演示: http://jsfiddle.net/kL5md/21/

+0

哇,听起来不错。但是,我不明白它的工作原理。 [here](http://geodev.grid.unep.ch/megatrends/data/bip_ch.php?lang=de)现实中的例子。在Highcharts跑完它之后,我必须加载事件吗?非常感谢你的帮助! – luftikus143

+0

您必须将Highcharts升级至3.0+ –

+0

太棒了!非常感谢! – luftikus143

0

上述代码在系列动态添加到图形时不会工作。在这种情况下,只需将上面的代码放入串行对象下的afterAnimate事件即可。

plotOptions:{ 
 
       series:{ 
 
        events:{ 
 
         afterAnimate: function(){ 
 
          console.log('test', this.chart.yAxis[0]); 
 
          var chart = this.chart, 
 
          yAxis = chart.yAxis[0], 
 
          tp = yAxis.tickPositions, 
 
          firstLabel = yAxis.ticks[tp[0]].label.getBBox().width, 
 
          lastLabel = yAxis.ticks[tp[tp.length - 1]].label.getBBox().width, 
 
          bb = yAxis.axisTitle.getBBox(); 
 

 
          yAxis.update({ 
 
           title: { 
 
            offset: -bb.width + (firstLabel > lastLabel ? firstLabel : lastLabel) + 15 
 
           } 
 
          }); 
 
         } 
 
        } 
 
       }, 
 
      }