Chart.js Dropdown to select 1 day, yesterday and 7 days - javascript

<script src="https://cdn.jsdelivr.net/npm/chart.js#2.9.3/dist/Chart.min.js"
integrity="sha256-R4pqcOYV8lt7snxMQO/HSbVCFRPMdrhAFMH+vr9giYI=" crossorigin="anonymous"></script>
<div class="chart" style="position: relative; height:50vh; width:100%;margin: 0 auto;;">
<canvas id="myChart" width="400" height="400"></canvas></div>
<select id="date-choose">
<option value="Today">Today</option>
<option value="Yesterday">Yesterday</option>
<option value="7 Days">Last 7 Days</option>
</select>
<script>
function BuildChart(labels, values, chartTitle) {
var data = {
labels: labels,
datasets: [{
label: chartTitle, // Name the series
data: values,
backgroundColor: [
'rgba(50, 99, 231, 0.2)',
'rgba(50, 90, 231, 0.2)',
'rgba(50, 90, 231, 0.2)',
'rgba(50, 90, 231, 0.2)',
'rgba(50, 90, 231, 0.2)',
'rgba(50, 90, 231, 0.2)'
],
borderColor: [
'rgba(50, 90, 231, 1)',
'rgba(54, 162, 235, 1)',
'rgba(50, 90, 231, 1)',
'rgba(50, 90, 231, 1)',
'rgba(50, 90, 231, 1)',
'rgba(50, 90, 231, 1)'
],
borderWidth: 1
}],
};
Chart.defaults.global.defaultFontColor = '#151515';
var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
type: 'line',
data: data,
options: {
responsive: true, // Instruct chart js to respond nicely.
maintainAspectRatio: false, // Add to prevent default behaviour of full-width/height
scales: {
xAxes: [{
scaleLabel: {
display: true,
labelString: ''
}
}],
yAxes: [{
ticks: {
callback: function(value, index, values) {
if (Math.floor(value) === value) {
return value;
}
}
}
}]
},
}
});
//$('#legend').html(myChart.generateLegend());
return myChart;
}
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var json = JSON.parse(this.response);
console.log(json);
// Map json labels back to values array
var labels = json.feed.entry.map(function (e) {
return e.gsx$date.$t;
});
// Map json values back to values array
var values = json.feed.entry.map(function (e) {
return e.gsx$followers.$t;
});
for (i = 0; i < values.length; i++) {
if (values[i].charAt(0) == '-') {
values.length = values.length - 1;
labels.length = labels.length - 1;
} else if (values[i].charAt(0) == '+'){
values.length = values.length - 1;
labels.length = labels.length - 1;
}
}
for (i = 0; i < values.length; i++) {
values[i]= values[i].replace(/,/g, '');
}
BuildChart(labels.reverse(), values.reverse(), "Followers");
}
};
xhttp.open("GET", "https://spreadsheets.google.com/feeds/list/1nLLfOhAD6PGcIPc5mttyBFi1maoveEYpsz4MiU7JNAA/od6/public/full?alt=json", false);
xhttp.send();
</script>
I am using this chart to show the follower data of a certain person, I would like to have a dropdown in which the person can choose the interval they prefer to see or a dropdown with "yesterday", "last 3 days", "last 7 days" . Thanks in advance to those who take the trouble to help me. Is it possible to do something similar?
Thanks in advance

