score:4

Accepted answer

to show a legend you need to set the label property of a dataset, so the type of output you are expecting can be built by creating a chart from the code as shown below. fiddle -> https://jsfiddle.net/6nkcx8sq/

var topclicksourceschart = new chart('dashboard-click-source-chart', {
    type: 'bar',
    data: {
      labels: ["number of users"],
      datasets: [{
        label: 'facebook',
        data: [10],
        backgroundcolor: '#4d90c3',
      },
      {
        label: 'instagram',
        data: [15],
        backgroundcolor: '#866db2',
      },
      {
        label: 'twitter',
        data: [7],
        backgroundcolor: '#ea6f98',
      }],
    },
    options: {
        scales: {
            xaxes: [{
                display: false,
            }],
            yaxes: [{
            ticks: {
                beginatzero: true
            }
        }]
        },
        legend: {
            position: 'right',
            labels: {
                boxwidth: 10,
            }
        }
    }
});

score:0

i was able to get it with the following, but it was a pain in the ass for loops due to the backgroundcolor having to be inside the dataset.

var topclicksourcechart = new chart('dashboard-click-source-chart', {
    type: 'bar',
    data: {
      labels: ["facebook","google","none",],
      datasets: [
          {label: "facebook", data: [10]},{label: "google", data: [5]},{label: "none", data: [3]},
      ]
    },
    options: {
        scales: {
            xaxes: [{
                display: false,
            }],
            yaxes: [{
                ticks: {
                    beginatzero: true,
                }
            }]
        },
        legend: {
            position: 'right',
            labels: {
                boxwidth: 10,
            }
        }
    }
});
if (topclicksourcechart.data.datasets.length > 0) topclicksourcechart.data.datasets[0].backgroundcolor = '#4d90c3';
if (topclicksourcechart.data.datasets.length > 1) topclicksourcechart.data.datasets[1].backgroundcolor = '#866db2';
if (topclicksourcechart.data.datasets.length > 2) topclicksourcechart.data.datasets[2].backgroundcolor = '#ea6f98';
if (topclicksourcechart.data.datasets.length > 3) topclicksourcechart.data.datasets[3].backgroundcolor = '#61bdf6';
if (topclicksourcechart.data.datasets.length > 4) topclicksourcechart.data.datasets[4].backgroundcolor = '#768bb7';

here is the jsp/jstl loop:

data: {
  labels: [<c:foreach items="${clicksources}" var="cs">"${cs.key}",</c:foreach>],
  datasets: [
      <c:foreach items="${clicksources}" var="cs">{label: "${cs.key}", data: [${cs.value}]},</c:foreach>
  ]
},

i still could not find a way to make the top of the bars rounded.

enter image description here


Related Query

More Query from same tag