Chart.js size not adapting to div - javascript

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.

Related

Cannot change chart.js color fill or y axes

I am trying to make a real time graph using chart.js, but I cannot seem to change the color fills.
<script type="text/javascript">
var canvas = document.getElementById('updating-chart'),
ctx = canvas.getContext('2d'),
startingData = {
labels: ["A", "B", "C", "D"],
datasets: [
{
label: "Product A",
fillColor: "rgba(206, 70, 90, 1)",
strokeColor: "rgba(220,220,220,0.8)",
pointColor: "rgba(220,220,220,1)",
pointStrokeColor: "#fff",
data: [65, 59, 80, 81],
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true,
min: 0,
max: 10
}
}]
}
}
}
]
};
var myLiveChart = new Chart(ctx,{
type: 'bar',
data: startingData,
responsive: true,
maintainAspectRatio: true
});
setInterval(function(){
// Get a random index point
var indexToUpdate = Math.round(Math.random() * startingData.labels.length);
// Update one of the points in the second dataset
myLiveChart.data.datasets[0].data[indexToUpdate] = Math.random() * 100;
myLiveChart.update();
}, 500);
</script>
I've clearly changed the axes and set the y to a maximum, but it still overflows and keeps dynamically changing the axes length. How do I fix this?
Also the color still seems to be grey for the first bar, even though I changed the rgba values. Help?
refer the below link for changing the colors.try background-color.If you share the fiddle it will help.
http://www.chartjs.org/docs/#chart-configuration-colors
Add below code in your datasets array. Color will change.
backgroundColor:"rgba(206, 70, 90, 1)"
https://jsfiddle.net/Smita31Jain/4zpuxvke/
For overflow and dynamically changing axes length issue, take out options property object code from startingData object's dataset array and add it to myLiveChart chart instance. Refer below jsfiddle
https://jsfiddle.net/Smita31Jain/zzpkxg3k/
Hope this is what you are looking for.

Use data from database in Chart.js/Rails

I want to show a line chart on my "Weights" index page with Chart.js in my Rails app (a weight loss app). I have a table that holds a user's weight (as "kilograms") for each day (as "day"). I am able to show a line chart, however, but only with static data - not with the data from my Weights table.
What I want to do now is to have "day" on the x-axis and "kilograms" on the y-axis.
How can I achieve this? And as I just started coding few months ago: how should the code look like?
Thx a lot.
This is the code from my weights index.html.erb:
<canvas id="myChart" width="400" height="200"></canvas>
<script>
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: ["day 1", "day 2", "day 3", "day 4", "day 5", "day 6"],
datasets: [{
label: 'My Weight',
data: [82.4, 79.6, 79.3, 78.4, 77.5, 75.1],
backgroundColor: [
'rgba(0, 0, 0, 0.1)',
],
borderColor: [
'rgba(0,0,0,0.9)',
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:false
}
}]
}
}
});
</script>
The main thing that had me stuck forever was that Chart.js relies on calling its tooltiptemplate with <% however this would then be interpreted by ERB and cause a problem. The workaround is adding another % which tells erb not to interpret the tags it otherwise would have. That's not very well documented but what are you going to do. As for the rest, in your view-page.html.erb file you want to add the chart scripts at the bottom:
Set your timeline X-Axis (I'll show you how to load it dynamically but this could be static if you want in which case just enter them directly into the timeline array):
<script type="text/javascript">
$(function() {
var lineData = {
<% timeline = []
datapoints = []
#workout.each do |workout|
timeline << workout.day
datapoints << workout.weight
end
%>
//The "raw" method is needed to stop the auto escaping of the output. Test this out in your console and you will notice the output is formatted like "[\"January\", \"February\", \"March\", \"April\", \"May\", \"June\", \"July\"]" This escaping of quotes causes errors in js...
labels: <%= raw timeline.to_json %>,
datasets: [{
label: "Weight Gain/Loss",
fillColor: "rgba(26,179,148,0.5)",
strokeColor: "rgba(220,220,220,1)",
pointColor: "rgba(220,220,220,1)",
pointStrokeColor: "#127A65",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(220,220,220,1)",
data: <%= raw datapoints.to_json %>,
}]
};
If you want to set some options remember to use the <%% tag for tooltips!
var lineOptions = {
scaleOverride : true,
tooltipTemplate: "<%%if (label){%>(<%%=label%>) <%%}%><%%= value %> pounds",
};
//NOTE THE ABOVE TOOLTIP REQUIRES A SECOND % SIGN ON OPENING TAGS SO THAT IS IS TAKEN LITERALLY AND NOT INTERPRETED BY RAILS ERB!!!!!!!!
var ctx = document.getElementById("myChart").getContext("2d");
var myNewChart = new Chart(ctx).Line(lineData, lineOptions);
});
</script>
I, too, was struggling with getting this to work on Rails, but I discovered that I did not have to use the Rails template escape characters that chart.js says that you do. In my case (needing to show a zero in the label when the value is set to 0.1), this is what I did:
tooltipTemplate: function(context){
var labelVal = (context.value == '0.1')? '0' : context.value;
var newLabel = context.label + ': ' + labelVal;
return newLabel;
}

Control which lines have points?

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.

Bar graph from json response using Jquery

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.

Chart.js - Where to put global chart configuration?

I am trying to set up a Chart.js line graph with the following code. Where in this do I place the Chart.defaults.global = {} or Chart.defaults.global.responsive = true; code?
Chart.js docs can be found here: http://www.chartjs.org/docs/
<!-- Chart.js -->
<script src="http://cdnjs.cloudflare.com/ajax/libs/Chart.js/0.2.0/Chart.min.js"></script>
<script>
var ctx = document.getElementById("myChart").getContext("2d");
var data = {
labels: ["Week 1", "Week 2", "Week 3", "Week 4", "Week 5", "Week 6", "Week 7"],
datasets: [
{
label: "My Second dataset",
fillColor: "rgba(151,187,205,0.2)",
strokeColor: "rgba(151,187,205,1)",
pointColor: "rgba(151,187,205,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(151,187,205,1)",
data: [86, 74, 68, 49, 42]
}
]
};
var options = {
...
};
var myLineChart = new Chart(ctx).Line(data, options);
</script>
There are two ways to accomplish what you're looking for. This way
var myLineChart = new Chart(ctx).Line(data, options);
var options = Chart.defaults.global = {
responsive: true,
maintainAspectRatio: true
};
or, this way
var myLineChart = new Chart(ctx).Line(data, {
responsive: true,
maintainAspectRatio: true
});
However, to make it responsive you'll have to add some extra CSS
canvas{
width: 100% !important;
height: auto !important;
}
so there's no need for inline CSS
Working demo
In accordance with the comment of #JustinXL below and the latest version of Chart.js there's no need for extra CSS, so check out the updated version.
Updated demo
You could set the options of your chart, but you can also set the global (as you asked) to avoid setting this specific property for each chart you want to instantiate.
You just have to set
Chart.defaults.global.elements.responsive = true;
before instantiating the chart, in your case, before
var myLineChart = new Chart(ctx).Line(data, options);
(P.S.: Chartjs V2)

Categories

Resources