You can do that by changing the chart.config.options.scales.xAxes[0].ticks.max and chart.config.options.scales.xAxes[0].ticks.min values.
The code is above just note one thing: I noticed that the labels are in reverse time. The "today" date is on the right and the values on the left are days in the future.
I don't understand very well how you are trying to present the data but in any case that doesn't change the way how it is done. In the snippet above there is an example with an numeric input that adds a certain amount of days to the current date. So you would only need to translate that into your <select>.
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.9.3/dist/Chart.min.js" integrity="sha256-R4pqcOYV8lt7snxMQO/HSbVCFRPMdrhAFMH+vr9giYI=" crossorigin="anonymous"></script>
<div class="chart" style="position: relative; height:50vh; width:100%;margin: 0 auto;;">
<canvas id="myChart" width="400" height="400"></canvas></div>
Days from now: <input id="days" value="0" type="number" />
<br/>
<select id="date-choose" disabled>
<option value="1">Today</option>
<option value="2">Yesterday</option>
<option value="7">Last 7 Days</option>
</select>
<script>
let chart; // 1
let inp = document.getElementById("days");
inp.oninput = function() { // 3
const today = new Date().getTime() + +inp.value * 1000 * 60 * 60 * 24; // 4
const newMax = new Date(today).toISOString().split("T")[0]
console.log("newMax", newMax)
chart.config.options.scales.xAxes[0].ticks.max = newMax
chart.update();
};
function BuildChart(labels, values, chartTitle) {
var data = {
labels: labels,
datasets: [{
label: chartTitle, // Name the series
data: values,
backgroundColor: [
'rgba(50, 99, 231, 0.2)',
'rgba(50, 90, 231, 0.2)',
'rgba(50, 90, 231, 0.2)',
'rgba(50, 90, 231, 0.2)',
'rgba(50, 90, 231, 0.2)',
'rgba(50, 90, 231, 0.2)'
],
borderColor: [
'rgba(50, 90, 231, 1)',
'rgba(54, 162, 235, 1)',
'rgba(50, 90, 231, 1)',
'rgba(50, 90, 231, 1)',
'rgba(50, 90, 231, 1)',
'rgba(50, 90, 231, 1)'
],
borderWidth: 1
}],
};
Chart.defaults.global.defaultFontColor = '#151515';
var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
type: 'line',
data: data,
options: {
responsive: true, // Instruct chart js to respond nicely.
maintainAspectRatio: false, // Add to prevent default behaviour of full-width/height
scales: {
xAxes: [{
scaleLabel: {
display: true,
labelString: ''
},
}],
yAxes: [{
ticks: {
callback: function(value, index, values) {
if (Math.floor(value) === value) {
return value;
}
}
}
}]
},
}
});
return myChart;
}
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var json = JSON.parse(this.response);
//console.log(json);
// Map json labels back to values array
var labels = json.feed.entry.map(function(e) {
return e.gsx$date.$t;
});
// Map json values back to values array
var values = json.feed.entry.map(function(e) {
return e.gsx$followers.$t;
});
for (i = 0; i < values.length; i++) {
if (values[i].charAt(0) == '-') {
values.length = values.length - 1;
labels.length = labels.length - 1;
} else if (values[i].charAt(0) == '+') {
values.length = values.length - 1;
labels.length = labels.length - 1;
}
}
for (i = 0; i < values.length; i++) {
values[i] = values[i].replace(/,/g, '');
}
chart = BuildChart(labels.reverse(), values.reverse(), "Followers"); // 2
}
};
xhttp.open("GET", "https://spreadsheets.google.com/feeds/list/1nLLfOhAD6PGcIPc5mttyBFi1maoveEYpsz4MiU7JNAA/od6/public/full?alt=json", false);
xhttp.send();
</script>
There are few important points from the code above (search for the comment to reference the number). These are:
chart is created so that it holds the chart instance
BuildChart output is saved into chart
A new oninput listener needs to be created to respond to date changes. If you use a <select> you can use the onchange event instead.
Here the calculation is made by substracting the amount of days we want to show.

Related

How to load datapoints from 4 array in CanvasJS to create a chart

I want to use chart canvasjs to display 4 different data.
My data is for the balances of 4 different accounts in the last 10 days and I want the x-axis of the days and the y-axis of the balance amounts.
my code :
const ColorBac = ["rgba(255, 0, 50, 0.2)", "rgba(27, 68, 128, 0.2)", "rgba(246, 162, 30, 0.2)", "rgba(23, 135, 95, 0.2)"];
const Colorborder = ["rgba(255, 0, 50, 0.6)", "rgba(27, 68, 128, 0.6)", "rgba(246, 162, 30, 0.6)", "rgba(23, 135, 95, 0.6)"];
Api = api('Chart');
console.log("load Api Array");
console.log(Api.ExData);
function setColor(chart) {
for (var i = 0; i < chart.options.data.length; i++) {
dataSeries = chart.options.data[i];
for (var j = 0; j < dataSeries.dataPoints.length; j++) {
if (dataSeries.dataPoints[j].y <= 0)
dataSeries.dataPoints[j].color = ColorBac[j];
}
}
}
function ShowChart() {
var dataPoints = [];
//GetData();
$.each(Api.ExData, function(index, Info) {
dataPoints.push({
x: parseInt(Info.fldHesabID),
y: parseInt(Info.fldMojoodi),
label: Info.fldDate,
mouseover: onMouseover,
});
});
console.log('load dataPoints');
console.log(dataPoints);
///////
var chart = new CanvasJS.Chart("chartContainer", {
animationEnabled: true,
theme: "light2", // "light1", "light2", "dark1", "dark2"
axisY: {
//title: "Reserves(MMbbl)"
//labelAngle: 30
},
axisX: {
interval: 1,
//minimum: 0,
// maximum: 20,
labelAngle: 30
},
data: [{
type: "line",
toolTipContent: "{label}: {y} ",
dataPoints: dataPoints,
}]
});
console.log('load Chart');
setColor(chart);
chart.render();
function onMouseover(e) {
createGauge(e.dataPoint.progressVal);
}
}
ShowChart();
console.log('end Chart');
<div id="chartContainer" style="height: 370px; width: 100%;border: 1px solid green;"></div>
<br>
<script type="text/javascript" src="https://canvasjs.com/assets/script/jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
My data output is in the form of a photo.
Please help me to display this chart

how can i change a specific bar color in chart.js color chartjs

i want to change the color of the chosen bar in bar chart I found this code but When i run the code this error shown myChart.getElementsAtEvent is not a function
at HTMLCanvasElement.ChangeColor
here is my code
html:
```
<div class="chartBox">
<canvas id="myChart"></canvas>
<input type="color" id ="colorPicker" hidden/>
</div>
```
Javascript code:
```
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script type="">
var color = '#456212';
var lastIndex = null;
var canvas = document.getElementById("myChart");
document.getElementById("my-select").addEventListener("change", changeChart);
document.getElementById("filter").addEventListener("change", filterChart);
var label = <%- JSON.stringify(x)%>
var data = [<%= y %>]
const originalLabels = label;
const originalData = data ;
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: originalLabels,
datasets: [{
label: '# of Votes',
data: originalData,
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
scales: {
y: {
beginAtZero: true
}
}
}
});
canvas.addEventListener("click", ChangeColor, false);
colorPicker = document.getElementById('colorPicker');
colorPicker.addEventListener("change", getColor, false);
function getColor(e){
//
console.log(this.lastIndex)
myChart.data.datasets[0].backgroundColor[lastIndex] = e.target.value;
console.log(e.target.value);
myChart.update();
}
function ChangeColor(e){
e.preventDefault();
var activePoints = myChart.getElementsAtEvent(e);
lastIndex = activePoints[0]._index;
this.color = myChart.data.datasets[0].backgroundColor[lastIndex];
console.log('Before', this.color);
var colorPicker = document.getElementById('colorPicker').click();
//console.log('After',this.color);
}
</script>
```
how can i change a specific bar color
i want the user click on the bar then chose the color or the opposite
I have prepared a sample. Clicking on the bar element, the color picker is visible and when you choose the color, the chart will be updated with new color.
I think it's better to use onClick option provided by CHART.JS instead of add event listener to the canvas because CHART.JS option is providing the elements affected by the click event.
To simplify the sample, be aware that the backgroundColor must be set as an array with the original colors for each bar (but you can add additional logic to manage it).
let selected = undefined;
const chartData = {
labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
datasets: [{
fill: true,
backgroundColor: ['cyan','cyan','cyan','cyan','cyan','cyan','cyan'],
data: [40, 39, 10, 40, 39, 80, 40],
}]
};
const ctx = document.getElementById('myChart');
const myChart = new Chart(ctx, {
type: 'bar',
data: chartData,
options: {
onClick(evt, elements, chart) {
if (elements.length) {
selected = elements;
const colorPicker = document.getElementById("colorPicker");
colorPicker.click();
}
}
}
});
document.getElementById("colorPicker").addEventListener("change", setColor);
function setColor() {
if (selected && selected.length) {
const colorPicker = document.getElementById("colorPicker");
for (const el of selected) {
const {datasetIndex, index} = el;
const dataset = myChart.data.datasets[datasetIndex];
dataset.backgroundColor.splice(index, 1, colorPicker.value);
}
myChart.update();
}
}
.myChartDiv {
max-width: 600px;
max-height: 400px;
}
<script src="https://cdn.jsdelivr.net/npm/chart.js#3.9.1/dist/chart.min.js"></script>
<html>
<body>
<div class="myChartDiv">
<canvas id="myChart" width="600" height="400"/>
</div>
<input id="colorPicker" type="color" style="visibility: hidden;"/>
</body>
</html>

