// This is the main program that sets up a bar chart to visualize data from the Data Canvas - Sense Your City API. // Curran Kelleher March 2015 require(["getLatestData", "barChart", "lineChart", "generateColors", "crossfilter"], function (getLatestData, BarChart, LineChart, generateColors) { // Initialize the bar chart. var barChart = BarChart({ // Bar identity. xColumn: "city", xAxisLabel: "City", // Bar height. yColumn: "temperature", yAxisLabel: "Temperature (°C)", // Bar ordering. sortColumn: "temperature", sortOrder: "descending", // Bar color. colorColumn: "city", // Use a fixed value of 0 for the temperature axis. yDomainMin: 0, // Spacing between bars. barPadding: 0.1, // Tell the chart which DOM element to insert itself into. container: d3.select("#container").node(), // Specify the margin and text label offsets. margin: { top: 10, right: 10, bottom: 60, left: 70 } }); // Initialize the line chart. var lineChart = LineChart({ lineColumn: "city", xColumn: "date", xAxisLabel: "Time", yColumn: "temperature", yAxisLabel: "Temperature (°C)", // Tell the chart which DOM element to insert itself into. container: d3.select("#container").node(), // Specify the margin and text label offsets. margin: { top: 0, right: 20, bottom: 55, left: 70 } }); var commonAxisLabelOffsets = { yAxisLabelOffset: 1.7, // Unit is CSS "em"s xAxisLabelOffset: 1.9 }; lineChart.set(commonAxisLabelOffsets); barChart.set(commonAxisLabelOffsets); // Pass the latest data into the charts. function update(){ getLatestData(function(err, data){ var observation = crossfilter(data), city = observation.dimension( function (d){ return d.city; }), date = observation.dimension( function (d){ return d.date; }); // Pass the full data (all cities by all time) into the line chart. lineChart.data = data; // Pass only the data for the most recent timestamp into the bar chart. date.filter(date.top(1)[0].date); var cityRecords = city.top(Infinity); var cities = cityRecords.map(function (d) { return d.city; }); barChart.data = cityRecords; // Choose colors to use for cities in both charts. var colors = generateColors(cityRecords.length); barChart.colorDomain = lineChart.colorDomain = cities; barChart.colorRange = lineChart.colorRange = colors; }); } // Initialize the data. update(); // Update the data every 5 minutes. setInterval(update, 1000 * 60 * 5); // Sets the `box` model property // based on the size of the container, function computeBoxes(){ barChart.box = { width: container.clientWidth, height: container.clientHeight / 2 }; lineChart.box = { width: container.clientWidth, height: container.clientHeight / 2 }; } // once to initialize `model.box`, and computeBoxes(); // whenever the browser window resizes in the future. window.addEventListener("resize", computeBoxes); });