简体   繁体   中英

Chartjs Add-Ons

I am using ChartJS to display a Scatter-Plot, and while I have created a basic ScatterPlot, I am having trouble adding specific features to my graph. I would like to highlight an acceptable range on my Y-Axis and add text to the highlighted range as seen below. Here is an example of what I am trying to recreate:

样本散点图

Here is what I have so far:

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <title>Getting Started with Chart JS</title>
  </head>
  <body>
    <canvas id="scatter-chart"></canvas>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.3/Chart.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-annotation/0.5.7/chartjs-plugin-annotation.js"></script>
    <script>
    var xLabels=['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
    var myChart= new Chart(document.getElementById("scatter-chart"), {
      type: 'scatter',
      data: {
      datasets: [{ 
        backgroundColor: "#399cff",
        pointStyle: 'rect',
        radius:15,
        pointHoverRadius: 15,
        // dummy values: enter user-data here for caloric intake. 
        // x=1: Monday
        // x=2: Tuesday
        // x=3: Wednesday
        // x=4: Thursday
        // x=5: Friday
        // x=6: Saturday
        // x=7: Sunday
        data: [
                {x: 1,y: 1200}, 
                {x: 2,y: 1000},
                {x: 3,y: 1500}, 
                {x: 4,y:1850},
                {x: 5,y:1600},
                {x:6,y:1750}, 
                {x:7,y:1400}
          ], 
            fill: true
          }
        ]
      },
      options: {
        scales: {
            xAxes: [{
                ticks: {
                    userCallback: function(label, index, labels) {
                        return xLabels[label-1];
                    }
                },

            }]
          },
          legend:{
              display:false
          },
          title: {
            display: true,
            fontSize: 30,
            text: 'Calories'
          }
        }
      });
    </script>

  </body>
</html>

I am a novice at Javascript (and StackOverflow in general) so any advice would be greatly appreciated.

There are some nice and ready-to-use plug-ins available for drawing rectangles on top of your chart. Maybe this one could help you out:

Code pen example

See the Annotation part in the Chart options:

annotation { annotations: [ ... ] {

GitHub source: https://github.com/chartjs/chartjs-plugin-annotation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM