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)
Related
I've got a little problem with html5 canvas. I've got a couple of line charts made but they have a problem with maximum grid values (sort of field limits inside the canvas itself). The chart is building from a dataset coming from the database and only through these values.
The example: sample chart
As you can see here, the above limit is 5.55, and the question is how to change that to a bigger value (for example, using a percentage of such maximum value or something so that other charts' offsets would match as well)?
The code:
$('#graf_' + i + '').html('<canvas id="lineChart' + i + '" width="' + $(".graf").width() + '" height="200"></canvas>');
var lineData = {
labels: data["headers"],
datasets: [{
label: data["rates"][i]["VltName"],
fillColor: "transparent",
strokeColor: data["rates"][i]["VltColor"],
pointColor: data["rates"][i]["VltColor"],
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(220,220,220,1)",
data: getRatesArr
}]
};
var lineOptions = {
scaleShowGridLines: true,
scaleGridLineColor: "rgba(0,0,0,.05)",
scaleGridLineWidth: 1,
bezierCurve: false,
pointDot: true,
pointDotRadius: 4,
pointDotStrokeWidth: 1,
pointHitDetectionRadius: 20,
datasetStroke: true,
datasetStrokeWidth: 2,
datasetFill: true
};
var ctx = document.getElementById("lineChart" + i).getContext("2d");
var myNewChart = new Chart(ctx).Line(lineData, lineOptions);
Hope my explanation is not too vague. Thanks in advance!
If you update to the latest Chart.js version (currently v2.6.0), you can use the max tick configuration option to set the max number to display on the axis:
options: {
scales: {
yAxes: [{
ticks: {
max: yourMaxNum
}
}]
}
}
If you want to set yourMaxNum to the largest number in all your dataset arrays, simply use the JavaScript Math.max() method to determine this number, and set the above chart config option to this number when you create all your line charts.
The Chart.js documentation lists additional tick configuration options that you might also find useful.
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¶m=";
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¶m=" + theParam;
window.location = theURL;
Not sure if it's optimal etc but it's working well so far.
Anyone know how looping json data INSIDE varibale?? Example
var data = {
$.each(data, function(i, item) {
console.log(data[i].PageName);
});
labels: [dateLoop],
datasets: [{
}]
};
Well that code is didnt work for me. I want looping inside that varibale. Anyway this coding for Chart.js
Why i need looping?? cuase i have filter buyer and date range, if i choose 3 buyer, and date range from january 2016 to May 2016. On data will show data buyer, each data buyer will have value from date range. Exmaple data json
data [Buyer 1] : ["167404", "129770", "113598", "127301", "156868", "634789", "242188", "166312", "169418"];
data [Buyer 2] : ["9580", "22250", "3500", "5558", "254556", "268500", "77750", "69850", "55"];
So what i need how too looping inside variable?? Sorry my bad languange.
Edit probbaly someone dont know what i mean,
example i have pick 2 buyer, Buyer A (Json["data"][0]) and Buyer B (Json["data"][1]) and each that buyer have value (wich this value order by month if i pick January and May, it will show "222","555")
and the code i mean like this :
var data = {
labels: [dateLoop], #ignore this
datasets: [{ label : (Json["data"][0])
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: [(value orderby month in Json["data"][0]]
},
{ label : (Json["data"][1])
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: [(value orderby month in Json["data"][1]]
}
]
};
That i want it. But i sue each make error. :/
try this, you need 2 loop first loop is for keys and second is for the values inside array
var data = {
'Buyer 1': ["167404", "129770", "113598", "127301", "156868", "634789", "242188", "166312", "169418"],
'Buyer 2': ["9580", "22250", "3500", "5558", "254556", "268500", "77750", "69850", "55"]
}
for(var key in data) {
for (var x in data[key]) {
console.log(data[key][x]);
}
}
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;
}
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)