2017-03-13 139 views
1

請看看這個fiddle手柄X軸標籤位置圖JS

如果調整輸出窗口,你會發現,x軸的標籤變得傾斜。這對我來說很好。但是如果你注意到標籤的結束位置是酒吧的中心。我希望標籤的結束位置是酒吧的右側。如何實現這一目標?

我的配置是

var myChart = new Chart(ctx, { 
    type: 'bar', 
    data: { 
     labels: ["2 Jan", "9 Jan", "16 Jan", "23 Jan", "30 Jan", "6 Feb", "13 Feb"], 
     datasets: [{ 
      data: [6, 87, 56, 15, 88, 60, 12], 
     }] 
    }, 
    options: { 
     legend: { 
      "display": false 
     }, 
     tooltips: { 
      "enabled": false 
     }, 
     scales: { 
      yAxes: [{ 
       display: false, 
       gridLines: { 
        display : false 
       }, 
       ticks: { 
        display: false, 
        beginAtZero:true 
       } 
      }], 
      xAxes: [{ 
       gridLines: { 
        display : false 
       }, 
       ticks: { 
        beginAtZero:true 
       } 
      }] 
     } 
    } 
}); 

回答

2

這當然是可能實現一個「正確」的對齊規模Tick標誌代替了原來的「中心」對齊規模Tick標誌,但不幸的是它是不是很簡單的實現。讓我來引導你如何去做,然後提供一個例子。

1)首先,由於沒有配置選項來控制它,所以我們必須考慮做某種自定義實現。事實證明,條形圖中的刻度刻度標籤是作爲Category刻度的繪製方法的一部分呈現的。因此,我們必須以某種方式覆蓋此draw方法以更改爲新的對齊方式。

2)根據API有文件的方式來創建新的規模類型,所以我們應該能夠使用類似的方法來延長Category階類型和覆蓋它的draw方法。

由於所有的尺度在ScaleService包裹起來,我們必須使用下面的方法來擴展現有規模型。

var CategoryRightAligned = Chart.scaleService.getScaleConstructor('category').extend({}); 

3)現在它只是一個搞清楚draw方法,我們需要修改的哪一部分的問題。看完它後,看起來我們需要更改計算labelX(渲染刻度標籤的像素位置)的邏輯。這將是新的邏輯。

// current logic for getting pixel value of each label (we will use the logic below to 
// adjust if necessary) 
labelX = me.getPixelForTick(index, gridLines.offsetGridLines) + optionTicks.labelOffset; 

// get a reference to the bar chart controller so we can determine the chart's bar width 
var meta = me.chart.getDatasetMeta(0); 

// use the bart chart controller to calculate the bar width 
var barWidth = meta.controller.calculateBarWidth(meta.controller.getRuler()); 

// if the labels are rotated, then move the pixel location from the middle of the bar 
// to the far right of the bar 
if (labelRotationRadians != 0) { 
    labelX += barWidth/2; 
} 

4)現在我們只需要註冊我們的新比例並配置圖表來使用它(而不是條形圖的默認分類比例)。

請參閱本jsfiddle的例子來看看它在行動和看到的一切是如何結合在一起的。

+0

這個解決方案不僅僅是真棒。謝謝,非常感謝... – Kenny