How can i get 3rd Axis in Chart js?

Trying to put a 3rd axis to the chart...,
the object data is beeing received, but not displayed. What is wrong ?
I checked that the data is pushed , but it is not displayed.
I have no idea , why data is not in the chart,
the spelling should be ok.
If pushing data from IOT,
I always get 3 Objects with data,
as shown in the Picture.
/* eslint-disable max-classes-per-file */
/* eslint-disable no-restricted-globals */
/* eslint-disable no-undef */
$(document).ready(() => {
// if deployed to a site supporting SSL, use wss://
const protocol = document.location.protocol.startsWith('https') ? 'wss://' : 'ws://';
const webSocket = new WebSocket(protocol + location.host);
// A class for holding the last N points of telemetry for a device
class DeviceData {
constructor(deviceId) {
this.deviceId = deviceId;
this.maxLen = 50;
this.timeData = new Array(this.maxLen);
this.temperatureData = new Array(this.maxLen);
this.PrsInData =new Array(this.maxLen);
this.PrsOutData =new Array(this.maxLen);
}
addData(time,Temperature, PrsIn,PrsOut) {
this.timeData.push(time);
this.temperatureData.push(Temperature);
this.PrsInData.push(PrsIn);
this.PrsOutData.push(PrsOut);
if (this.timeData.length > this.maxLen) {
this.timeData.shift();
this.temperatureData.shift();
this.PrsOutData.shift();
this.PrsInData.shift();
}
}
}
// All the devices in the list (those that have been sending telemetry)
class TrackedDevices {
constructor() {
this.devices = [];
}
// Find a device based on its Id
findDevice(deviceId) {
for (let i = 0; i < this.devices.length; ++i) {
if (this.devices[i].deviceId === deviceId) {
return this.devices[i];
}
}
return undefined;
}
getDevicesCount() {
return this.devices.length;
}
}
const trackedDevices = new TrackedDevices();
// Define the chart axes
const chartData = {
datasets: [
{
fill: false,
label: 'Temperature',
yAxisID: 'Temperature',
borderColor: 'rgba(255, 204, 0, 1)',
pointBoarderColor: 'rgba(255, 204, 0, 1)',
backgroundColor: 'rgba(255, 204, 0, 0.4)',
pointHoverBackgroundColor: 'rgba(255, 204, 0, 1)',
pointHoverBorderColor: 'rgba(255, 204, 0, 1)',
spanGaps: true,
},
{
fill: false,
label: 'PrsIn',
yAxisID: 'PrsIn',
borderColor: 'rgba(24, 120, 240, 1)',
pointBoarderColor: 'rgba(24, 120, 240, 1)',
backgroundColor: 'rgba(24, 120, 240, 0.4)',
pointHoverBackgroundColor: 'rgba(24, 120, 240, 1)',
pointHoverBorderColor: 'rgba(24, 120, 240, 1)',
spanGaps: true,
},
{
fill: false,
label: 'PrsOut',
yAxisID: 'PrsOut',
borderColor: 'rgba(24, 24, 240, 1)',
pointBoarderColor: 'rgba(24, 24, 240, 1)',
backgroundColor: 'rgba(24, 24, 240, 0.4)',
pointHoverBackgroundColor: 'rgba(24, 24, 240, 1)',
pointHoverBorderColor: 'rgba(24, 24, 240, 1)',
spanGaps: true,
}
]
};
const chartOptions = {
scales: {
yAxes: [{
id: 'Temperature',
type: 'linear',
scaleLabel: {
labelString: 'Temperature (ºC)',
display: true,
},
position: 'left',
ticks: {
max: 420,
min: 0
}
},
{
id: 'PrsIn',
type: 'linear',
scaleLabel: {
labelString: 'PrsIn',
display: true,
},
position: 'right',
}
,
{
id: 'PrsOut',
type: 'linear',
scaleLabel: {
labelString: 'PrsOut',
display: true,
},
position: 'right',
} ]
}
};
// Get the context of the canvas element we want to select
const ctx = document.getElementById('iotChart').getContext('2d');
const myLineChart = new Chart(
ctx,
{
type: 'line',
data: chartData,
options: chartOptions,
});
// Manage a list of devices in the UI, and update which device data the chart is showing
// based on selection
let needsAutoSelect = true;
const deviceCount = document.getElementById('deviceCount');
const listOfDevices = document.getElementById('listOfDevices');
function OnSelectionChange() {
const device = trackedDevices.findDevice(listOfDevices[listOfDevices.selectedIndex].text);
chartData.labels = device.timeData;
chartData.datasets[0].data = device.Temperature;
chartData.datasets[1].data = device.PrsInData;
chartData.datasets[2].data = device.PrsOutData;
myLineChart.update();
}
listOfDevices.addEventListener('change', OnSelectionChange, false);
// When a web socket message arrives:
// 1. Unpack it
// 2. Validate it has date/time and temperature
// 3. Find or create a cached device to hold the telemetry data
// 4. Append the telemetry data
// 5. Update the chart UI
webSocket.onmessage = function onMessage(message) {
try {
const messageData = JSON.parse(message.data);
console.log(messageData);
// time and either temperature or humidity are required
if (!messageData.MessageDate || (!messageData.IotData.Temperature && !messageData.IotData.PrsIn && !messageData.IotData.PrsOut )) {
return;
}
// find or add device to list of tracked devices
const existingDeviceData = trackedDevices.findDevice(messageData.DeviceId);
if (existingDeviceData) {
existingDeviceData.addData(messageData.MessageDate, messageData.IotData.Temperature, messageData.IotData.PrsIn, messageData.IotData.PrsOut);
} else {
const newDeviceData = new DeviceData(messageData.DeviceId);
trackedDevices.devices.push(newDeviceData);
const numDevices = trackedDevices.getDevicesCount();
deviceCount.innerText = numDevices === 1 ? `${numDevices} device` : `${numDevices} devices`;
newDeviceData.addData(messageData.MessageDate, messageData.IotData.Temperature, messageData.IotData.PrsIn, messageData.IotData.PrsOut);
// add device to the UI list
const node = document.createElement('option');
const nodeText = document.createTextNode(messageData.DeviceId);
node.appendChild(nodeText);
listOfDevices.appendChild(node);
// if this is the first device being discovered, auto-select it
if (needsAutoSelect) {
needsAutoSelect = false;
listOfDevices.selectedIndex = 0;
OnSelectionChange();
}
}
myLineChart.update();
} catch (err) {
console.error(err);
}
};
});
Temperature is missing in the chart

