Chart.js - Where to put global chart configuration? - javascript

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)

Related

Chart.js size not adapting to div

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.

Chart.js - get base 64 encoded string as variable

I'm creating a chart using the Chart.js library and it's working well. I'm using the .toBase64Image() function to generate a base 64 encoded string of the chart (png data url).
I can see this when I inspect the chart in my browser developer tools, e.g.:
data:image/png;base64,iVBORw0KGgoAAAA etc
I now need to call a URL to another application that will pass the data url as a parameter - I'm just stuck at how to get the data url as a parameter to pass to my URL that I will then call.
Here's my script as it currently stands:
var radarChartData = {
labels: ["Eating", "Drinking", "Sleeping", "Designing", "Coding", "Cycling", "Running"],
datasets: [{
label: "My First dataset",
fillColor: "rgba(220,220,220,0.2)",
strokeColor: "rgba(220,220,220,1)",
pointColor: "rgba(220,220,220,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(220,220,220,1)",
data: [3, 2, 1, 5, 6, 8, 5]
},
]
};
window.onload = function() {
window.myRadar = new Chart(document.getElementById("canvas").getContext("2d")).Radar(radarChartData, {
responsive: true,
scaleOverride: true,
scaleSteps: 10,
scaleStepWidth: 1,
scaleStartValue: 0,
onAnimationComplete: function() {
document.getElementById("canvas").innerHTML = myRadar.toBase64Image();
theURL = "fmp://$/chartingFile?script=getChartToContainer&param=";
window.location = theURL;
}
});
}
I need to append the "data:image/png;base64,iVBORw0KGgoAAAA" string to the 'theURL' variable but can't figure out how to get this as a string?
Managed to work this out as follows:
onAnimationComplete: function() {
document.getElementById("canvas").innerHTML = myRadar.toBase64Image();
var x = document.getElementById("canvas").innerHTML = myRadar.toBase64Image();
theParam = encodeURIComponent(x);
theURL = "fmp://$/chartingFile?script=getChartToContainer&param=" + theParam;
window.location = theURL;
Not sure if it's optimal etc but it's working well so far.

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;
}

Remove radar chart labels in chart.js

I'm trying to get rid of the label "undefined" from showing at all at the top of my chart, as I only have one dataset and don't need a legend.
Here's my code:
// Radar chart data
var radarData = {
labels : ["Abs","Arms","Back","Butt","Chest","Legs","Shoulders"],
datasets : [
{
lavel: "test",
fillColor: "rgba(102,45,145,.1)",
strokeColor: "rgba(102,45,145,1)",
pointColor : "rgba(220,220,220,1)",
pointStrokeColor : "#fff",
data : [65,59,90,81,56,55,40]
}
]
};
// Create Radar chart
var ctx = document.getElementById("radarChart").getContext("2d");
var myNewChart = new Chart(ctx, {
type: "radar",
data: radarData
});
Adding "options: [scaleShowLabels=false]" doesn't work for some reason.
var myNewChart = new Chart(ctx, {
type: "radar",
data: radarData,
});
myNewChart.options.title.text = "top of chart"; // test, total fail
myNewChart.options.legend.display = false; // This one does it!
So apparently on the radar chart, that top element is called the legend. I was able to place a watch on myNewChart object in Chrome and step thru the code in dev tools.
Keep in mind that in Chart.js version 3, the options now have a plugins inner field, in which such options are to be configured.
So now it is:
options:{
plugins:{
legend:{
display:false
}
}
}
Or programmatically:
myNewChart.options.plugins.legend.display = false;

Chart.js custom tooltipTemplate index

I have this chart made with Chart.js.
var data = {
labels: ["", "", "", "2015-08-28", "2015-08-29", "2015-08-30", "2015-08-31", ],
websites: ["", "", "", "gamesoutletCrawler", "gamesoutletCrawler", "G2PLAY", "instantgaming", ],
datasets: [{
label: "Best price last 7 days",
fillColor: "rgba(220,220,220,0.2)",
strokeColor: "rgba(220,220,220,1)",
pointColor: "rgba(220,220,220,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(220,220,220,1)",
data: [0, 0, 0, 34.5, 36.8, 37.3, 37.99, ]
}]
};
window.onload = function() {
var ctx = document.getElementById("chartkeys").getContext("2d");
window.myLine = new Chart(ctx).Line(data, {
responsive: true,
tooltipTemplate: "<%= data.websites[idx] %>",
scaleLabel: "<%= Number(value).toFixed(2).replace('.', ',') + ' €'%>"
});
}
On my tooltip template, I want to use values from data.websites but I don't know how to pass in the index for my tooltip array. This is not working:
<%= data.websites[idx] %>
idx is wrong, it's not the index the system is using. Any idea what I have to write here to show the index tooltip when you hover on the graph?
If I write <%= data.websites %>, it's showing me all the websites in the array, not the one hovered.
You can use a function instead of a template string
...
tooltipTemplate: function (d) {
return data.websites[data.labels.indexOf(d.label)]
},
...
Note that this requires the labels to be unique, or if there are duplicate labels that it not matter which one is active (for instance, in your data, the first 3 labels are the same but that won't cause any problems because the first 3 entries in the websites array too are the same. If they were different this method will not work)

Categories

Resources