Rendering Rails json data in chartjs - javascript

I have my canvas tag in my portfolio#show page:
<%= content_tag :canvas, "", id: "positions_chart", width: "300", height: "300", data: {positions: #positions } %>
In my portfolio.js file I have created a chartInstance object:
$(document).ready(function () {
var context = document.getElementById('positions_chart');
var ctx = context.getContext("2d");
var pieData = {
labels: $("#positions_chart").data(positions['name']),
datasets: [
{
backgroundColor: "rgba(220,220,220,1)",
borderColor: "rgba(220,220,220,1)",
data: $("#positions_chart").data(positions['quantity'])
}
]
}
var chartInstance = new Chart(ctx, {
type: 'pie',
data: pieData,
options: {
responsive: true
}
});
console.log(chartInstance);
});
I'm loading the data I want in the DOM -- a collection of position data.
<canvas id="positions_chart" width="600" height="600"
data-positions="[{"id":1,"ticker":"AAPL","name":"Apple Inc.",
"quantity":20,"portfolio_id":1,"created_at":"2016-10-22T18:19:36.255Z",
"updated_at":"2016-10-23T01:21:38.731Z","price":"116.6"},...
style="width: 300px; height: 300px;"></canvas>
The examples I've seen online are how to handle preloaded data within the data and dataset attributes in the js file. I want to have a pie chart with labels corresponding to the ticker names and using data from my rails database. I grab the data in the canvas tag and have access to it in my js file.
From what I understand, I'm passing the pieData object to the ctx object and whichever graph I chose (in this case pie) it should render the label and dataset to a graph. I'm not sure why the pie chart isn't showing up.

