I have an AJAX call which on success gets a JSON response in the below format. Where the number of JSON array columns does not change but the number of entries can increase. Need help in plotting this as a bar chart using jQuery.
[
{
"amount": XX,
"instanceId": "XXX",
"timeStamp": XXX
},
{
"amount": XX,
"instanceId": "XX",
"timeStamp": XX
}
]
You should show code of what you have tried so far and ask a specific question about an issue you are having. Without this information it's hard to provide a suitable answer. That being said, I will provide one way of creating a dynamic bar chart with JavaScript.
This approach uses Chart.js which is a responsive HTML5 charting library that uses the <canvas> element. They provide a bar chart implementation and you can find the documentation for it here.. The first thing to do is include the library into your HTML file (download it and put it in a directory on your server first):
<script src="Chart.js"></script>
Then, in your HTML add a canvas element where the chart will be displayed:
<canvas id="myChart" width="400" height="400"></canvas>
Now, in your JavaScript file, create the chart object using the canvas context:
var ctx = document.getElementById("myChart").getContext("2d");
var chartObject = new Chart(ctx);
Then, using the chart object we created, we can call the Bar(data, options) factory method on it to create the bar chart. The Bar() method takes two arguments: a data object and a options object. The options object allows you to alter certain default functionality. The data object is where you will add your values retrieved from your AJAX call.
The data object contains two direct properties: labels and datasets; each of which are arrays. The labels will be what displays on the bottom of the graph going horizontally, such as dates. Each object in the datasets array will contain a data property which will be the y-value of that particular bar graph corresponding to the label at the same index. They may sound confusing but it's really not once you have a look:
var data = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [
{
label: "My First dataset",
fillColor: "rgba(220,220,220,0.5)",
strokeColor: "rgba(220,220,220,0.8)",
highlightFill: "rgba(220,220,220,0.75)",
highlightStroke: "rgba(220,220,220,1)",
data: [65, 59, 80, 81, 56, 55, 40]
},
{
label: "My Second dataset",
fillColor: "rgba(151,187,205,0.5)",
strokeColor: "rgba(151,187,205,0.8)",
highlightFill: "rgba(151,187,205,0.75)",
highlightStroke: "rgba(151,187,205,1)",
data: [28, 48, 40, 19, 86, 27, 90]
}
]
};
Where the first index of both objects data arrays will correspond to the first index in the label array: bar one was at 65 in January and bar two was at 28 in January.
Since now we have our data object, we can now create the bar graph:
var barChart = chartObject.Bar(data);
Now, whenever you get more data you can add it with the following method:
// The values array passed into addData should be one for each dataset in the chart
barChart.addData([40, 60], "August");
// The new data will now animate at the end of the chart.
And you can even add more datasets:
barChart.datasets.push("data to push");
That should give you enough of a start. You just need to provide some alterations to fit your scenario.
Related
I have been working on a chart using charts.js that show workouts duration each day. The y-axis should have dates and the x-axis should have the duration of the Series,
Here is my dataset:
public lineChartData: ChartDataSets[] = [
{ data: [65, 19, 40, 81, 56, 5, 40], label: 'Series A' },
{ data: [95, 69, 40, 81, 56, 96, 40], label: 'Series B' },
{ data: [65, 74, 40, 41, 54, 55, 40], label: 'Series C' }
];
public lineChartLabels: Label[] = ['2020/05/20', '2020/05/21', '2020/05/22', '2020/05/23', '2020/05/24', '2020/05/25'];
So far I am unable to find any implementation-related it, it would be very helpful if anyone can help me out on this.
I have tried the stackblitz with horizontal with a bar chart, we need to same like in LINE CHART
Here is stackblitz link
You need to use a scatter chart and define the option showLine: true on each dataset. Further you have to define the y-axis as a time cartesian axis as follows.
yAxes: [
{
type: "time",
time: {
parser: "YYYY/MM/DD",
unit: "day",
displayFormats: {
day: "YYYY/MM/DD"
}
},
ticks: {
reverse: true
}
}
]
Since the scatter chart expects the data in point format, you have to generate appropriate data structure in the ngOnInit method as follows:
ngOnInit() {
this.lineChartData.forEach(ds => {
ds.data = ds.data.map((v, i) => ({ x: v, y: this.lineChartLabels[i] }));
});
}
Also remove [labels]="lineChartLabels" from the canvas, this is not needed when defining the data in point format.
Unfortunately however ng2-charts can't cope with this configuration and displays wrong colors for the data points and the legend labels. Therefore I also had to remove [colors]="lineChartColors" from the canvas and define the colors on the datasets.
You'll probably have to get rid of this wrapper library and use Chart.js directly in order to obtain the expected result.
Please take a look at your amended code in this StackBlitz.
I'm trying to use chart.js to draw a chart. My use case is very simple, I'm getting data from my database that needs to be plotted on a line chart. I'm able to get the chart to work when using hardcoded data (i.e)
data: {
labels: ["January", "February", "March"],
datasets: [{
label: "Occupancy",
backgroundColor: 'rgb(255, 99, 132)',
borderColor: 'rgb(255, 99, 132)',
data: [1,2,3],
}]
},
When trying to replace data: [1,2,3] with a variable array, I get an error in the console:
var occ_labels = $('.chart_data_class')[0].dataset['occLbl'];
//var occ_labels =["1","2","3"];
console.log(occ_labels);
var occ_twentyfive = $('.chart_data_class')[0].dataset['occ-25'];
var ctx_occ = document.getElementById('occ-chart').getContext('2d');
console.log(ctx_occ);
var chart = new Chart(ctx_occ, {
// The type of chart we want to create
type: 'line',
// The data for our dataset
data: {
labels: ["January", "February", "March"],
datasets: [{
label: "Occupancy",
backgroundColor: 'rgb(255, 99, 132)',
borderColor: 'rgb(255, 99, 132)',
data: occ_twentyfive,
}]
},
// Configuration options go here
options: {
legend: false,
}
});
var ctx_adr = document.getElementById('adr-chart').getContext('2d');
Then the following error occurs:
jquery3.self-5af507e253c37e9c9dcf65064fc3f93795e6e28012780579975a4d709f4074ad.js?body=1:3828 Uncaught TypeError: Object.defineProperty called on non-object
at Function.defineProperty (<anonymous>)
at e (Chart.min.js:12)
at a.buildOrUpdateElements (Chart.min.js:12)
at t.Controller.<anonymous> (Chart.min.js:11)
at Object.o.each (Chart.min.js:12)
at t.Controller.update (Chart.min.js:11)
at t.Controller.initialize (Chart.min.js:11)
at new t.Controller (Chart.min.js:11)
at new t (Chart.min.js:12)
at HTMLDocument.<anonymous> (interest.self-8876b9dfa2300b4adb2cc9db31f03dcc885a83d23bfc2247d8c08fa65a545fe9.js?body=1:16)
Nothing else changed besides that variable. The variable is valid and has been printed in the console. I have also tried setting the variable as follows:
var occ_twentyfive = [1,2,3];
and that doesn't work either. Thoughts? I've spent the last few hours trying to figure out what's the issue and I can't figure out what the problem is.
Surprisingly enough, I just went back to the page and it seems to be working now even though I had started and restarted the server multiple times before. Perhaps something was caching somewhere and waiting a few days to retry fixed it somehow. not sure what happened...
I have tried so many things (modify css, add inline css to canvas, add inline css to a wrapper div of canvas) but I still can't make the chart fit in the panel properly.
Here is the HTML
<section class="panel">
<header class="panel-heading">
Temp
</header>
<canvas id="tempChart"></canvas>
</section>
Here is the js code
<script>
var data = {
labels: ["January", "Aary", "March", "April", "May", "June"],
datasets: [{
label: "My First dataset",
fillColor: 'rgba(220,220,220,0)',
strokeColor: "rgba(220,220,220,1)",
pointColor: 'red',
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(220,220,220,1)",
data: [65, 59, 80, 81, 56, 55, 40]
} ]
};
var option = {
responsive: true,
};
var ctx = $("#tempChart").get(0).getContext("2d");
var myLineChart = new Chart(ctx).Line(data, option);
The class panel in CSS contains only graphic things such as border background color and so on.
By the way I am using Bootstrap grid.
Thanks for your help.
have you tried to set all your charts responsive with default value : Chart.defaults.global.responsive = true;
Your global synthax seems correct has you setted up
var options = { responsive:true }
However; it's a tiny detail but you added a coma after that true.
I suggest to remove it.
as #brian suggested; please; inform us the version of the lib.
Add a jsfindle is even better
Thanks for all the replies. The problem was the version of lib I was using. Updating that solved the problem.
With Chart.js, you can set in the options of the graph to show points or not:
pointDot: true,
I have a graph with three static lines and one line that shows some fluctuations. I'd like the straight lines not to have points but the fluctuation line show the points. Is there a setting somewhere on the line that I can set the point size to nothing?
** Edit **
Each line is its own set of data configured like this:
datasets: [
{
label: "Cycle Time Per Last Piece",
strokeColor: "red",
fillColor: "red",
pointHighlightFill: "red",
data: [#foreach (var item in Model.DataPoints) {
#(Model.ExpectedCycleTimePerPart * 1.20M)#:,
}]
},
{
label: "Expected Cycle Time Per Part",
strokeColor: "black",
pointHighlightFill: "black",
data: [#foreach (var item in Model.DataPoints) {
#Model.ExpectedCycleTimePerPart#:,
}]
}
The pointDot option drives the display property, so you can do something like
myChart.datasets[0].points[2].display = false;
where myChart is your chart object.
I have a chart where based on date, data changes. Problem current date is default and sometimes there is no data to show. is it possible with chart.js to check for if there is data in current chart and keep previous if there is none. Subing it with DIV placeholder ect. Same data is also in DataTable. Not really good at writing conditions yet.
Things I tried so far:
if (sampleTable != null && sampleTable.rows.count > 0) {
$("#labelDiv").hide();
}
if (parsedData.Item2 = null)
{
$("#labelDiv").hide();
}
if (buyerData == null) {
$("#labelDiv").hide();
}
chart
var buyerData = {
labels: parsedData.Item2,
datasets: [
{
label: "Lazi Chart",
fillColor: "rgba(10,190,10,0.6)",
strokeColor: "rgba(151,187,205,0.8)",
highlightFill: "rgba(151,187,205,0.75)",
highlightStroke: "rgba(151,187,205,1)",
data: parsedData.Item3,
}
]
}
barChartOptions.datasetFill = false;
barChart.Bar(barChartData, barChartOptions);
I figured it out. I check if object is empty and then if it is place a div saying experimental data and fake chart. Tnx for Any Help.
if (parsedData.Item1 != "") {
$("#labelDiv").hide();
$("#buyers").show();
}
else {
$("#labelDiv").show();
$("#FakeData").show();
$("#buyers").hide();
var barData = {
labels: ['SaaS', 'Virtual Machines', 'Networking', 'Storage', 'Data Managment'],
datasets: [
{
label: '2010 customers #',
fillColor: '#382765',
data: [2500, 1902, 1041, 610, 1245]
},
{
label: '2014 customers #',
fillColor: '#7BC225',
data: [3104, 1689, 1318, 589, 1199]
}
]
};
var context = document.getElementById('FakeData').getContext('2d');
var clientsChart = new Chart(context).Bar(barData);
I don't know chart.js, but by it's name I'll assume it's a plugin to draw graphs.
Probably, it'll require that you feed them with data, or at least, with an endpoint where read the data, so it can draw a graph that represent these data.
Now... if you have a data collection, or an endpoint where check for data, won't be easy to check these data and redirect your code execution than try to do that from within a plugin?
If the collection of data is empty or you don't get data from the endpoint just end the execution or return it to the last call (which you could have stored previously if necessary)