[Chartjs]-Place Text in Chart-Canvas Area in ChartJS

2👍

An working example:

var plugin = {
  id: 'plugin',
  beforeDraw: function(chart) {

    var width = chart.chart.width,
      height = chart.chart.height,
      ctx = chart.chart.ctx,
      xScale = chart.scales['x-axis-0'],
      yScale = chart.scales['y-axis-0'];

    ctx.restore();
    ctx.font = "1em sans-serif";
    ctx.textAlign = "center";
    ctx.textBaseline = "middle";
    // ctx.fillText("s(A)", width * .28, height * .70);
    ctx.fillText(
      "s(A)",
      xScale.getPixelForValue('2005'),
      yScale.getPixelForValue(3)
    );
    ctx.fillText(
      "s(B)",
      xScale.getPixelForValue('2015'),
      yScale.getPixelForValue(9)
    );
    ctx.save();
  }
};

var xCoord = new Array(1997, 2003, 2005, 2009, 2014, 2018, 2019);
var yCoord = new Array(1, 3, 5, 3, 6, 10, 9);
var c = [];
for (var i = 0; i < xCoord.length; i++) {
  var obj = {
    x: xCoord[i],
    y: yCoord[i]
  };
  c.push(obj);
}
var ctx = document.getElementById('myTau').getContext('2d');
var myTau = new Chart(ctx, {
  type: 'line',
  data: {
    datasets: [{
      label: 'None',
      data: c,
      borderWidth: 1,
      borderColor: "#ef1414",
      fill: false,
      cubicInterpolationMode: 'monotone'
    }]
  },
  plugins: [plugin],
  options: {
    title: {
      display: true,
      text: 'My Chart 2'
    },
    tooltips: {
      mode: 'nearest',
      intersect: true
    },
    scales: {
      xAxes: [{
        type: 'linear',
        position: 'bottom',
        scaleLabel: {
          display: true,
          labelString: 'Year Assembly',
          fontSize: 14
        }
      }],
      yAxes: [{
        scaleLabel: {
          display: true,
          labelString: 'Aquifer Values Corresponding',
          fontSize: 15
        }
      }]
    }
  }
});
var ctx = document.getElementById('myTax').getContext('2d');
var myTau = new Chart(ctx, {
  type: 'line',
  data: {
    datasets: [{
      label: 'None',
      data: c,
      borderWidth: 1,
      borderColor: "#ef1414",
      fill: false,
      cubicInterpolationMode: 'monotone'
    }]
  },
  options: {
    title: {
      display: true,
      text: 'My Chart 2'
    },
    tooltips: {
      mode: 'nearest',
      intersect: true
    },
    scales: {
      xAxes: [{
        type: 'linear',
        position: 'bottom',
        scaleLabel: {
          display: true,
          labelString: 'Year Assembly',
          fontSize: 14
        }
      }],
      yAxes: [{
        scaleLabel: {
          display: true,
          labelString: 'Aquifer Values Corresponding',
          fontSize: 15
        }
      }]
    }
  }
});
<canvas id="myTau" height="120"></canvas>
<canvas id="myTax" height="120"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.bundle.min.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>

Create and register a new plugin that draw the text, then call it only on the second chart, you can pass data as well (like an array of labels and the locations of each for example).


Update: (register plugins)

If you register a plugin globally then, you will have to disable the plugin in each chart here you don’t want it to run.

options: {
    plugins: {
        plugin: false
    }
}

– or –

If you don’t register the plugin globally, in each chart that you need to add the labels add the following:

{
    plugins: [plugin]
}

Note: In the second snippet of code plugin is not nested under options. Seen here.


Update: (display text using x,y datasets)

In order to use a x,y value you need to identify the axes you what the value from using its id, the defaults are x-axis-0 and y-axis-0, that increments if you add more axes. Or use a custom axis id.

