I have a plot.ly that inputs a number and digits to view the number of frequency. Per say you enter 111222333 and digits 1,2,3. It will display a bar graph of the repetition of each digit. Everything seems to work except one detail, whenever I add random numbers, the graph does not display in order. Here is an example
Below is my JS code:
function plotIt() {
event.preventDefault();
var entireNumber = document.getElementById('fullNumber').value.split("");
var number = document.getElementById('digit').value.split("");
var matchedNumbers = [];
entireNumber.forEach(digit => {
if (number.includes(digit)) {
matchedNumbers.push(digit);
}
});
var layout = {
categoryorder: 'category ascending',
xaxis: {
type: 'category',
title: 'Values',
},
yaxis: {
title: '# of repetitions'
},
title:'Count'
};
var histElements = {
x: matchedNumbers,
type: 'histogram',
marker: {
color: 'rgba(235, 77, 75,1.0);',
},
};
var data = [histElements];
//Using ID for div to plot the graph
Plotly.newPlot('graph', data, layout,{scrollZoom:true});
}
You are using categoryorder: 'category ascending' in layout which does not exist for histograms in Plotly. As of July 2018 you cannot sort categorical data in histograms. But simply sorting your array before passing it to Plotly should work.
function plotIt() {
var entireNumber = document.getElementById('fullNumber').value.split("");
var number = document.getElementById('digit').value.split("");
number.sort();
var matchedNumbers = [];
entireNumber.forEach(digit => {
if (number.includes(digit)) {
matchedNumbers.push(digit);
}
});
matchedNumbers.sort();
var layout = {
xaxis: {
type: 'category',
title: 'Values',
}
};
var histElements = {
x: matchedNumbers,
type: 'histogram'
};
var data = [histElements];
Plotly.newPlot('graph', data, layout);
}
var button = document.getElementById('button');
button.addEventListener("click", plotIt(), false);
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<form>
<input type='number' id='fullNumber' value='144445522123' >
<input type='number' id='digit' value='0123456789'>
</form>
<button type="button" id='button'>Plot me!</button>
<div id='graph'>
</div>
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...
I am trying to create a simple real time chart using epoch.js which updates itself on a click event.
My code posted below has a total of 3 functions. They are:
1) generate a random value
2) generate the current date and time in milliseconds.
3) onclick event that updates chart datapoints.
Though I have datapoints in the right format as required for the chart. I am unable to update it .
Appreciate any help on find out as to why the graph is not working as it should.
///////////////this function generates the date and time in milliseconds//////////
function getTimeValue() {
var dateBuffer = new Date();
var Time = dateBuffer.getTime();
return Time;
}
////////////// this function generates a random value ////////////////////////////
function getRandomValue() {
var randomValue = Math.random() * 100;
return randomValue;
}
////////////// this function is used to update the chart values ///////////////
function updateGraph() {
var newBarChartData = [{
label: "Series 1",
values: [{
time: getTimeValue(),
y: getRandomValue()
}]
}, ];
barChartInstance.push(newBarChartData);
}
////////////// real time graph generation////////////////////////////////////////
var barChartData = [{
label: "Series 1",
values: [{
time: getTimeValue(),
y: getRandomValue()
}]
}, ];
var barChartInstance = $('#barChart').epoch({
type: 'time.bar',
axes: ['right', 'bottom', 'left'],
data: barChartData
});
<head>
<script src="https://code.jquery.com/jquery-1.11.3.js">
</script>
<script src="http://www.goldhillcoldtouch.co.uk/wp-content/uploads/d3.min.js">
</script>
<script src="http://www.goldhillcoldtouch.co.uk/wp-content/uploads/epoch.min.js"></script>
<link rel="stylesheet" type="text/css" href="http://www.goldhillcoldtouch.co.uk/wp-content/uploads/epoch.min.css">
</head>
<div id="barChart" class="epoch category10" style="width:320px; height: 240px;"></div>
<p id="updateMessage" onclick="updateGraph()">click me to update chart</p>
You are pushing the wrong object to barChartInstance when updating the graph. You need to just push the array containing the new data point, instead of pushing the full configuration again.
function updateGraph() {
var newBarChartData = [{time: getTimeValue(), y:getRandomValue()}];
/* Wrong: don't use the full configuration for an update.
var newBarChartData = [{
label: "Series 1",
values: [{
time: getTimeValue(),
y: getRandomValue()
}]
}, ];
*/
barChartInstance.push(newBarChartData);
}
///////////////this function generates the date and time in milliseconds//////////
function getTimeValue() {
var dateBuffer = new Date();
var Time = dateBuffer.getTime();
return Time;
}
////////////// this function generates a random value ////////////////////////////
function getRandomValue() {
var randomValue = Math.random() * 100;
return randomValue;
}
////////////// this function is used to update the chart values ///////////////
function updateGraph() {
var newBarChartData = [{time: getTimeValue(), y:getRandomValue()}];
/*
var newBarChartData = [{
label: "Series 1",
values: [{
time: getTimeValue(),
y: getRandomValue()
}]
}, ];
*/
barChartInstance.push(newBarChartData);
}
////////////// real time graph generation////////////////////////////////////////
var barChartData = [{
label: "Series 1",
values: [{
time: getTimeValue(),
y: getRandomValue()
}]
}, ];
var barChartInstance = $('#barChart').epoch({
type: 'time.bar',
axes: ['right', 'bottom', 'left'],
data: barChartData
});
<head>
<script src="https://code.jquery.com/jquery-1.11.3.js">
</script>
<script src="http://www.goldhillcoldtouch.co.uk/wp-content/uploads/d3.min.js">
</script>
<script src="http://www.goldhillcoldtouch.co.uk/wp-content/uploads/epoch.min.js"></script>
<link rel="stylesheet" type="text/css" href="http://www.goldhillcoldtouch.co.uk/wp-content/uploads/epoch.min.css">
</head>
<div id="barChart" class="epoch category10" style="width:320px; height: 240px;"></div>
<p id="updateMessage" onclick="updateGraph()">click me to update chart</p>
Ok I have a graph using Highcharts.JS that is populated by an api call providing it with XML data.
I have managed to get the data to push and display on the graph as such, but now I am having the issue of "What happens when there is no data for "x" component" In which I found out that it makes the whole graph blank until you click to hide "x" component on the legend.
So I was thinking that I could probably do some conditional to have it check if there is actually data in the array that is made from the XML.
<!DOCTYPE html>
<html>
<head>
<title>Graph</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" src="https://code.highcharts.com/highcharts.js"> </script>
<script>
$(document).ready(function() {
var sgaxml = 'https://sga.quickbase.com/db/bjmdensiu?apptoken=beadyrucxguavbx5isubd6iaqpe&act=API_DoQuery&query=%7B14.EX.%27_FID_9%7D&clist=7.24.25.26.27.28.29.30.31.32.33.34.35.36.37'
var options = {
chart: {
renderTo: 'container',
type: 'column'
},
title: {
text: 'Components Over Time'
},
xAxis: {
categories: []
},
yAxis: {
title: {
text: 'Concentration%'
}
},
series: []
};
// Load the data from the XML file
$.get(sgaxml, function(xml) {
// Split the lines
var xml = $(xml).find('record');
// Variables for the component series
var seriesH = {
name: 'Hydrogen',
data: []
};
var seriesHe = {
name: 'Helium',
data: []
};
var seriesO = {
name: 'Oxygen',
data: []
};
var seriesHs = {
name: 'Hydrogen Sulfide',
data: []
};
var seriesN = {
name: 'Nitrogen',
data: []
};
var seriesC = {
name: 'Carbon Dioxide',
data: []
};
var seriesM = {
name: 'Methane',
data: []
};
var seriesE = {
name: 'Ethane',
data: []
};
var seriesP = {
name: 'Propane',
data: []
};
var seriesIb = {
name: 'Iso-Butane',
data: []
};
var seriesNb = {
name: 'N-Butane',
data: []
};
var seriesIp = {
name: 'Iso-Pentane',
data: []
};
var seriesNp = {
name: 'N-Pentane',
data: []
};
var seriesHex = {
name: 'Hexanes+',
data: []
};
xml.each(function (i, record) {
options.xAxis.categories.push(new Date(parseInt($(record).find('sample_date').text())));
seriesH.data.push(parseFloat($(record).find('hydrogen').text()));
seriesHe.data.push(parseFloat($(record).find('helium').text()));
seriesO.data.push(parseFloat($(record).find('oxygen').text()));
seriesHs.data.push(parseFloat($(record).find('hydrogen_sulfide').text()));
seriesN.data.push(parseFloat($(record).find('nitrogen').text()));
seriesC.data.push(parseFloat($(record).find('co2').text()));
seriesM.data.push(parseFloat($(record).find('methane').text()));
seriesE.data.push(parseFloat($(record).find('ethane').text()));
seriesP.data.push(parseFloat($(record).find('propane').text()));
seriesIb.data.push(parseFloat($(record).find('iso_butane').text()));
seriesNb.data.push(parseFloat($(record).find('n_butane').text()));
seriesIp.data.push(parseFloat($(record).find('iso_pentane').text()));
seriesNp.data.push(parseFloat($(record).find('n_pentane').text()));
seriesHex.data.push(parseFloat($(record).find('hexanes_').text()));
});
console.log(seriesO);
options.series.push(seriesH);
options.series.push(seriesHe);
options.series.push(seriesO);
options.series.push(seriesHs);
options.series.push(seriesN);
options.series.push(seriesC);
options.series.push(seriesM);
options.series.push(seriesE);
options.series.push(seriesP);
options.series.push(seriesIb);
options.series.push(seriesNb);
options.series.push(seriesIp);
options.series.push(seriesNp);
options.series.push(seriesHex);
console.log('options: ', options);
var chart = new Highcharts.Chart(options);
});
});
</script>
</head>
<body>
<div id="container" style=" width: 1000px; height: 600px; margin: 0 auto "></div>
</body>
</html>
<!--
XML FROM CALL
=============
<qdbapi>
<action>API_DoQuery</action>
<errcode>0</errcode>
<errtext>No error</errtext>
<dbinfo>
<name>RESULT</name>
<desc/>
</dbinfo>
<variables>
<co2>Carbon Dioxide</co2>
<methane>methane</methane>
</variables>
<chdbids></chdbids>
<record>
<sample_date>1386892800000</sample_date>
<hydrogen>0.002</hydrogen>
<helium>0.114</helium>
<oxygen/>
<hydrogen_sulfide/>
<nitrogen>1.926</nitrogen>
<co2>0.454</co2>
<methane>82.163</methane>
<ethane>6.353</ethane>
<propane>4.760</propane>
<iso_butane>0.618</iso_butane>
<n_butane>1.819</n_butane>
<iso_pentane>0.491</iso_pentane>
<n_pentane>0.544</n_pentane>
<hexanes_>0.756</hexanes_>
<update_id>1408654196361</update_id>
</record>
<record>
<sample_date>1383782400000</sample_date>
<hydrogen>0.006</hydrogen>
<helium>0.038</helium>
<oxygen/>
<hydrogen_sulfide/>
<nitrogen>0.512</nitrogen>
<co2>0.844</co2>
<methane>83.178</methane>
<ethane>8.678</ethane>
<propane>3.631</propane>
<iso_butane>0.493</iso_butane>
<n_butane>1.097</n_butane>
<iso_pentane>0.342</iso_pentane>
<n_pentane>0.371</n_pentane>
<hexanes_>0.810</hexanes_>
<update_id>1408981434690</update_id>
</record>
<record>
<sample_date>1369699200000</sample_date>
<hydrogen>0.004</hydrogen>
<helium>0.060</helium>
<oxygen/>
<hydrogen_sulfide/>
<nitrogen>1.684</nitrogen>
<co2>0.443</co2>
<methane>77.742</methane>
<ethane>10.430</ethane>
<propane>6.842</propane>
<iso_butane>0.587</iso_butane>
<n_butane>1.482</n_butane>
<iso_pentane>0.232</iso_pentane>
<n_pentane>0.249</n_pentane>
<hexanes_>0.245</hexanes_>
<update_id>1408981112624</update_id>
</record>
</qdbapi>
I've attempted to us isnan() as I was told it would be doable with it, but that didn't have any results.
There is already a way to handle this in highcharts. See noData.
noData: {
style: {
fontWeight: 'bold',
fontSize: '15px',
color: '#303030'
}
}
You need to include an extra library (modules/no-data-to-display.js) from highcharts but it is dead simple.