How add the sizes of the slices in the pie chart (at the top) in Chart.js?

I am starting to learn the chart.js library.
I drew a pie chart (like "pie"). When you hover over the slices of the diagram, a number appears in the pop-up window that sets the size of the sector.
new chart(
document.getElementById('diagram_1').getContext('2d'), {
type: 'pie',
data: {
labels: [
'Завершенная задача',
'Новая задача',
'Ошибка выполнения'
],
datasets: [{
label: '# of Votes',
data: [#successful_tasks, #new_tasks, #error_tasks],
backgroundColor: [
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(255, 99, 132, 0.2)'
],
borderColor: [
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(255, 99, 132, 1)'
],
borderWidth: 1
}]
},
options: {
scales: {
y: {
beginAtZero: true
}
},
responsive: false
}
}
)
How can you make this number still displayed at the top, where the sectors are listed (I marked this place with a red circle in the picture)?
I can add the required number to the labels array
...
data: {
labels: [
'Завершенная задача: ' + #successful_tasks,
'Новая задача: ' + #new_tasks,
'Ошибка выполнения: ' + #error_tasks
],
...
But then this number will appear twice in the tooltip
You can use the plugin system for this:
var options = {
type: 'pie',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
backgroundColor: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"]
}]
},
options: {
plugins: {
customNumber: {
textColor: 'red',
xOffset: 10,
yOffset: 0,
font: '24px Comic Sans MS'
}
}
},
plugins: [{
id: 'customNumber',
afterDraw: (chart, args, opts) => {
const hoveredSlice = chart._active[0];
const {
ctx,
chartArea: {
right
}
} = chart;
if (!hoveredSlice) {
return;
}
ctx.font = opts.font || '24px verdana, sans-serif'
ctx.fillStyle = opts.textColor || 'black'
const val = chart.data.datasets[hoveredSlice.datasetIndex].data[hoveredSlice.index];
const meassures = ctx.measureText(val);
const height = ctx.measureText('M').width;
ctx.fillText(val, (right - meassures.width - (opts.xOffset || 0)), height + (opts.yOffset || 0))
}
}]
}
var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.6.0/chart.js"></script>
</body>
I found the answer. My project is written in CoffeeScript, but I think it would be more useful for the StackOverflow community to post the code in JS.
options: {
legend: {
labels: {
generateLabels: function(chart) {
var data = chart.data;
if (data.labels.length && data.datasets.length) {
return data.labels.map(function(label, i) {
var meta = chart.getDatasetMeta(0);
var ds = data.datasets[0];
var arc = meta.data[i];
var custom = arc && arc.custom || {};
var getValueAtIndexOrDefault = Chart.helpers.getValueAtIndexOrDefault;
var arcOpts = chart.options.elements.arc;
var fill = custom.backgroundColor ? custom.backgroundColor : getValueAtIndexOrDefault(ds.backgroundColor, i, arcOpts.backgroundColor);
var stroke = custom.borderColor ? custom.borderColor : getValueAtIndexOrDefault(ds.borderColor, i, arcOpts.borderColor);
var bw = custom.borderWidth ? custom.borderWidth : getValueAtIndexOrDefault(ds.borderWidth, i, arcOpts.borderWidth);
var value = chart.config.data.datasets[arc._datasetIndex].data[arc._index];
return {
text: label + ": " + value,
fillStyle: fill,
strokeStyle: stroke,
lineWidth: bw,
hidden: isNaN(ds.data[i]) || meta.data[i].hidden,
index: i
};
});
} else {
return [];
}
}
}
}
}