After that, within the chart instance there is a scale object that represents the axis and using chart.scales['x-axis-0'] you can access a function called getPixelForValue which will convert the giving value from that axis to its pixel location.

0👍

<!DOCTYPE html>
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <div class="w3-row">
        <div class="w3-col s3"><p></p></div>
        <div class="w3-col s6" align="center"><canvas id="myChart" height="120"></canvas></div>
        <div class="w3-col s3"><p></p></div>
    </div>
    <div class="w3-row">
        <div class="w3-col s3"><p></p></div>
        <div class="w3-col s6" align="center"><canvas id="myTau" height="120"></canvas></div>
        <div class="w3-col s3"><p></p></div>
    </div>
</body>
</html>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.bundle.min.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0"></script>
<script type="text/javascript">
    var plugin = {
        beforeDraw: function (chart) {
            var width = chart.chart.width,
                height = chart.chart.height,
                ctx = chart.chart.ctx;
            ctx.restore();
            ctx.font = "1em sans-serif";
            ctx.textAlign = "center";
            ctx.textBaseline = "middle";
            ctx.fillText("s(A)", width * .28, height * .70);
            ctx.fillText("s(B)", width * .75, height * .55);
            ctx.save();
        }
    };
    Chart.plugins.register(plugin);

    var xCoord = new Array(1997, 2003, 2005, 2009, 2014, 2018, 2019);
    var yCoord = new Array(1, 3, 5, 3, 6, 10, 9);
    var c = [];
    for (var i = 0; i < xCoord.length; i++) {
        var obj = { x: xCoord[i], y: yCoord[i] };
        c.push(obj);
    }
        var ctx = document.getElementById('myChart').getContext('2d');
        var myChart = new Chart(ctx, {
            type: 'line',
            data: {
                datasets: [{
                    label: 'None',
                    data: c,
                    borderWidth: 1,
                    borderColor: "#3e95cd",
                    fill: false,
                    cubicInterpolationMode: 'monotone'
                }
                ]
            },
            options: {
                plugins: [plugin],
                title: {
                    display: true,
                    text: 'My Chart'
                },
                tooltips: {
                    mode: 'nearest',
                    intersect: true
                },
                scales: {
                    xAxes: [{
                        type: 'linear',
                        position: 'bottom',
                        scaleLabel: {
                            display: true,
                            labelString: 'Year Assembly',
                            fontSize: 14
                                    }
                    }],
                    yAxes: [{
                        scaleLabel: {
                            display: true,
                            labelString: 'Aquifer Values',
                            fontSize: 15
                                    }
                    }]
                }
            }
        });
</script>

<script type="text/javascript">
    var xCoord = new Array(1997, 2003, 2005, 2009, 2014, 2018, 2019);
    var yCoord = new Array(41, 31, 11, 31, 88, 101, 91);
    var c = [];
    for (var i = 0; i < xCoord.length; i++) {
        var obj = { x: xCoord[i], y: yCoord[i] };
        c.push(obj);
    }
    var ctx = document.getElementById('myTau').getContext('2d');
    var myTau = new Chart(ctx, {
        type: 'line',
        data: {
            datasets: [{
                label: 'None',
                data: c,
                borderWidth: 1,
                borderColor: "#ef1414",
                fill: false,
                cubicInterpolationMode: 'monotone'
            }
            ]
        },
        options: {
            title: {
                display: true,
                text: 'My Chart 2'
            },
            tooltips: {
                mode: 'nearest',
                intersect: true
            },
            scales: {
                xAxes: [{
                    type: 'linear',
                    position: 'bottom',
                    scaleLabel: {
                        display: true,
                        labelString: 'Year Assembly',
                        fontSize: 14
                    }
                }],
                yAxes: [{
                    scaleLabel: {
                        display: true,
                        labelString: 'Aquifer Values Corresponding',
                        fontSize: 15
                    }
                }]
            }
        }
    });
</script>

Here is problem. The text is written all charts. My aim is only red one chart (My Chart 2).

Leave a comment