2017-03-09 117 views
0

我使用chart.js繪製了一個折線圖。對於標籤和數據集,我從數據庫中獲取值。我對chart.js和它非常強大的庫很陌生,但我無法完全理解它。我想繪製多個水平線。就像數據集的平均值,標準偏差以及最小和最大值一樣。我在這裏試過這個問題在stackoverflow,但這些給錯誤或可能是我無法理解的工作。這是我的chart.js之代碼在v2上的chart.js上在圖表上繪製水平線

function display_graph(id, label, data) { 
var ctx = document.getElementById(id); 
var data = { 
    labels: data.labels, 
    datasets: [ 
     { 
      label: label, 
      fill: false, 
      lineTension: 0.1, 
      backgroundColor: "rgba(75,192,192,0.4)", 
      borderColor: "rgba(75,192,192,1)", 
      borderCapStyle: 'butt', 
      borderDash: [], 
      borderDashOffset: 0.0, 
      borderWidth: 1, 
      borderJoinStyle: 'miter', 
      pointBorderColor: "rgba(75,192,192,1)", 
      pointBackgroundColor: "#fff", 
      pointBorderWidth: 1, 
      pointHoverRadius: 5, 
      pointHoverBackgroundColor: "rgba(75,192,192,1)", 
      pointHoverBorderColor: "rgba(220,220,220,1)", 
      pointHoverBorderWidth: 2, 
      pointRadius: 1, 
      pointHitRadius: 10, 
      data: data.assay_value, 
      spanGaps: false 
     } 
    ] 
}; 

//options 
var options = { 
    responsive: true, 
    title: { 
     display: true, 
     position: "top", 
     text: label, 
     fontSize: 18, 
     fontColor: "#111" 
    }, 
    legend: { 
     display: true, 
     position: "bottom", 
     labels: { 
      fontColor: "#333", 
      fontSize: 16 
     } 
    } 
}; 
var Blanks_Chart=null; 
Blanks_Chart = new Chart(ctx, { 
    type: 'line', 
    data: data, 
    options: options 
});} 

回答

4

你可以使用圖表上的chart.js annotation plugin輕鬆地畫線,而不必亂用在你的畫布渲染手動像素(即給你錯誤的老辦法)。請注意,該插件由chart.js創建/支持,並在chart.js docs中提及。

這是一個example codepen演示在圖表上創建一條線。

一旦添加插件,您只需在圖表配置中設置annotation屬性即可。這是一個例子。

var myChart = new Chart(ctx, { 
    type: 'line', 
    data: { 
    labels: ["January", "February"], 
    datasets: [{ 
     label: 'Dataset 1', 
     borderColor: window.chartColors.blue, 
     borderWidth: 2, 
     fill: false, 
     data: [2, 10] 
    }] 
    }, 
    options: { 
    responsive: true, 
    title: { 
     display: true, 
     text: 'Chart.js Draw Line On Chart' 
    }, 
    tooltips: { 
     mode: 'index', 
     intersect: true 
    }, 
    annotation: { 
     annotations: [{ 
     type: 'line', 
     mode: 'horizontal', 
     scaleID: 'y-axis-0', 
     value: 5, 
     borderColor: 'rgb(75, 192, 192)', 
     borderWidth: 4, 
     label: { 
      enabled: false, 
      content: 'Test label' 
     } 
     }] 
    } 
    } 
}); 
+0

這不適用於離子。任何想法 ? –

+0

您是否收到任何錯誤?你能描述發生了什麼嗎?這可能是chart.js版本控制的一個簡單問題。該解決方案的目標是chart.js v2.3.0(問題得到解答時的最新版本),但是最新版本(v2.7.1)中的某些選項和API已更改。 – jordanwillis

+0

現已解決:https://stackoverflow.com/questions/47655173/chart-js-v2-draw-horizo​​ntal-baraverage-over-vertical-bar/47752998#47752998。感謝喬丹! –