All the bar in bar chart stays at left with very little width

I am populating my bar chart with very simple data. But it seems that it stays always left with little width no matter what I do. How can I solve this can you pls tell me?I also tried with bar thickness and bar percentage doesn't seem to change any thing. Is there anything I can do? Thank you.
Js part:
var labels = ["Request for Information", "Product Availability", "Offer Eligibility", "Price Query", "How To Order",
"Delivery Duration", "Offer Duration", "Product Feature Query", "Delivery Charge", "Order Confirmation"]
var barData=[17076, 16313, 11337, 11000, 6116, 5957, 5590, 4815, 3825, 335]
var tempbackgroundColor=['rgba(192, 57, 43, 1)',
'rgba(155, 89, 182, 1)',
'rgba(84, 153, 199, 1)',
'rgba(69, 179, 157, 1)',
'rgba(245, 176, 65 , 1)',
'rgba(236, 240, 241, 1)',
'rgba(127, 140, 141, 1)',
'rgba(44, 62, 80, 1)'
]
var dataSets = [];
for (var i = 0; i < labels.length; i++) {
var tmp = { data: [] };
tmp.label = labels[i];
tmp.borderColor = [tempbackgroundColor[i]];
tmp.backgroundColor = [tempbackgroundColor[i]];
tmp.borderWidth = 1;
tmp.data = [barData[i]];
dataSets.push(tmp);
}
if (data != '') {
$scope.trendChartLoading = '0';
}
showMBSLineChart(this.canvasId, labels, dataSets, "bar", this.area,true,false);
showMBSLineChart function
var showMBSLineChart = function (canvasId, labels, dataSets, chartType = 'line',xlabelstring="",ticksunitdisplay=true,labeldisplayx=false) {
var ctxL = document.getElementById(canvasId).getContext('2d');
var aspratio = 1;
var ticksdisplay = true;
var scalelabeldisplayx = false;
var scalestringx = xlabelstring;
if (chartType == 'line') {
aspratio = 1;
ticksdisplay = ticksunitdisplay;
scalelabeldisplayx = labeldisplayx;
} else if (chartType == 'bar') {
aspratio = 1;
ticksdisplay = ticksunitdisplay;
scalelabeldisplayx = labeldisplayx;
}
var myLineChart = new Chart(ctxL, {
type: chartType,
data: {
labels: labels,
datasets: dataSets
},
options: {
responsive: true,
legend: {
display: true,
labels: {
boxWidth: 8,
fontSize:10
}
},
aspectRatio: aspratio,
scales: {
xAxes: [{
ticks: {
display: ticksdisplay,
fontSize: 10
},
scaleLabel: {
display: scalelabeldisplayx,
labelString: scalestringx
},
}]
}
}
});
}
In time of calling the showMBSLinechart function just call with single array data.Like this
showMBSLineChart(this.canvasId, ["counts"], dataSets, "bar", this.area,false,true);

Categories

Resources