Рисование этого вида гистограммы с помощью chart.js можно сделать следующим образом.
var ctx = document.getElementById("myChart").getContext("2d");
var data = {
labels: ["Good", "Not good"],
datasets: [{
label: "Oranges",
backgroundColor: "orange",
data: [2, 1]
}, {
label: "Apples",
backgroundColor: "green",
data: [4, 2]
}, {
label: "Grapes",
backgroundColor: "purple",
data: [3, 1]
}]
};
var myBarChart = new Chart(ctx, {
type: 'bar',
data: data,
options: {
barValueSpacing: 20,
scales: {
yAxes: [{
ticks: {
min: 0,
}
}]
}
}
});
<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/Chart.js/2.7.3/Chart.bundle.min.js"></script>
<canvas id="myChart" width="400" height="400"></canvas>
Однако данные, предоставленные вашим API, не идеальны.Таким образом, вам придется манипулировать данными из вашего ответа следующим образом.
const res = {
fruits: [
{
oranges: {
good: 1,
not_good: 0
},
apples: {
good: 1,
not_good: 0
},
grapes: {
good: 2,
not_good: 0
}
}
]
};
const dataset = Object.entries(res.fruits[0]).map(fruit => {
return {
label: fruit[0],
data: Object.values(fruit[1])
};
});
console.log(dataset);
Учитывая, что backgroundColor
для каждого бара не входит в данные вашего API, вам также необходимо выяснить, откуда это взять.
Вот как все это может выглядеть вместе.
const res = {
fruits: [
{
oranges: {
good: 10,
not_good: 5
},
apples: {
good: 6,
not_good: 1
},
grapes: {
good: 9,
not_good: 5
},
pears: {
good: 15,
not_good: 6
}
}
]
};
const datasets = Object.entries(res.fruits[0]).map(fruit => {
return {
label: fruit[0],
data: Object.values(fruit[1]),
backgroundColor: getRandomColor()
};
});
const ctx = document.getElementById("myChart").getContext("2d");
const data = {
labels: ["Good", "Not good"],
datasets
};
const myBarChart = new Chart(ctx, {
type: 'bar',
data: data,
options: {
barValueSpacing: 20,
scales: {
yAxes: [{
ticks: {
min: 0,
}
}]
}
}
});
function getRandomColor() {
const letters = '0123456789ABCDEF';
let color = '#';
for (let i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
<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/Chart.js/2.7.3/Chart.bundle.min.js"></script>
<canvas id="myChart" width="400" height="400"></canvas>
JSfiddle
getRandomColor из этого ответа