Is this what you want?
You can pass data you get from rails database and insert it into your js code immediately (no need to put it to data attribute in canvas tag).
I see you are using chart js v2 so no need to get context I think.
Also I fixed your code a little bit.
in your js code
$(document).ready(function() {
var positionsQuantity = <%= raw(#positions.map(&:quantity)) %>;
var positionName = <%= raw(#positions.map(&:name)) %>;
var ctx = $('#positions_chart');
var pieData = {
labels: positionName,
datasets: [
{
label: "pie labels",
data: positionsQuantity,
backgroundColor: "rgba(220,220,220,1)",
borderColor: "rgba(220,220,220,1)"
}]
}
var chartInstance = new Chart(ctx, {
type: 'pie',
data: pieData,
options: {
responsive: true
}
});
});
Hope it works!

Related

Hiding labels on y axis in Chart.js 3.5.0 not working properly

This driving me nuts. I tried all of the stuff here and looked to documentation https://www.chartjs.org/docs/latest/getting-started/v3-migration.html
but still not able to remove y-axis labels from bar charts.
Which part I could be missing ?
Here is the part of the code that defines
y axis stuff
<script>
var ctx = document.getElementById('myChart').getContext('2d');
var chartOptions = {
scales: {
y: {
display: true
}
}
};
var chart = new Chart(ctx, {
// The type of chart we want to create
type: 'bar',
// The data for our dataset
data: {
labels: {{ countrynames|safe }},
datasets: [{
label: 'Infected Counts',
barThickness:'flex',
backgroundColor:'#03a9fc',
backgroundColor : 'rgb(255,99,132)' ,
borderColor : 'rgb(255,99,132)' ,
data: {{ barPlotVals|safe }}
}]
},
// Configuration options go here
options: { indexAxis: 'y', chartOptions}
});
</script>

chart.js - how to draw and manage line when only one label present in chart js Linechart

I'm using Chart.JS v 2.9.3 to create a line chart
line-chart diagram to show the month-wise total of expenses of selected product
For example, if the user select XYZ product then this charts would show the monthly expenses [Jan-2021-Dec-2021]
and if that respective product expense only present Jan-2021 then it displays month on y-Axes at staring
here is jsfiddle example
Adding offset trick I had already tried xAxes : [{ offset:true }],
var config = {
type: 'line',
data: {
labels: ["jan-2021"],
datasets: [{
label: "month-year",
data: [65],
backgroundColor: "rgb(118, 101, 228)",
}],
},
scales : {
xAxes : [{
offset:true
}],
},
};
var ctx = document.getElementById("myChart").getContext("2d");
new Chart(ctx, config);
<div class="myChart">
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.js"></script>
<canvas id="myChart"></canvas>
</div>
please refer to the above image for getting an idea of what I'm trying to archive, I'm not concern about dot that on the chart
As you can see, the points are stick to the y-axis. Is there a possibility to center the line chart when only one data is present in the diagram?
Chart.js does not support this kind of use case since it gives a distorted image of your chart since point and label don't align anymore. If you really want this you can check beforehand in your code if there is only 1 data point there. If this is the case add an empty string in your labels array in the front and back and add zero at the front of back of your data array (or a slightly lower value as your single datapoint so that the scales don't get big steps) like so:
var config = {
type: 'line',
data: {
labels: ["", "January-2021", ""],
datasets: [{
label: "month-year",
data: [0, 134335066, 0],
backgroundColor: "rgb(118, 101, 228)",
}],
},
scales: {},
};
var ctx = document.getElementById("myChart").getContext("2d");
new Chart(ctx, config);
<div class="myChart">
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.bundle.js"></script>
<canvas id="myChart"></canvas>
</div>
You can use align option:
var mybarChart = new Chart(ctx, {
type: 'bar',
responsive: true,
data: data,
options: {
legend: {
display: false,
position: 'bottom',
align: 'center'
},
var config = {
type: 'line',
data: {
labels: ["", "January-2021", ""],
datasets: [{
label: "month-year",
data: [0, 134335066, 0],
backgroundColor: "rgb(118, 101, 228)",
}],
options: {
legend: {
display: false,
position: 'bottom',
align: 'center'
},
},
scales: {},
};
refer to this

How can I plot data from an external JSON file to a chart.js graph?

I would like to chart data from an external JSON file using chart.js. As an example, the json file here lists movies ("title") and ratings ("rt_score"). I'd like to be able to show each movie and its rating without including the static JSON in the .js file, but rather using the $.ajax call method to refer to the /films endpoint.
I'd like to have:
labels: labelsVariable
data: dataVariable
Here is a fiddle with the setup so far with static data.
Here's my HTML:
<body>
<canvas id="myChart" width="400" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.js">
</script>
</body>
Here's the js that successfully generates a bar chart like I want, but with static data in "labels" and "data" instead of referencing the JSON file.
var ctx = document.getElementById('myChart');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['Castle in the Sky', 'Grave of the Fireflies'],
datasets: [{
label: 'rating',
data: [95, 97],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
Instead of using the static data and labels, how can I reference the external JSON file using the $.ajax call method?
Based on what I've read, I may have to use "map" to break down the objects into arrays that contain labels and data?
Thank you in advance.
I think you are looking for Ajax request to fill your chart.
function getRandomIntInclusive(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
var ctx_live = document.getElementById("mycanvas");
var myChart = new Chart(ctx_live, {
type: 'bar',
data: {
labels: [],
datasets: [{
data: [],
borderWidth: 1,
borderColor:'#00c0ef',
label: 'liveCount',
}]
},
options: {
responsive: true,
title: {
display: true,
text: "Chart.js - Dynamically Update Chart Via Ajax Requests",
},
legend: {
display: false
},
scales: {
yAxes: [{
ticks: {
beginAtZero: true,
}
}]
}
}
});
var postId = 1;
var getData = function() {
$.ajax({
url: 'https://jsonplaceholder.typicode.com/posts/' + postId + '/comments',
success: function(data) {
myChart.data.labels.push("Post " + postId++);
myChart.data.datasets[0].data.push(getRandomIntInclusive(1, 25));
// re-render the chart
myChart.update();
}
});
};
setInterval(getData, 3000);
see live example here.
Load the json chart data dynamically and set it when you are creating the graph. There are many ways you can load the chart json data. However, I believe the JQuery getJSON function is more relevant to you.
$.getJSON( "chartdata/test.json", function( data ) {
var myChart = new Chart(ctx, {
type: 'bar',
data: data,
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
}
I figured it out. Here's what worked. I had to use .map to set up the data properly inside variables and then use those variables as data and labels.
function renderChart(data, labels) {
var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: labels,
datasets: [{
label: 'This week',
data: data,
}]
},
});
}
function getChartData() {
$("#loadingMessage").html('<img src="./giphy.gif" alt="" srcset="">');
$.ajax({
url: "https://ghibliapi.herokuapp.com/films",
success: function (result) {
var data = result.map(x=>x.rt_score);
var labels = result.map(x=>x.title);
renderChart(data, labels);
console.log(data);
},
});
$("#renderBtn").click(
function () {
getChartData();
});

Auto Generating Pie Chart Legend

I am trying to create a pie chart in JavaScript. I would like this chart to display in the legend only the labels that are non zero.
Does anyone have any ideas how this can be done?
Here is the code I have so far. Currently the legend of the pie chart shows all possible 12 Labels, even though 8 of these have zero value. "Data" will eventually be filled from a database and therefore it is important that this is an automated process.
var ctx = document.getElementById("myPieChart");
var myPieChart = new Chart(ctx, {
type: 'pie',
data: {
labels: ["Astronomica", "Deuteronic", "Floral", "Galactic","Celestrial","Heliosphere","Jupiter","Interstella","Koronis","Eclipse,"Borealis","Lunatic"],
datasets: [{
data: [12.21, 15.58, 11.25, 8.32],
backgroundColor: ['#007bff', '#dc3545', '#ffc107', '#28a745'],
}],
},
});
You can manage data before use they.
var ctx = document.getElementById("myPieChart");
var input_lables = ["Astronomica" , "Deuteronic", "Floral", "Galactic", "Celestrial", "Heliosphere", "Jupiter", "Interstella","Koronis", "Eclipse", "Borealis", "Lunatic"];
var input_values = [12.21, 15.58, 11.25, 8.32];
var output_lables = [];
var output_values = [];
for(var i=0;i<input_lables.length;i++){
if(!values[i]){
output_lables.push(input_lables[i]);
output_values.push(input_values[i]);
}
}
var myPieChart = new Chart(ctx, {
type: 'pie',
data: {
labels: output_lables,
datasets: [{
data: output_values,
backgroundColor: ['#007bff', '#dc3545', '#ffc107', '#28a745'],
}],
},
});
if you went to automatic it just enough make a function like this code.
According with the documentation you can use the filter parameter in the label
http://www.chartjs.org/docs/latest/configuration/legend.html
and you can make a validation to validate the data and if it is 0 you can return false
Filter a legend Item with Chartjs.org V2.7

Pie chart isn't loading, but the labels are

I'm using Chart.js in Laravel to display data.
I'm following this tutorial, which worked for the bar chart. But now I'm trying a pie chart.
This is my controller which gets the data.
public function chart()
{
$result = \DB::table('users')
->where('userType','=','Landlord')
->orderBy('created_at', 'ASC')
->get();
return response()->json($result);
}
The view is this
<script>
var url = "{{url('/users')}}";
var Name = new Array();
var Email = new Array();
$(document).ready(function(){
$.get(url, function(response){
response.forEach(function(data){
Name.push(data.name);
Email.push(data.email);
});
var ctx = document.getElementById("canvas").getContext('2d');
var myPieChart = new Chart(ctx,{
type: 'pie',
data : {
datasets: [{
data: [Name,Email]
}],
// These labels appear in the legend and in the tooltips when hovering different arcs
labels: [Name, Email]
}
});
});
});
</script>
This is the output
According to the ChartJS documenation, the expected data passed for a pie chart is numbers only. Here's an example of a dataset that should work:
data = {
datasets: [{
data: [10, 20, 30]
}],
// These labels appear in the legend and in the tooltips when hovering different arcs
labels: [
'Red',
'Yellow',
'Blue'
]
};
Currently, your Ajax request is getting the name and email from the /users route; you will need to update the request to get some sort of number value from /users and add that to the dataset.

Categories

Resources