0

I'm using chart.js to graph my data.

enter image description here

I'm wondering if I can show the flag image/icon PNG for the labels.

function drawChart(obj, columnName, type = 'bar', selectedVal){

var ajax = $.ajax({url: '/query/' + obj + '/'+ columnName + '/' + selectedVal });
ajax.done(function (response) {

    console.log('Response from API >>',response);
    $('.lds-ripple').fadeOut();

    var selector = `chart-${columnName}`;

    var chartHtml = `<div class="col-sm-6"><canvas class="chart" id="${selector}" height="200"></canvas></div>`;
    $('.charts').append(chartHtml);


    keys   = [];
    values = [];

    var length = 0


    $.each(response, function(key,val) {
        //console.log(key+val);

        length++;

        if(length<15){
            keys.push(key);
            values.push(val);
        }
        
    });

    var showLegend = false; 
    if(type == 'doughnut' || type == 'radar' || type == 'polarArea' || type == 'pie'){
        showLegend = true; 
    }


    let chart = document.getElementById(selector).getContext('2d');
    let xAxisTitle = columnName;
    var sumOfAllValues = values.reduce((a, b) => a + b, 0);
    Chart.defaults.global.defaultFontColor = "#fff";


    var ticksDisplay = true;
    if(columnName == 'country'){
        ticksDisplay = false;
    }

    const images = ['https://i.stack.imgur.com/2RAv2.png', 'https://i.stack.imgur.com/Tq5DA.png', 'https://i.stack.imgur.com/3KRtW.png', 'https://i.stack.imgur.com/iLyVi.png'];

    new Chart(chart, {
        type: type, // bar, horizontalBar, pie, line, doughnut, radar, polarArea
        plugins: [{
            afterDraw: chart => {      
                var ctx = chart.chart.ctx; 
                var xAxis = chart.scales['x-axis-0'];
                var yAxis = chart.scales['y-axis-0'];
                xAxis.ticks.forEach((value, index) => {  
                    var x = xAxis.getPixelForTick(index);  
                    var y = yAxis.getPixelForTick(index);      
                    var image = new Image();
                    image.src = images[index],
                    ctx.drawImage(image, x - 12, yAxis.bottom + 10);
                    // ctx.drawImage(image, x + 12, yAxis.left - 10);
                });      
            }
        }],
        data:{
            labels: keys,
            datasets:[{
                label:'Count',
                data:values,
                borderWidth:2,
                hoverBorderWidth:2,
                hoverBorderColor:'#fff',
                color:'#fff',
                backgroundColor: neonBgColors,
                borderColor: neonBgBorders,
                defaultFontColor: 'white'
            }
            ]
        },
        options:{
            title:{
                display:true,
                fontSize: 20,
                text: columnName + '(' + sumOfAllValues + ')'
            },
            legend:{
                display:showLegend,
                position:'right',
                labels:{
                    fontColor:'#000'
                }
            },
            scales: {
                xAxes: [{
                    ticks: {
                        precision:0,
                        beginAtZero: true
                    },
                    scaleLabel: {
                        display: true,
                        labelString: xAxisTitle + ' (' + sumOfAllValues +  ')'
                    }
                }],
                yAxes: [{
                    ticks: {
                        precision:0,
                        beginAtZero: true,
                        display: ticksDisplay,
                    },
                    scaleLabel: {
                        display: true,
                        // labelString: 'Visitor Count'
                    }
                }]
            },
            layout: {
                padding: {
                    bottom: 30
                }
            },
        }




    });


});
}

I kept getting

enter image description here

code-8
  • 54,650
  • 106
  • 352
  • 604

1 Answers1

1

I adapted the code of this answer and came up with the following solution for your case.

const labels = ['Red Vans', 'Blue Vans', 'Green Vans', 'Gray Vans'];
const images = ['https://i.stack.imgur.com/2RAv2.png', 'https://i.stack.imgur.com/Tq5DA.png', 'https://i.stack.imgur.com/3KRtW.png', 'https://i.stack.imgur.com/iLyVi.png']
  .map(png => {
    const image = new Image();
    image.src = png;
    return image;
  });
const values = [48, 56, 33, 44];

new Chart(document.getElementById("myChart"), {
  type: "horizontalBar",
  plugins: [{
    afterDraw: chart => {
      var ctx = chart.chart.ctx;
      var xAxis = chart.scales['x-axis-0'];
      var yAxis = chart.scales['y-axis-0'];
      yAxis.ticks.forEach((value, index) => {
        var y = yAxis.getPixelForTick(index);
        ctx.drawImage(images[index], xAxis.left - 40, y - 10);
      });
    }
  }],
  data: {
    labels: labels,
    datasets: [{
      label: 'My Dataset',
      data: values,
      backgroundColor: ['red', 'blue', 'green', 'lightgray']
    }]
  },
  options: {
    responsive: true,
    layout: {
      padding: {
        left: 50
      }
    },
    legend: {
      display: false
    },
    scales: {
      yAxes: [{
        ticks: {
          display: false
        }
      }],
      xAxes: [{
        ticks: {
          beginAtZero: true
        }
      }],
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="myChart" height="90"></canvas>
uminder
  • 23,831
  • 5
  • 37
  • 72