I am creating a project using JavaScript. In my project i am integrating google charts, In my chart i want to show only five labels.I don't know how can i do this.Here is code:
var N = 10;
// Array filled with N values at '0'
var zero_array = [];
for (i = 0; i < N; i++)
zero_array.push(0);
// The data of the chart, describe the differents sets of data you want with points, colors...
var data = {
labels: zero_array,
datasets: [
{
showXLabels: 5,
label: zero_array, // Name of the line
data: zero_array, // data to represent
// The following makes the line way less ugly
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)",
}
]
};
// We wait for everything to be loaded
window.onload = function main() {
// Get the context of the canvas
var ctx = document.getElementById("line_example").getContext("2d");
// Create the Chart object
var line_example_chart = new Chart(ctx).Line(data);
// Used for the labels on the X axis
var label_idx = 1;
// Function to execute to remove then add a new random value to the chart
function rand_value() {
// Generate a random integer
var rand_val = Math.floor(Math.random() * 100);
// Remove the point at the far left of the chart
line_example_chart.removeData();
// Add the random value at the far right of the chart
line_example_chart.addData([rand_val], label_idx++);
}
// Run rand_value() every 2 seconds
window.setInterval(rand_value, 2000);
}
plunker link:
https://plnkr.co/edit/fat6hRS4lFnAEjoiSORW?p=preview
please help.
Looking at your code, just change N to 5:
var N = 5;
https://plnkr.co/edit/eJP4G6bYuGB5NaYvcQGX?p=preview
Please update below line and you can see only 5 nodes in your chart
var N = 5;
Related
At the outset, I inform you that I am a novice javascript programmer. I'm writing an application to dynamically draw a circle marker on a map. I use the leaflet library. As the source, it uses data loaded from a csv file. The csv file consists of three columns: date, x coordinate, y coordinate. At the moment the map works in such a way that it draws all markers at one time.
var map = L.map("map");
L.tileLayer("http://{s}.tile.osm.org/{z}/{x}/{y}.png").addTo(map);
map.setView([51.95, 19.55], 6);
var myRenderer = L.canvas({ padding: 0.02 });
for (var j=1; j<lines.length; j++)
{
var values = lines[j].split(';'); // Split up the comma seperated values
var x= values[2];
var y = values[3];
var data2 = values[1];
var markery2 = [];
markery2.push(y,x);
document.getElementById("demo").innerHTML =
"Data: " + data2;
console.log("JSON");
console.log(data2);
L.circleMarker(markery2, {
color: 'blue',
fillColor: 'blue',
fillOpacity: 0.2,
weight: 1,
radius: 3,
renderer: myRenderer
}).addTo(map).bindPopup('marker ' + j);
//Set up the data arrays
}
}
});
Ultimately, I would like to read records from specific dates, ascending and drawn in such a order on the map with a 3-second time interval
Welcome to SO!
Look for setTimeout.
Or it can be easier for you to begin with setInterval.
I'm using ChartJS to display a timeseries as a bar chart. Is there some way to separate the tick resolution on the x axis from the width of the bars?
The snippet below demonstrates the problem; it is showing hourly data over one week. Because options.scales.xAxes[0].time.unit is set to day, the tick marks appear one per day but the bars are also one day wide. Setting the unit to hour makes the bars the right width but leads to hundreds of tick marks on the x axis and makes the labels unreadable.
Is there some way to have the best of both?
const RANGE = (a,b) => Array.from((function*(x,y){
while (x <= y) yield x++;
})(a,b));
labels = [];
for(var ii = 0; ii < 170; ii++) {
labels.push((1483228800 + ii * 3600) * 1000);
}
var canvas = document.getElementById('chart'),
ctx = canvas.getContext('2d'),
startingData = {
labels: labels,
datasets: [
{
fillColor: "rgba(220,220,220,0.2)",
strokeColor: "rgba(220,220,220,1)",
pointColor: "rgba(220,220,220,1)",
pointStrokeColor: "#fff",
data: RANGE(1, 170),
label: 'Data'
},
]
},
options = {
scales: {
xAxes: [{
type: 'time',
time: {
unit: 'day',
}
}]
}
};
// Reduce the animation steps for demo clarity.
var myLiveChart = new Chart(ctx, {
type: 'bar',
data: startingData,
options: options
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.bundle.min.js"></script>
</head>
<body>
Hello, world.<br>
<canvas id="chart" width="500" height="300"></canvas>
</body>
</html>
The property unitStepSize might be what you are looking for.
Here is a JSFiddle with a example
As per the documentation:
The number of units between grid lines.
I made a chart in chartJS and I would like to update it using new data based on what the user chooses from a drop down list, using the same canvas. The problem is when i do the update function, the chart updates with the new data but it keeps coming back to the original chart after a while. How can i solve this? Here's the code, thank you for any help:
/* Original Chart */
var ctx3 = document.getElementById("canvas3").getContext("2d");
var canvas3 = new Chart(ctx3, {
type: 'line',
data: {
labels: stationRentalsLabels,
datasets: [{
label: 'Wypożyczenia',
fillColor: "rgba(220,280,220,0.5)",
strokeColor: "rgba(220,220,220,1)",
backgroundColor: "rgba(153,255,51,0.4)",
data: stationRentalsData
}]
}
});
/* event listener on drop-down list, when triggered, update chart */
select.addEventListener('change', function() {
updateChart()
});
/* Update Chart */
function updateChart() {
var stationRentalsHoursTemp = [];
var stationRentalName = [];
var determineHour = selectNumber.options[selectNumber.selectedIndex].innerHTML;
for (var i = 0; i < stationRentalsHours.length; i++) {
if (determineHour == stationRentalsHours[i]) {
stationRentalsHoursTemp.push(stationRentalsData[i])
stationRentalName.push(stationRentalsLabels[i]);
}
}
/* Updated Chart */
var ctx3 = document.getElementById("canvas3").getContext("2d");
var canvas3 = new Chart(ctx3, {
type: 'line',
data: {
labels: stationRentalName,
datasets: [{
label: 'Wypożyczenia',
fillColor: "rgba(220,280,220,0.5)",
strokeColor: "rgba(220,220,220,1)",
backgroundColor: "rgba(153,255,51,0.4)",
data: stationRentalsHoursTemp
}]
}
});
}
You are creating new chart on update function in the same div as before but in order to do that you need to destroy the previous instance of the chart by calling the destroy function before calling the updateChart function.
canvas3.destroy();
Another approach to solving your problem is by replacing the data not the chart itself when the updateChart function is called by calling the update function(Not initializing a new chart)
function updateChart() {
var stationRentalsHoursTemp = [];
var stationRentalName = [];
var determineHour = selectNumber.options[selectNumber.selectedIndex].innerHTML;
for (var i = 0; i < stationRentalsHours.length; i++) {
if (determineHour == stationRentalsHours[i]) {
stationRentalsHoursTemp.push(stationRentalsData[i])
stationRentalName.push(stationRentalsLabels[i]);
}
}
// just update the label and dataset not the entire chart
canvas3.data.labels = stationRentalName;
canvas3.data.datasets[0].data = stationRentalsHoursTemp;
canvas3.update();
}
I am using a chart in my page using chart.js I have on my x axis dates while on my y axis values(cost). I want to keep the line chart continue its value until there is a change and have coded for that. Here is the output
In this as marked if the value is same I have dots plotted. I have an option to remove all dots but I want to remove dots if the value is same as previous.(there is no change). I would like to know if this is doable. If please guide me how to go for it?
Its not the same as marked for being duplicate...
I want them to be true or flse based on value. If value is zero or same as previous then dont display dot
HERE IS MY CODE
as.dashboard = {};
as.dashboard.adjustWidgetsHeight = function () {
var maxHeight = 0;
$(".panel-widget .panel-heading").height('auto');
$(".panel-widget .panel-heading").each(function () {
if ($(this).height() > maxHeight) {
maxHeight = $(this).height();
}
});
$(".panel-widget .panel-heading").height(maxHeight);
};
as.dashboard.initChart = function () {
var data = {
labels: dayss,
//Number - Tension of the bezier curve between points
bezierCurveTension : 0.4,
datasets: [
{
label: "Machine costs History",
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)",
bezierCurve : false,
data: costVariations
}
, {
label: "My third dataset", // This ONE IS DUMMY IT HELPS IN
// SOLVING OVERLAPPING TOOL TIPS
}
]
};
var ctx = document.getElementById("myChart").getContext("2d");
var myLineChart = new Chart(ctx).Line(data, {
responsive: true,
maintainAspectRatio: false,
tooltipTemplate: "<%if (value!=0){%><%= value %> <%= units %> <%}%>",
multiTooltipTemplate: "<%if (value!=0){%><%= value %> <%= units %> <%}%>",
});
};
$(document).ready(function () {
as.dashboard.adjustWidgetsHeight();
as.dashboard.initChart();
});
...
for (var i = 1; i <= data.datasets[0].data.length - 1; i++)
if (data.datasets[0].data[i - 1] === data.datasets[0].data[i])
myChart.datasets[0].points[i].display = false;
where myChart is your chart object
Fiddle - http://jsfiddle.net/3tok57dL/
I am trying to get a BarChart appear using MVC, EF and json. For some reason the Bar Chart does not load and Google Chrome shows the following error "Uncaught TypeError: Cannot read property 'length' of undefined" in the console.
I am struggling to find the error in my code and hope someone can help me.
DashboardController
[AjaxOnly]
public ActionResult WeeklyLatenessSummary()
{
ChartHelper chart = new ChartHelper();
DateTime d = DateTime.Today;
int offset = d.DayOfWeek - DayOfWeek.Monday;
offset = (offset < 0) ? 6 : offset;
DateTime startDate = d.AddDays(-offset);
DateTime endDate = startDate.AddDays(7);
var data = (from a in _db.Attendances
join at in _db.AttendanceTypes on a.Type equals at.AttendanceTypeID
where a.Date >= startDate
&& a.Date < endDate
&& at.AttendanceTypeCode == "L"
group at by at.AttendanceTypeDescription into g
select new
{
value = g.Count()
}).ToList();
return Json(JsonConvert.SerializeObject(chart.PopulateBarChart("Weekly Lateness", data)), JsonRequestBehavior.AllowGet);
}
JSON Result
"[{\"label\":\"Weekly Lateness\",\"data\":\"3\",\"fillColor\":\"#F7464A\",\"strokeColor\":\"#F7464A\",\"highlightFill\":\"#FF5A5E\",\"highlightStroke\":\"#FF5A5E\"}]"
View
<div class="col-md-12">
<div class=" panel panel-success">
<div class="panel-heading">
<h3 class="panel-title">Weekly Lateness Summary</h3>
</div><!--End of panel-heading-->
<div class="panel-body">
<canvas id="weekly-lateness" width="650" height="300" class="center-block"></canvas>
</div><!--End of panel-body-->
</div><!--End of panel-->
</div><!--End of col-md-12-->
smChart.js
var ctx3 = $("#weekly-lateness").get(0).getContext("2d");
var barChartOptions = {
//Boolean - Whether the scale should start at zero, or an order of magnitude down from the lowest value
scaleBeginAtZero: true,
//Boolean - Whether grid lines are shown across the chart
scaleShowGridLines: true,
//String - Colour of the grid lines
scaleGridLineColor: "rgba(0,0,0,.05)",
//Number - Width of the grid lines
scaleGridLineWidth: 1,
//Boolean - Whether to show horizontal lines (except X axis)
scaleShowHorizontalLines: true,
//Boolean - Whether to show vertical lines (except Y axis)
scaleShowVerticalLines: true,
//Boolean - If there is a stroke on each bar
barShowStroke: true,
//Number - Pixel width of the bar stroke
barStrokeWidth: 2,
//Number - Spacing between each of the X value sets
barValueSpacing: 5,
//Number - Spacing between data sets within X values
barDatasetSpacing: 1,
//String - A legend template
legendTemplate: "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<datasets.length; i++){%><li><span style=\"background-color:<%=datasets[i].fillColor%>\"></span><%if(datasets[i].label){%><%=datasets[i].label%><%}%></li><%}%></ul>"
}
var getDaysInMonth = function (month, year) {
return new Date(year, month, 0).getDate();
}
var dates = [];
for (var i = 1; i <= getDaysInMonth(8,2015); i++) {
dates.push(i);
}
window.onload = function () {
$.ajax({
type: "GET",
dataType: "json",
url: "/Dashboard/WeeklyLatenessSummary/",
success: function (data) {
var json = JSON.parse(data);
var chartData = [];
for (var k in json) {
chartData.push(json[k])
}
if (chartData.length == 0) {
$('#weekly-lateness').hide();
$('#weekly-lateness').before("<h3 class='text-center'>No Data</h3>");
}
else {
var myPieChart3 = new Chart(ctx3).Bar(chartData, barChartOptions)
}
}
});
}
You're building the chartData variable incorrectly. For reference, here is what it should look like (from http://www.chartjs.org/docs/#bar-chart)
{
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]
}
] };
The labels (not to be confused with label which is the series name)correspond to the x axis entries and the there is a datasets element for each series. Each series has as many entries in its data array as there are entries in labels
With the sample JSON you've given, here's one way to make the data appear
var chartData = {
labels: ['Potatoes'],
datasets: []
};
for (var k in json) {
chartData.datasets.push(json[k])
}
It will be easier to change it based on your requirements about what needs to be displayed and on which dimension.
I would venture to say it is bombing on your legend template when it is rendered.
datasets is undefined
legendTemplate: "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<datasets.length; i++){%><li><span style=\"background-color:<%=datasets[i].fillColor%>\"></span><%if(datasets[i].label){%><%=datasets[i].label%><%}%></li><%}%></ul>"