I've got an issue with ChartJS. I've wanting to add charts to different areas of my site, and I've been able to get it to work with one chart but now I'm trying to add a separate chart (that isn't even on the same page as the first) and it won't load at all. It's the oddest thing.
Here's my script for the charts:
var wins = $("#wins").text();
var losses = $("#losses").text();
var draws = $("#draws").text();
var winsstrike = $("#wins-strike").text();
var winsgrapple = $("#wins-grapple").text();
var winssubmit = $("#wins-submit").text();
var winsother = $("#wins-other").text();
var recorddata = [{
value: 1*wins,
color: "#eb3f3d",
label: "Wins"
}, {
value: 1*losses,
color: "#ec582a",
label: "Losses"
}, {
value: 1*draws,
color: "#f8a430",
label: "Draws"
}
]
var recordoptions = {
animation: true,
segmentShowStroke : true,
segmentStrokeColor : "#191919",
percentageInnerCutout : 70
};
var winsdata = [{
value: 1*winsstrike,
color: "#eb3f3d",
label: "Strike"
}, {
value: 1*winsgrapple,
color: "#E82521",
label: "Grappling"
}, {
value: 1*winssubmit,
color: "#CB1815",
label: "Submission"
}, {
value: 1*winsother,
color: "#A61411",
label: "Other"
}
]
var winsoptions = {
animation: true,
segmentShowStroke : true,
segmentStrokeColor : "#191919",
percentageInnerCutout : 90
};
var c = $('#recordChart');
var ct = c.get(0).getContext('2d');
var ctx = document.getElementById("recordChart").getContext("2d");
myNewChart = new Chart(ct).Doughnut(recorddata, recordoptions);
var c1 = $('#winsbyChart');
var ct1 = c1.get(0).getContext('2d');
var ctx1 = document.getElementById("winsbyChart").getContext("2d");
myNewChart1 = new Chart(ct1).Doughnut(winsdata, winsoptions);
I have no clue why they won't work; the first chart, posting the #recordChart works flawlessly, but the second doesn't. I know the code is fine because I built a fiddle for it. I just can't figure out why the hell it won't work on the second chart (#winsbyChart).
Is there a conflict between the charts I'm not seeing? This is just so frustrating.
UPDATE:
I've deleted the first chart call (not the options or data), and the second appears. They seem to be conflicting with one another somehow. I'm also calling an external JS file; the script isn't embedded in my code. Below is the ENTIRE JS script - which is specifically used for these charts. Perhaps it's something to do with how I've set up the script file?
(function( root, $, undefined ) {
"use strict";
$(function () {
// DOM ready, take it away
var wins = $("#wins").text();
var losses = $("#losses").text();
var draws = $("#draws").text();
var winsstrike = $("#wins-strike").text();
var winsgrapple = $("#wins-grapple").text();
var winssubmit = $("#wins-submit").text();
var winsother = $("#wins-other").text();
var recorddata = [{
value: 1*wins,
color: "#eb3f3d",
label: "Wins"
}, {
value: 1*losses,
color: "#ec582a",
label: "Losses"
}, {
value: 1*draws,
color: "#f8a430",
label: "Draws"
}
]
var recordoptions = {
animation: true,
segmentShowStroke : true,
segmentStrokeColor : "#191919",
percentageInnerCutout : 80
};
var winsdata = [{
value: 1*winsstrike,
color: "#eb3f3d",
label: "Strike"
}, {
value: 1*winsgrapple,
color: "#E82521",
label: "Grappling"
}, {
value: 1*winssubmit,
color: "#CB1815",
label: "Submission"
}, {
value: 1*winsother,
color: "#A61411",
label: "Other"
}
]
var winsoptions = {
animation: true,
segmentShowStroke : true,
segmentStrokeColor : "#191919",
percentageInnerCutout : 80
};
var c = $('#recordChart');
var ct = c.get(0).getContext('2d');
var ctx = document.getElementById("recordChart").getContext("2d");
myNewChart = new Chart(ct).Doughnut(recorddata, recordoptions);
var c1 = $('#winsbyChart');
var ct1 = c1.get(0).getContext('2d');
var ctx1 = document.getElementById("winsbyChart").getContext("2d");
myNewChart1 = new Chart(ct1).Doughnut(winsdata, winsoptions);
});
} ( this, jQuery ));
Related
We want to plot live data in this site https://www.highcharts.com/demo/live-data is it possible to plot it with Highcharter library in R language if not is there any another solution to do that with R language?
Here is JavaScript code:
var defaultData = 'https://demo-live-data.highcharts.com/time-data.csv';
var urlInput = document.getElementById('fetchURL');
var pollingCheckbox = document.getElementById('enablePolling');
var pollingInput = document.getElementById('pollingTime');
function createChart() {
Highcharts.chart('container', {
chart: {
type: 'spline'
},
title: {
text: 'Live Data'
},
accessibility: {
announceNewData: {
enabled: true,
minAnnounceInterval: 15000,
announcementFormatter: function (allSeries, newSeries, newPoint) {
if (newPoint) {
return 'New point added. Value: ' + newPoint.y;
}
return false;
}
}
},
data: {
csvURL: urlInput.value,
enablePolling: pollingCheckbox.checked === true,
dataRefreshRate: parseInt(pollingInput.value, 10)
}
});
if (pollingInput.value < 1 || !pollingInput.value) {
pollingInput.value = 1;
}
}
urlInput.value = defaultData;
// We recreate instead of using chart update to make sure the loaded CSV
// and such is completely gone.
pollingCheckbox.onchange = urlInput.onchange = pollingInput.onchange = createChart;
// Create the chart
createChart();
I have been struggling with this one for days now, really need some help. I need to apply gradient colors and some custom styling to our ChartJs bar chart, that contains call reporting data which comes from the back-end server. I found a way how to apply the styles and gradients, but can't figure out how to configure datasets to display correct data from the server, instead of some random numbers (eg. 10,20,30), like I tried for gradientGreen below. Any ideas?
//main html
<div class="row mb-4 mt-4">
<div class="col-9">
<h4 class="text-center">Call Distribution</h4>
#await Component.InvokeAsync("HourlyCallTotals", new { from = Model.From, to = Model.To, customer = Model.customer, site = Model.site })
</div>
//component html
#model CallReporter.ViewModels.BasicFilter
<div id="hourlyChart">
</div>
<script>
var HourlyCallData = #Html.RenderAction("HourlyTotals", "Calls", "", new { from = Model.from.ToString("s"), to = Model.to.ToString("s"), customer = Model.customer, site = Model.site })
</script>
//relevant part of JS function for Chart
function hoursChartAjax() {
var hourlyChart = $('#hourlyChart').html('<canvas width="400" height="300"></canvas>').find('canvas')[0].getContext('2d');
// set gradients for bars
let gradientGreen = hourlyChart.createLinearGradient(0, 0, 0, 400);
gradientGreen.addColorStop(0, '#66d8b0');
gradientGreen.addColorStop(1, '#1299ce');
let gradientBlue = hourlyChart.createLinearGradient(0, 0, 0, 400);
gradientBlue.addColorStop(0, '#1299ce');
gradientBlue.addColorStop(1, '#2544b7');
if (hourlyChart !== undefined) {
$.get(base + "Calls/HourlyTotals", { from: from.format(), to: to.format(), customer: currentCustomer.id, site: currentSite }, function (data) {
// set the default fonts for the chart
Chart.defaults.global.defaultFontFamily = 'Nunito';
Chart.defaults.global.defaultFontColor = '#787878';
Chart.defaults.global.defaultFontSize = 12;
var chart = new Chart(hourlyChart, {
type: 'bar',
data: {
labels: ['6AM', '9AM', '12AM', '3PM', '6PM', '9PM', '12PM'],
datasets: [
{
label: 'Total outgoing calls',
backgroundColor: gradientBlue,
data: HourlyCallData
},
{
label: 'Total incoming calls',
backgroundColor: gradientGreen,
data: [10, 20, 30]
}
]
},
//relevant part of back-end code that returns call data as Json
totalsContainer.Totals = allCallsHourly.OrderBy(x => x.Date).ToList();
return Json(new
{
labels = totalsContainer.Totals.Select(x => x.Date.ToString("hh tt")),
datasets = new List<object>() {
new { label = "Total Outgoing Calls", backgroundColor = "#1299CE", data = totalsContainer.Totals.Select(x => x.TotalOutgoingCalls) },
new { label = "Total Incoming Calls", backgroundColor = "#00B050", data = totalsContainer.Totals.Select(x => x.TotalIncomingCalls) } }
});
Attached img with console log and error, after trying solution below:
If the data comes formatted in the right way, you can just write this:
var chart = new Chart(hourlyChart, {
type: 'bar',
data: data: data
}
If not you could do it like so:
var chart = new Chart(hourlyChart, {
type: 'bar',
data: {
labels: data.labels,
datasets: [
{
label: data.datasets[0].label,
backgroundColor: gradientBlue,
data: data.datasets[0].data
},
{
label: data.datasets[1].label,
backgroundColor: gradientGreen,
data: data.datasets[1].data
}
]
}
}
I am learning how use the Google Charts API, to be more specific Material cloumn charts.
I want to show all labels in hAxis, for example (1,2,3,4,5 [...]), but my chart shows them in the format (5,10,15, [...]).
I have tried the suggestions from this question, but without success.
This is my chart currently:
And this is my code:
desenharGrafico(data: Array<any>) {
var rows: Array<any> = [];
for (var item of data) {
var rua = item.rua;
var valor = item.valor;
var valorCortado = item.valorCortado;
var objeto = { c: [{ v: rua }, { v: valor }, { v: valorCortado }] };
rows.push(objeto);
}
var chartData = new google.visualization.DataTable({
cols: [
{ id: '', label: 'Rua', type: 'number' },
{ id: '', label: 'Faturado', type: 'number' },
{ id: '', label: 'Corte', type: 'number' }
],
rows: rows
});
var options =
{
title: "Período: " + this.data1 + ' á ' + this.data2,
hAxis: { slantedText: true, showTextEvery: 1 },
legend: "none",
};
var chart = new google.charts.Bar(document.getElementById('cortes-rua'));
chart.draw(chartData, google.charts.Bar.convertOptions(options));
}
there are many options that are simply not supported by Material charts,
including slantedText & showTextEvery
see --> Tracking Issue for Material Chart Feature Parity
an alternative solution is to use 'string' values for the x-axis
this will result in a Discrete axis, vs. Continuous
with enough room, a Discrete axis will display all labels...
The following code is used to display a chart. The problem is the "data" is hard coded in. How can I change this so that the chart displays values which are displayed using:
<div id="name"> </div>
<div id="testscore"></div>
The above 2 div's contain dynamic values. I want to display these values in the chart.
<script type="text/javascript">
window.onload = function () {
var chart = new CanvasJS.Chart("chartContainer",
{
// title:{
// text: "Olympic Medals of all Times (till 2012 Olympics)"
// },
animationEnabled: true,
legend: {
cursor:"pointer",
itemclick : function(e) {
if (typeof (e.dataSeries.visible) === "undefined" || e.dataSeries.visible) {
e.dataSeries.visible = false;
}
else {
e.dataSeries.visible = true;
}
chart.render();
}
},
axisY: {
title: "Time"
},
toolTip: {
shared: true,
content: function(e){
var str = '';
var total = 0 ;
var str3;
var str2 ;
for (var i = 0; i < e.entries.length; i++){
var str1 = "<span style= 'color:"+e.entries[i].dataSeries.color + "'> " + e.entries[i].dataSeries.name + "</span>: <strong>"+ e.entries[i].dataPoint.y + "</strong> <br/>" ;
total = e.entries[i].dataPoint.y + total;
str = str.concat(str1);
}
str2 = "<span style = 'color:DodgerBlue; '><strong>"+e.entries[0].dataPoint.label + "</strong></span><br/>";
str3 = "<span style = 'color:Tomato '>Total: </span><strong>" + total + "</strong><br/>";
return (str2.concat(str)).concat(str3);
}
},
data: [
{
type: "bar",
showInLegend: true,
name: "Black",
color: "#000000",
dataPoints: [
{ y: 0.18, label: "Name"},
{ y: 0.12, label: "Name 1"},
{ y: 0.59, label: "Name 2"},
{ y: 1.15, label: "Name 3"},
]
},
]
});
chart.render();
}
</script>
You can simply call
var data = document.getElementById('name').value;
var data2 = document.getElementById('testscore').value;
If it's a single value, it would work; otherwise, you need to do it this way:
var array = $('#your.id').data('stuff');
Here, "stuff" is nothing but
<div data-stuff="some data" ></div>
Or, create an array by:
var array = new Array();
and finally, store the data into the array.
I'm running into an odd issue with JQuery Flot.
I had been running
var plot = null;
function initPlot () {
plot = $.plot("#graph", myData, { /* my options here */ });
}
and everything worked fine.
I moved my options data into a variable within the scope of the function
var plot = null;
function initPlot () {
var myOptions = { /* my options here */ };
plot = $.plot("#graph", myData, myOptions);
}
and again, everything works fine.
Then I moved the variable to a broader scope (so I could reference it in other functions).
var plot = null;
var myOptions = { /* my options here */ };
function initPlot () {
plot = $.plot("#graph", myData, myOptions);
}
Suddenly it won't plot correctly. What's even more confusing to me is that it gets the values of most of the options--the graph appears, just not the data.
Using Chrome's debugger, I can see that myOptions has the correct value at the time I call $.plot(). I also tried setting a local variable o = myOptions and calling $.plot() with o instead of myOptions, but this, too, fails to plot the data.
What's causing this and how do I fix it?
I should note that I'm using Flot.Grow and Flot.Stack, but disabling these does not change the result.
EDIT (again)
Per the comments, here is literally the state of my code:
<body>
<div id="graph" style="width: 100%; height: 800px;"></div>
<script>
var idMap = {};
var yesData = [];
var noData = [];
var incData = [];
var voteData = [{ label: "Yes votes", data: yesData },
{ label: "No votes", data: noData },
{ label: "Not met quorum", data: incData }];
var ticks = [];
var plot = null;
var myOptions = {
series: {
//stack: true,
lines: {
show: false,
fill: true,
steps: false,
},
bars: {
show: true,
barWidth: .8,
horizontal: true,
},
//grow: {
// active: false,
// steps: 20,
// stepDirection: "up",
// stepMode: "linear",
// valueIndex: 0,
// growings: [{
// valueIndex: 0,
// }]
//},
},
yaxis: {
min: -.2,
max: 10, //dictLen(idMap),
//ticks: ,
//tickLength: 0,
},
xaxis: {
min: 0,
max: 200,
},
grid: {
hoverable: true,
},
};
function dictLen(obj) {
var size = 0, key;
for (key in obj) {
if (obj.hasOwnProperty(key)) size++;
}
return size;
};
function setDataPoint(val) {
var total = val.r["yes"] + val.r["no"];
if (total < val.q) {
incData.push([total, idMap[val.id]]);
}
else {
yesData.push([val.r["yes"], idMap[val.id]]);
noData.push([val.r["no"], idMap[val.id]]);
}
}
function initData() {
$.getJSON('/Vote/results', function (data) {
$.each(data, function (key, val) {
idMap[val.id] = key;
ticks.push([key + .4, val.nm]);
setDataPoint(val);
});
initPlot();
});
}
function initPlot() {
plot = $.plot("#graph", voteData, myOptions);
}
$(document).ready(function () {
initData();
});
</script>
</body>
Turns out I'm a bit of an idiot.
The issue was that I was calculating myOptions.yaxis.max before idMap was populated. Then, while I was waiting for an answer here, I did some refactoring on the database side, which resulted in an empty dataset.
When I fixed the db and set myOptions to only static values, it worked fine.