text:
<file_sep># power-radar
power-radar test for react netive
<file_sep>import React from 'react';
import {
	Platform,
	ScrollView,
	StyleSheet,
	Text,
	View,
	Dimensions,
	FlatList
} from 'react-native';

import { VictoryPie, VictoryAnimation, VictoryLabel   } from "victory-native";
import Svg from 'react-native-svg';
const { width } = Dimensions.get('window');

export default class HomeScreen extends React.Component {
	static navigationOptions = {
		header: null,
	};

	constructor() {
		super();
		this.state = {
			percent: 25,
			data: this.getData(0)
		};
	}

	getData(percent) {
		return [{ x: 1, y: percent }, { x: 2, y: 100 - percent }];
	}

	componentDidMount() {
		this.setStateInterval = window.setInterval(() => {
			this.setState({
				percent: 100, data: this.getData(200)
			});
		}, 200);
	}

	componentWillUnmount() {
		window.clearInterval(this.setStateInterval);
	}

	render() {
		return (
			<View style={styles.container}>
				<ScrollView style={styles.container} contentContainerStyle={styles.contentContainer}>
					<View style={styles.header}>
						<Text>Tzaban Residence</Text>
						<Text>Zevulun St 20, Tel Aviv Yafo</Text>
					</View>
					<Svg viewBox="0 0 400 400" height={400} width={width}>
						<VictoryPie
							standalone={false}
							width={400} height={400}
							data={[{x: 1, y:0}, {x: 2, y : 100}]}
							innerRadius={120}
							cornerRadius={25}
							padAngle={30}
							startAngle={165}
							endAngle={650}
							labels={() => null}
							style={{
								data: { fill: () => {
										return "gray"
									}
								}
							}}
						/>
						<VictoryPie
							standalone={false}
							animate={{ duration: 1000 }}
							width={400} height={400}
							data={this.state.data}
							innerRadius={120}
							cornerRadius={25}
							padAngle={30}
							startAngle={195}
							endAngle={650}
							labels={() => null}
							style={{
								data: { fill: (d) => {
										const color = d.y > 30 ? "green" : "red";
										return d.x === 1 ? color : "transparent";
									}
								}
							}}
						/>

						<VictoryAnimation duration={1000} data={this.state}>
							{(newProps) => {
								return (
									<VictoryLabel
										textAnchor="middle" verticalAnchor="middle"
										x={200} y={200}
										text={`${Math.round(newProps.percent)}Kw`}
										style={{ fontSize: 45 }}
									/>
								);
							}}
						</VictoryAnimation>
						<VictoryLabel
							textAnchor="middle" verticalAnchor="middle"
							x={50} y={350}
							text={`0Kw`}
							style={{ fontSize: 16 }}
						/>
						<VictoryLabel
							textAnchor="middle" verticalAnchor="middle"
							x={width/2} y={330}
							text={`1.0`}
							style={{ fontSize: 25 }}
						/>
						<VictoryLabel
							textAnchor="middle" verticalAnchor="middle"
							x={width/2} y={350}
							text={`$ Per Hour`}
							style={{ fontSize: 16 }}
						/>
						<VictoryLabel
							textAnchor="middle" verticalAnchor="middle"
							x={350} y={350}
							text={`400Kw`}
							style={{ fontSize: 16 }}
						/>
					</Svg>
					<FlatList
						data={[
							{key: 'Mains', percent: 50},
							{key: 'Heating and Cooling', percent: 80},
							{key: 'Generation', percent: 50},
							{key: 'Home Appliances', percent: 60},
							{key: 'Industrial Heating', percent: 10},
							{key: 'Kitchen/Cafeteria', percent: 28},
							{key: 'Lighting', percent: 40},
							{key: 'Machinery', percent: 50},
						]}
						renderItem={({item}) => <View
							style={{
								flexDirection: 'row',
								height: 30,
								padding: 20,
								flex: 1,
								width: '100%',
								justifyContent: 'flex-start'
							}}>
							<Text style={styles.item}>{item.key}</Text>
							<View style={styles.bar}>
								<View style={{position: 'absolute', borderRadius: 10,  height: 15, width: '100%', backgroundColor: 'grey', flex: 1}} />
								<View style={{position: 'absolute' , borderRadius: 10, backgroundColor: 'blue', height: 20,  width: item.percent + '%'}} />
							</View>
							<Text style={{flex: 0, height: 20}}>{item.percent}</Text>
						</View>
						}
					/>
				</ScrollView>
			</View>
		);
	}
}

const styles = StyleSheet.create({
	container: {
		flex: 1,
		backgroundColor: '#fff',
	},
	item:{
		flex: 1,
		height: 20,
	},
	bar: {
		position: 'relative',
		height: 20,
		flex: 1,
		justifyContent: 'center',
		elevation:2,
		shadowColor: "#000000",
		shadowOpacity: 0.8,
		shadowRadius: 2,
		shadowOffset: {
			height: 5,
			width: 1
		}
	},
	barBg: {
		position: 'absolute',
		backgroundColor: 'grey',
		flex: 1
	},
	developmentModeText: {
		marginBottom: 20,
		color: 'rgba(0,0,0,0.4)',
		fontSize: 14,
		lineHeight: 19,
		textAlign: 'center',
	},
	contentContainer: {
		paddingTop: 30,
	},
	welcomeContainer: {
		alignItems: 'center',
		marginTop: 10,
		marginBottom: 20,
	},
	welcomeImage: {
		width: 100,
		height: 80,
		resizeMode: 'contain',
		marginTop: 3,
		marginLeft: -10,
	},
	getStartedContainer: {
		alignItems: 'center',
		marginHorizontal: 50,
	},
	homeScreenFilename: {
		marginVertical: 7,
	},
	codeHighlightText: {
		color: 'rgba(96,100,109, 0.8)',
	},
	codeHighlightContainer: {
		backgroundColor: 'rgba(0,0,0,0.05)',
		borderRadius: 3,
		paddingHorizontal: 4,
	},
	getStartedText: {
		fontSize: 17,
		color: 'rgba(96,100,109, 1)',
		lineHeight: 24,
		textAlign: 'center',
	},
	tabBarInfoContainer: {
		position: 'absolute',
		bottom: 0,
		left: 0,
		right: 0,
		...Platform.select({
			ios: {
				shadowColor: 'black',
				shadowOffset: { height: -3 },
				shadowOpacity: 0.1,
				shadowRadius: 3,
			},
			android: {
				elevation: 20,
			},
		}),
		alignItems: 'center',
		backgroundColor: '#fbfbfb',
		paddingVertical: 20,
	},
	tabBarInfoText: {
		fontSize: 17,
		color: 'rgba(96,100,109, 1)',
		textAlign: 'center',
	},
	navigationFilename: {
		marginTop: 5,
	},
	helpContainer: {
		marginTop: 15,
		alignItems: 'center',
	},
	helpLink: {
		paddingVertical: 15,
	},
	helpLinkText: {
		fontSize: 14,
		color: '#2e78b7',
	},
});

repo_name: gzaban/power-radar


text:
<file_sep>import csv, datetime
from statistics import mean

def google_data(word):
    google_dict = {}
    with open("facebook_app/data/{}.csv".format(word), 'rt') as f:
        reader = list(csv.reader(f))
        for num, row in enumerate(reader):
            if "Top cities for {}".format(word) in row:
                google_dict.update(cities(reader, num + 2))
                google_dict.update(distinctcountry(reader, num + 2))
            if "Top regions for {}".format(word) in row:
                google_dict.update(regions(reader, num + 2))
            if "Top searches for {}".format(word) in row:
                google_dict.update(top_searched(reader, num))
            if "2015-02-08 - 2015-02-14" in row:
                google_dict.update(trend_12(reader, num))
                google_dict.update(year_average(reader, num))
                google_dict.update(month_min_max(reader, num))
            if "2015-08-09 - 2015-08-15" in row:
                google_dict.update(trend_6(reader, num))
            if "2015-11-01 - 2015-11-07" in row:
                google_dict.update(trend_3(reader, num))
    return google_dict

def year_average(a_list, num):
    a_dict = {}
    mentions = []
    count = 0
    while count < 50:
        mentions.append(int(a_list[num + count][1]))
        count += 1
    a_dict['year_average'] = mean(mentions)
    return a_dict

def trend_3(a_list, num):
    a_dict = {}
    num += 1
    month_a_sum = a_list[num][1] + a_list[num + 1][1] + \
                  a_list[num + 2][1] + a_list[num + 3][1]
    month_b_sum = a_list[num + 4][1] + a_list[num + 5][1] + \
                  a_list[num + 6][1] + a_list[num + 7][1]
    month_c_sum = a_list[num + 8][1] + a_list[num + 9][1] + \
                  a_list[num + 10][1] + a_list[num + 11][1]
    if month_a_sum <= month_b_sum and month_b_sum <= month_c_sum:
        a_dict['trend3'] = 1
        return a_dict
    elif month_a_sum > month_b_sum and month_b_sum > month_c_sum:
        a_dict['trend3'] = -1
        return a_dict
    else:
        a_dict['trend3'] = 0
        return a_dict

def trend_6(a_list, num):
    a_dict = {}
    week_count = 0
    tally = 0
    while week_count < 24:
        month_a_sum = a_list[num][1] + a_list[num + 1][1] + \
                      a_list[num + 2][1] + a_list[num + 3][1]
        month_b_sum = a_list[num + 4][1] + a_list[num + 5][1] + \
                      a_list[num + 6][1] + a_list[num + 7][1]
        if month_a_sum <= month_b_sum:
            num += 8
            week_count += 8
            tally += 1
        elif month_a_sum > month_b_sum:
            num += 8
            week_count += 8
            tally -= 1
    if tally >= 11:
        a_dict['trend6'] = 1
    elif tally <= -11:
        a_dict['trend6'] = -1
    else:
        a_dict['trend6'] = 0
    return a_dict

def trend_12(a_list, num):
    a_dict = {}
    week_count = 0
    tally = 0
    while week_count < 48:
        month_a_sum = a_list[num][1] + a_list[num + 1][1] + \
                      a_list[num + 2][1] + a_list[num + 3][1]
        month_b_sum = a_list[num + 4][1] + a_list[num + 5][1] + \
                      a_list[num + 6][1] + a_list[num + 7][1]
        if month_a_sum <= month_b_sum:
            num += 8
            week_count += 8
            tally += 1
        elif month_a_sum > month_b_sum:
            num += 8
            week_count += 8
            tally -= 1
    if tally >= 11:
        a_dict['trend12'] = 1
    elif tally <= -11:
        a_dict['trend12'] = -1
    else:
        a_dict['trend12'] = 0
    return a_dict

def month_min_max(a_list, num):
    month_max_num = 0
    month_min_num = 1000000
    a_dict = {'monthminnum': 0, 'monthmaxnum': 0, 'monthmin': 0, 'monthmax': 0}
    week_count = 0
    while week_count < 48:
        month_sum = int(a_list[num][1]) + int(a_list[num + 1][1]) + \
                    int(a_list[num + 2][1]) + int(a_list[num + 3][1])
        if month_sum > month_max_num:
            a_dict['monthmaxnum'] = int(a_list[num][0][5:7])
            month_max_num = month_sum
        elif month_sum < month_min_num:
            a_dict['monthminnum'] = int(a_list[num][0][5:7])
            month_min_num = month_sum
        week_count += 4
        num += 4
    a_dict['monthmin'] = month_converter(a_dict['monthminnum'])
    a_dict['monthmax'] = month_converter(a_dict['monthmaxnum'])
    return a_dict

def top_searched(a_list, num):
    a_dict = {}
    a_dict['toprelated'] = a_list[num + 1][0]
    a_dict['toprelated_rank'] = a_list[num + 1][1]
    return a_dict

def distinctcountry(a_list, num):
    a_dict = {}
    country_list = []
    for list in a_list[num: num+7]:
        split_list = list[0].split(' (')
        country_list.append(split_list[1].strip(')'))
    a_dict.update({"distinctcountry": len(set(country_list))})
    return a_dict

def regions(a_list, num):
    a_dict = {}
    count = 0
    while count < 5:
        if len(a_list[num+count]) == 0:
            a_dict.update({"country{}".format(count): 'null',
                           "country{}rank".format(count): 0})
        else:
           a_dict.update({"country{}".format(count): a_list[num+count][0],
                          "country{}rank".format(count): a_list[num+count][1]})
        count += 1
    return a_dict

def city_cleanup(a_list, count):
    a_dict = {}
    city = a_list[0].split(' (')
    a_dict['city{}'.format(count)] = city[0]
    a_dict['city{}rank'.format(count)] = a_list[1]
    return a_dict

def cities(a_list, num):
    a_dict = {}
    count = 0
    while count < 5:
        a_dict.update(city_cleanup(a_list[num+count], count))
        count += 1
    return a_dict

def month_converter(num):
    month = datetime.date(1900, num, 1).strftime('%B')
    return month
<file_sep>from pandas import DataFrame
import csv

google_dict = {}
with open("facebook_app/data/pizza.csv", 'rt') as f:
    reader = list(csv.reader(f))
    for num, row in enumerate(reader):
        if "2015-02-08 - 2015-02-14" in row:
            date_list = [a_list[0] for a_list in reader[num:num+51]]
            for date in date_list:
                print(date[21:])
            #df = DataFrame({'string': reader[num], 'visits': visits, 'date': date})
<file_sep>$(document).on('ready', function () {

  // narrative
  $('.btn').click(function(e){
    var category = $('#category-selector').val()

    if (category == "Food") {
      words = ["Pizza", "Bacon", "Chicken", "Steak", "Tofu"]
    } else if (category == "Luxury Cars") {
      words = ["Tesla", "Porsche", "Mercedes", "Range Rover", "Ferrari"]
    } else if (category == "Top NBA Teams") {
      words = ["Cavaliers", "Warriors", "Spurs", "Knicks", "Lakers"]
    } else if (category == "Workout trends") {
      words = ["Crossfit", "Pilates", "Yoga", "HIIT", "Barre"]
    } else if (category == "Illness") {
      words = ["Breast Cancer", "Heart Disease", "Zika", "Plague", "Ebola"]
    } else if (category == "Prog Lang") {
      words = ["Python", "Ruby", ".NET", "Java", "PHP"]
    } else if (category == "Jacksons") {
      words = ["<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>"]
    } else if (category == "Warriors") {
      words = ["<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>"]
    } else if (category == "TV Brands") {
      words = ["Sony", "Samsung", "Vizio", "LG", "Panasonic"]
    } else if (category == "Top Movies") {
      words = ["Mad Max", "Star Wars", "Revenant", "Spotlight", "Martian"]
    }
    console.log(words)

    encodedCategory = category.replace(" ", "_");

    $.each(words, function( index, word ) {
      encodedWord = word.replace(" ", "_");

      // get narrative for that word
      $.ajax({
        type: "GET",
        url: "http://localhost:5000/api/v1.0/narrative/" + encodedCategory + "/" + encodedWord,
        success: function(response) {
          $('#response-' + index).html( response['narrative'].replace(/xxx/g, "<br />") )
          $('#word-' + index).html(word)
        }
      });
    });

    $('#nav').show()
    $('#response-0').show()
  });

  $('.nav-button').hover(function(e){
    var idNumber = $(e.target).attr('id').replace( /^\D+/g, '');
    $('.response').hide()
    $('#response-' + idNumber).show()
  });

});
<file_sep>from flask import Blueprint, flash, request, jsonify
from flask.ext.cors import CORS
from pytrends.pyGTrends import pyGTrends
import time, os, timeit
from random import randint
from .google_search import google_data
from .wordsmith_api import request_content

facebook_app = Blueprint("facebook_app", __name__)
CORS(facebook_app)
google_username = os.environ['GOOGLE_USERNAME']
google_password = os.<PASSWORD>['GOOGLE_PASSWORD']

@facebook_app.route('/api/v1.0/narrative/<category>/<item>', methods=['GET'])
def get_narrative(category, item):
    item = item.lower().replace('_', ' ')
    user_dict = google_data(item)
    user_dict.update({'item': item, 'category': category})
    content = request_content("hackathon-2016", "category-trends-2",
                              "projects", user_dict)
    clean_content = content['data']['content'].replace('\n', 'xxx')
    return jsonify({'narrative': clean_content})

def google_trends(search_word):
    # search_word = search_word
    # #connect to Google
    # connector = pyGTrends(google_username, google_password)
    # # make request
    # connector.request_report(search_word)
    # # wait a random amount of time between requests to avoid bot detection
    # time.sleep(randint(5, 10))
    # # download file
    # connector.save_csv("", "facebook_app/data/{}".format(search_word))
    # return 'hola'
    return google_data(search_word)
<file_sep>import requests, os
from flask import jsonify
import json

_app_key = os.environ['API_KEY']
api_version = '0.1'
base_url = 'https://anvil.autoi.co/api/v{}/'.format(api_version)

def wordsmith_post(ext, data={}):
    headers = {'Authorization' : 'Bearer {}'.format(_app_key),
               'Content-Type': 'application/json'}
    x = requests.post(base_url + ext,
                     headers = headers,
                     data = json.dumps({'data': data}))
    return x.json()

def wordsmith_request(ext):
    headers = {'Authorization' : 'Bearer {}'.format(_app_key)}
    x = requests.get(base_url + ext, headers = headers)
    return x.json()

def data_slugs():
    project_raw = call_wordsmith('projects')
    return [project['slug'] for project in project_raw['data']]

def template_slugs(data_slug):
    project_raw = call_wordsmith('projects')
    for index, project in enumerate(project_raw['data']):
        if project['slug'] == data_slug:
            return [template['slug'] for template in project['templates']]
        elif (index + 1) == len(project_raw['data']):
            return "Slug not found"

def data_schema(data_slug):
    raw_return = call_wordsmith('projects/{}'.format(data_slug))
    return raw_return['data']['schema']

def request_content(data_slug, template_slug, gamertag, user_dict):
    ext = 'templates/{}/{}/outputs'.format(data_slug,template_slug)
    return wordsmith_post(ext, data = user_dict)

branch_name: refs/heads/master

languages: JavaScript Python

repo_language: JavaScript


text:
<file_sep>using Microsoft.EntityFrameworkCore;
using OnlineFoodDelivery.Core;
using System;
using System.Collections.Generic;
using System.Text;

namespace OnlineFoodDelivery.Data
{
    public class OnlineFoodDeliveryDbContext : DbContext
    {
        public OnlineFoodDeliveryDbContext(DbContextOptions<OnlineFoodDeliveryDbContext> options) : base(options)
        {

        }
        public DbSet<Restaurant> Restaurants { get; set; }
    }
}
<file_sep>@using OnlineFoodDelivery.Core
@model Restaurant

@Model.Name

        Location: @Model.Location
        Cuisine: @Model.Cuisine

            Get Details

            Edit

            Delete

<file_sep>@using Online_Food_Delivery
@namespace Online_Food_Delivery.Pages
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@addTagHelper *, Online Food Delivery

languages: HTML+Razor C#

repo_language: HTML+Razor

repo_name: sauravjaiswa/Online-Food-Delivery


text:
<file_sep>var width =500;
var height= 500;

d3.csv("calvinCollegeSeniorScores.csv", function(csv) {
    for (var i=0; i<csv.length; ++i) {
		csv[i].GPA = Number(csv[i].GPA);
		csv[i].SATM = Number(csv[i].SATM);
		csv[i].SATV = Number(csv[i].SATV);
		csv[i].ACT = Number(csv[i].ACT);
    }
    var satmExtent = d3.extent(csv, function(row) { return row.SATM; });
    var satvExtent = d3.extent(csv, function(row) { return row.SATV; });
    var actExtent = d3.extent(csv,  function(row) { return row.ACT;  });
    var gpaExtent = d3.extent(csv,  function(row) {return row.GPA;   });

    var satExtents = {
	"SATM": satmExtent,
	"SATV": satvExtent
    };

    // Axis setup
    var xScale = d3.scaleLinear().domain(satmExtent).range([50, 470]);
    var yScale = d3.scaleLinear().domain(satvExtent).range([470, 30]);

    var xScale2 = d3.scaleLinear().domain(actExtent).range([50, 470]);
    var yScale2 = d3.scaleLinear().domain(gpaExtent).range([470, 30]);

    var xAxis = d3.axisBottom().scale(xScale);
    var yAxis = d3.axisLeft().scale(yScale);

    var xAxis2 = d3.axisBottom().scale(xScale2);
    var yAxis2 = d3.axisLeft().scale(yScale2);

    //Create SVGs for charts
    var chart1 = d3.select("#chart1")
					.append("svg:svg")
	                .attr("width",width)
	                .attr("height",height);

    var chart2 = d3.select("#chart2")
					.append("svg:svg")
	                .attr("width",width)
	                .attr("height",height);

	// add brush code HERE
	var brush = d3.brush().extent([[0,0], [width, height]]);
	var brush2 = d3.brush().extent([[0,0], [width, height]]);

	brush.on('start', handleStart1)
		.on('brush', handleMove1)
		.on('end', handleEnd1);
	brush2.on('start', handleStart2)
		.on('brush', handleMove2)
		.on('end', handleEnd2);

	var b1 = chart1.append('g');
	b1.call(brush);
	var b2 = chart2.append('g');
	b2.call(brush2);

	function rectContains(selection, x ,y){
		//console.log("selection = ", selection)
		var brushx0 = selection.selection[0][0];
		var brushx1 = selection.selection[1][0];
		var brushy0 = selection.selection[0][1];
		var brushy1 = selection.selection[1][1];
		if (x<=brushx1 && x>=brushx0 && y<=brushy1 && y>=brushy0){
			return true;
		}
		return false;
	}
	function handleStart1(){
		b2.call(brush2.move, null);
		b1.call(brush);
		if (!d3.event.selection){
			clear1();
		}

	}
	function handleStart2(){
		b1.call(brush.move, null);
		b2.call
		if (!d3.event.selection){
			clear2();
		}

	}

	function handleMove1(p){
		var selection = d3.event;
		//chart2.selectAll('.selected2').classed('selected2', false);
		if (selection.selection != null){
			chart2.selectAll("circle").classed('selected2', function(d){
				var x1 = xScale(d.SATM);
				var y1 = yScale(d.SATV);
				return rectContains(selection, x1, y1);
			});
		}
	}
	function handleMove2(p){
		var selection = d3.event;
		//chart1.selectAll('.selected').classed('selected', false);
		if (selection.selection != null){
			chart1.selectAll("circle").classed('selected', function(d){
				var x2 = xScale2(d.ACT);
				var y2 = yScale2(d.GPA);
				return rectContains(selection, x2, y2);
			});
		}
	}
	function handleEnd1(){
		if (!d3.event.selection){
			clear1();
		}
	}
	function handleEnd2(){
		if (!d3.event.selection){
			clear2();
		}
	}
	function clear1(){
		chart1.selectAll('.selected').classed('selected', false);
		chart2.selectAll('.selected2').classed('selected2', false);
	}
	function clear2(){
		chart1.selectAll('.selected').classed('selected', false);
		chart2.selectAll('.selected2').classed('selected2', false);
	}
	 //add scatterplot points
	var text = d3.select('#chart3');
	var temp1= chart1
	   .selectAll("circle")
	   //.append('g')
	   .data(csv)
	   .enter()

	   .append("circle")
	   .attr("id",function(d,i) {return 'a' + i;} )
	   .attr("cx", function(d) { return xScale(d.SATM); })
	   .attr("cy", function(d) { return yScale(d.SATV); })
	   .attr("r", 5)
	   .attr('stroke', 'black')
	   .attr('fill', 'black')
	   	.on('click', function(d,i){
		   chart1.selectAll('circle').classed('clicked', false);
		   chart2.selectAll('circle').classed('clicked', false);
		   chart2.select('#b' + i).classed('clicked', true);
		   text.select("#satm").html(d.SATM);
		   text.select("#satv").html(d.SATV);
		   text.select("#act").html(d.ACT);
		   text.select("#gpa").html(d.GPA);
	   });

	var temp2= chart2
	   .selectAll("circle")
	   //.append('g')
	   .data(csv)
	   .enter()
	   .append("circle")
	   .attr("id",function(d,i) {return 'b' + i;} )
	   .attr("stroke", "black")
	   .attr('fill', 'black')
	   .attr("cx", function(d) { return xScale2(d.ACT); })
	   .attr("cy", function(d) { return yScale2(d.GPA); })
	   .attr("r", 5)
	   .on('click', function(d, i) {
		   chart1.selectAll('circle').classed('clicked', false);
		   chart2.selectAll('circle').classed('clicked', false);
		   chart1.select("#a" + i).classed("clicked", true);
		   text.select("#satm").html(d.SATM);
		   text.select("#satv").html(d.SATV);
		   text.select("#act").html(d.ACT);
		   text.select("#gpa").html(d.GPA);
	   });

    chart1 // or something else that selects the SVG element in your visualizations
		.append("g") // create a group node
		.attr("transform", "translate(0,"+ (width -30)+ ")")
		.call(xAxis); // call the axis generator
	chart1.append("text")
		.attr("class", "label")
		.attr("x", width-16)
		.attr("y", height)
		.style("text-anchor", "end")
		.text("SATM");

    chart1 // or something else that selects the SVG element in your visualizations
		.append("g") // create a group node
		.attr("transform", "translate(50, 0)")
		.call(yAxis);
	chart1.append("text")
		.attr("class", "label")
		.attr("transform", "rotate(-90)")
		.attr("y", 10)
		.attr("dy", ".71em")
		.style("text-anchor", "end")
		.text("SATV");

    chart2 // or something else that selects the SVG element in your visualizations
		.append("g") // create a group node
		.attr("transform", "translate(0,"+ (width -30)+ ")")
		.call(xAxis2);
	chart2.append("text")
		.attr("class", "label")
		.attr("x", width-16)
		.attr("y", height)
		.style("text-anchor", "end")
		.text("ACT");

    chart2 // or something else that selects the SVG element in your visualizations
		.append("g") // create a group node
		.attr("transform", "translate(50, 0)")
		.call(yAxis2);
	chart2.append("text")
		.attr("class", "label")
		.attr("transform", "rotate(-90)")
		.attr("y", 10)
		//.attr("x", 250)
		.attr("dy", ".71em")
		.style("text-anchor", "end")
		.text("GPA");

	});
<file_sep>// Define the div for the tooltip
var div = d3.select("body").append("div")
    .attr("class", "tooltip")
    .style("opacity", 0);
var div2 = d3.select("body").append("div")
    .attr("class", "tooltip2")
    .style("opacity", 0);

d3.csv("college.csv", function(error, data) {
  if (error) throw error;
  var GroupByRegion = {};
  var GroupByLocale = {};
  var GroupByControl = {};
  var option = "Control";
  for (var i=0; i<data.length; ++i) {
	data[i].MedianDebt = Number(data[i].MedianDebt);
	data[i].Expenditure = Number(data[i].Expenditure);
	data[i].MedianFamilyIncome = Number(data[i].MedianFamilyIncome);
  data[i].FederalLoans = Number(data[i].FederalLoans);

  data[i].White = Number(data[i].White);
	data[i].Black = Number(data[i].Black);
	data[i].Asian = Number(data[i].Asian);
	data[i].Hispanic = Number(data[i].Hispanic);
  }
  GroupByControl['Private'] = data.filter(function(d){return d.Control == 'Private';});
  GroupByControl['Public'] = data.filter(function(d){return d.Control == 'Public';});
  var avgWhiteC = {}
  avgWhiteC['Private'] = GroupByControl['Private'].reduce((acc, curRow) => {return acc + (curRow.White.toFixed(4) / (GroupByControl['Private'].length).toFixed(4));},0);
  avgWhiteC['Public'] = GroupByControl['Public'].reduce((acc, curRow) => {return acc + (curRow.White.toFixed(4) / (GroupByControl['Public'].length).toFixed(4));},0);
  var avgBlackC = {}
  avgBlackC['Private'] = GroupByControl['Private'].reduce((acc, curRow) => {return acc + (curRow.Black.toFixed(4) / (GroupByControl['Private'].length).toFixed(4));},0);
  avgBlackC['Public'] = GroupByControl['Public'].reduce((acc, curRow) => {return acc + (curRow.Black.toFixed(4) / (GroupByControl['Public'].length).toFixed(4));},0);
  var avgHispanicC = {}
  avgHispanicC['Private'] = GroupByControl['Private'].reduce((acc, curRow) => {return acc + (curRow.Hispanic.toFixed(4) / (GroupByControl['Private'].length).toFixed(4));},0);
  avgHispanicC['Public'] = GroupByControl['Public'].reduce((acc, curRow) => {return acc + (curRow.Hispanic.toFixed(4) / (GroupByControl['Public'].length).toFixed(4));},0);
  var avgAsianC = {}
  avgAsianC['Private'] = GroupByControl['Private'].reduce((acc, curRow) => {return acc + (curRow.Asian.toFixed(4) / (GroupByControl['Private'].length).toFixed(4));},0);
  avgAsianC['Public'] = GroupByControl['Public'].reduce((acc, curRow) => {return acc + (curRow.Asian.toFixed(4) / (GroupByControl['Public'].length).toFixed(4));},0);

  GroupByLocale['MidC'] = data.filter(function(d){return d.Locale == "Mid-size City";});
  GroupByLocale['MidS'] = data.filter(function(d){return d.Locale == "Mid-size Suburb";});
  GroupByLocale['LargeC'] = data.filter(function(d){return d.Locale == "Large City";});
  GroupByLocale['SmallC'] = data.filter(function(d){return d.Locale == "Small City";});
  GroupByLocale['SmallS'] = data.filter(function(d){return d.Locale == "Small Suburb";});
  GroupByLocale['LargeS'] = data.filter(function(d){return d.Locale == "Large Suburb";});
  GroupByLocale['FringeT'] = data.filter(function(d){return d.Locale == "Fringe Town";});
  GroupByLocale['RemoteT'] = data.filter(function(d){return d.Locale == "Remote Town";});
  GroupByLocale['FringeR'] = data.filter(function(d){return d.Locale == "Fringe Rural";});
  GroupByLocale['RemoteR'] = data.filter(function(d){return d.Locale == "Remote Rural";});
  GroupByLocale['DistantT'] = data.filter(function(d){return d.Locale == "Distant Town";});
  GroupByLocale['DistantR'] = data.filter(function(d){return d.Locale == "Distant Rural";});

  var avgWhiteL = {}
  avgWhiteL['MidC'] = GroupByLocale['MidC'].reduce((acc, curRow) => {return acc + (curRow.White.toFixed(4) / (GroupByLocale['MidC'].length).toFixed(4));},0);
  avgWhiteL['MidS'] = GroupByLocale['MidS'].reduce((acc, curRow) => {return acc + (curRow.White.toFixed(4) / (GroupByLocale['MidS'].length).toFixed(4));},0);
  avgWhiteL['LargeC'] = GroupByLocale['LargeC'].reduce((acc, curRow) => {return acc + (curRow.White.toFixed(4) / (GroupByLocale['LargeC'].length).toFixed(4));},0);
  avgWhiteL['SmallC'] = GroupByLocale['SmallC'].reduce((acc, curRow) => {return acc + (curRow.White.toFixed(4) / (GroupByLocale['SmallC'].length).toFixed(4));},0);
  avgWhiteL['LargeS'] = GroupByLocale['LargeS'].reduce((acc, curRow) => {return acc + (curRow.White.toFixed(4) / (GroupByLocale['LargeS'].length).toFixed(4));},0);
  avgWhiteL['SmallS'] = GroupByLocale['SmallS'].reduce((acc, curRow) => {return acc + (curRow.White.toFixed(4) / (GroupByLocale['SmallS'].length).toFixed(4));},0);
  avgWhiteL['FringeT'] = GroupByLocale['FringeT'].reduce((acc, curRow) => {return acc + (curRow.White.toFixed(4) / (GroupByLocale['FringeT'].length).toFixed(4));},0);
  avgWhiteL['RemoteT'] = GroupByLocale['RemoteT'].reduce((acc, curRow) => {return acc + (curRow.White.toFixed(4) / (GroupByLocale['RemoteT'].length).toFixed(4));},0);
  avgWhiteL['FringeR'] = GroupByLocale['FringeR'].reduce((acc, curRow) => {return acc + (curRow.White.toFixed(4) / (GroupByLocale['FringeR'].length).toFixed(4));},0);
  avgWhiteL['RemoteR'] = GroupByLocale['RemoteR'].reduce((acc, curRow) => {return acc + (curRow.White.toFixed(4) / (GroupByLocale['RemoteR'].length).toFixed(4));},0);
  avgWhiteL['DistantT'] = GroupByLocale['DistantT'].reduce((acc, curRow) => {return acc + (curRow.White.toFixed(4) / (GroupByLocale['DistantT'].length).toFixed(4));},0);
  avgWhiteL['DistantR'] = GroupByLocale['DistantR'].reduce((acc, curRow) => {return acc + (curRow.White.toFixed(4) / (GroupByLocale['DistantR'].length).toFixed(4));},0);
  var avgBlackL = {};
  avgBlackL['MidC'] = GroupByLocale['MidC'].reduce((acc, curRow) => {return acc + (curRow.Black.toFixed(4) / (GroupByLocale['MidC'].length).toFixed(4));},0);
  avgBlackL['MidS'] = GroupByLocale['MidS'].reduce((acc, curRow) => {return acc + (curRow.Black.toFixed(4) / (GroupByLocale['MidS'].length).toFixed(4));},0);
  avgBlackL['LargeC'] = GroupByLocale['LargeC'].reduce((acc, curRow) => {return acc + (curRow.Black.toFixed(4) / (GroupByLocale['LargeC'].length).toFixed(4));},0);
  avgBlackL['SmallC'] = GroupByLocale['SmallC'].reduce((acc, curRow) => {return acc + (curRow.Black.toFixed(4) / (GroupByLocale['SmallC'].length).toFixed(4));},0);
  avgBlackL['LargeS'] = GroupByLocale['LargeS'].reduce((acc, curRow) => {return acc + (curRow.Black.toFixed(4) / (GroupByLocale['LargeS'].length).toFixed(4));},0);
  avgBlackL['SmallS'] = GroupByLocale['SmallS'].reduce((acc, curRow) => {return acc + (curRow.Black.toFixed(4) / (GroupByLocale['SmallS'].length).toFixed(4));},0);
  avgBlackL['FringeT'] = GroupByLocale['FringeT'].reduce((acc, curRow) => {return acc + (curRow.Black.toFixed(4) / (GroupByLocale['FringeT'].length).toFixed(4));},0);
  avgBlackL['RemoteT'] = GroupByLocale['RemoteT'].reduce((acc, curRow) => {return acc + (curRow.Black.toFixed(4) / (GroupByLocale['RemoteT'].length).toFixed(4));},0);
  avgBlackL['FringeR'] = GroupByLocale['FringeR'].reduce((acc, curRow) => {return acc + (curRow.Black.toFixed(4) / (GroupByLocale['FringeR'].length).toFixed(4));},0);
  avgBlackL['RemoteR'] = GroupByLocale['RemoteR'].reduce((acc, curRow) => {return acc + (curRow.Black.toFixed(4) / (GroupByLocale['RemoteR'].length).toFixed(4));},0);
  avgBlackL['DistantT'] = GroupByLocale['DistantT'].reduce((acc, curRow) => {return acc + (curRow.Black.toFixed(4) / (GroupByLocale['DistantT'].length).toFixed(4));},0);
  avgBlackL['DistantR'] = GroupByLocale['DistantR'].reduce((acc, curRow) => {return acc + (curRow.Black.toFixed(4) / (GroupByLocale['DistantR'].length).toFixed(4));},0);
  var avgHispanicL = {};
  avgHispanicL['MidC'] = GroupByLocale['MidC'].reduce((acc, curRow) => {return acc + (curRow.Hispanic.toFixed(4) / (GroupByLocale['MidC'].length).toFixed(4));},0);
  avgHispanicL['MidS'] = GroupByLocale['MidS'].reduce((acc, curRow) => {return acc + (curRow.Hispanic.toFixed(4) / (GroupByLocale['MidS'].length).toFixed(4));},0);
  avgHispanicL['LargeC'] = GroupByLocale['LargeC'].reduce((acc, curRow) => {return acc + (curRow.Hispanic.toFixed(4) / (GroupByLocale['LargeC'].length).toFixed(4));},0);
  avgHispanicL['SmallC'] = GroupByLocale['SmallC'].reduce((acc, curRow) => {return acc + (curRow.Hispanic.toFixed(4) / (GroupByLocale['SmallC'].length).toFixed(4));},0);
  avgHispanicL['LargeS'] = GroupByLocale['LargeS'].reduce((acc, curRow) => {return acc + (curRow.Hispanic.toFixed(4) / (GroupByLocale['LargeS'].length).toFixed(4));},0);
  avgHispanicL['SmallS'] = GroupByLocale['SmallS'].reduce((acc, curRow) => {return acc + (curRow.Hispanic.toFixed(4) / (GroupByLocale['SmallS'].length).toFixed(4));},0);
  avgHispanicL['FringeT'] = GroupByLocale['FringeT'].reduce((acc, curRow) => {return acc + (curRow.Hispanic.toFixed(4) / (GroupByLocale['FringeT'].length).toFixed(4));},0);
  avgHispanicL['RemoteT'] = GroupByLocale['RemoteT'].reduce((acc, curRow) => {return acc + (curRow.Hispanic.toFixed(4) / (GroupByLocale['RemoteT'].length).toFixed(4));},0);
  avgHispanicL['FringeR'] = GroupByLocale['FringeR'].reduce((acc, curRow) => {return acc + (curRow.Hispanic.toFixed(4) / (GroupByLocale['FringeR'].length).toFixed(4));},0);
  avgHispanicL['RemoteR'] = GroupByLocale['RemoteR'].reduce((acc, curRow) => {return acc + (curRow.Hispanic.toFixed(4) / (GroupByLocale['RemoteR'].length).toFixed(4));},0);
  avgHispanicL['DistantT'] = GroupByLocale['DistantT'].reduce((acc, curRow) => {return acc + (curRow.Hispanic.toFixed(4) / (GroupByLocale['DistantT'].length).toFixed(4));},0);
  avgHispanicL['DistantR'] = GroupByLocale['DistantR'].reduce((acc, curRow) => {return acc + (curRow.Hispanic.toFixed(4) / (GroupByLocale['DistantR'].length).toFixed(4));},0);
  var avgAsianL = {};
  avgAsianL['MidC'] = GroupByLocale['MidC'].reduce((acc, curRow) => {return acc + (curRow.Asian.toFixed(4) / (GroupByLocale['MidC'].length).toFixed(4));},0);
  avgAsianL['MidS'] = GroupByLocale['MidS'].reduce((acc, curRow) => {return acc + (curRow.Asian.toFixed(4) / (GroupByLocale['MidS'].length).toFixed(4));},0);
  avgAsianL['LargeC'] = GroupByLocale['LargeC'].reduce((acc, curRow) => {return acc + (curRow.Asian.toFixed(4) / (GroupByLocale['LargeC'].length).toFixed(4));},0);
  avgAsianL['SmallC'] = GroupByLocale['SmallC'].reduce((acc, curRow) => {return acc + (curRow.Asian.toFixed(4) / (GroupByLocale['SmallC'].length).toFixed(4));},0);
  avgAsianL['LargeS'] = GroupByLocale['LargeS'].reduce((acc, curRow) => {return acc + (curRow.Asian.toFixed(4) / (GroupByLocale['LargeS'].length).toFixed(4));},0);
  avgAsianL['SmallS'] = GroupByLocale['SmallS'].reduce((acc, curRow) => {return acc + (curRow.Asian.toFixed(4) / (GroupByLocale['SmallS'].length).toFixed(4));},0);
  avgAsianL['FringeT'] = GroupByLocale['FringeT'].reduce((acc, curRow) => {return acc + (curRow.Asian.toFixed(4) / (GroupByLocale['FringeT'].length).toFixed(4));},0);
  avgAsianL['RemoteT'] = GroupByLocale['RemoteT'].reduce((acc, curRow) => {return acc + (curRow.Asian.toFixed(4) / (GroupByLocale['RemoteT'].length).toFixed(4));},0);
  avgAsianL['FringeR'] = GroupByLocale['FringeR'].reduce((acc, curRow) => {return acc + (curRow.Asian.toFixed(4) / (GroupByLocale['FringeR'].length).toFixed(4));},0);
  avgAsianL['RemoteR'] = GroupByLocale['RemoteR'].reduce((acc, curRow) => {return acc + (curRow.Asian.toFixed(4) / (GroupByLocale['RemoteR'].length).toFixed(4));},0);
  avgAsianL['DistantT'] = GroupByLocale['DistantT'].reduce((acc, curRow) => {return acc + (curRow.Asian.toFixed(4) / (GroupByLocale['DistantT'].length).toFixed(4));},0);
  avgAsianL['DistantR'] = GroupByLocale['DistantR'].reduce((acc, curRow) => {return acc + (curRow.Asian.toFixed(4) / (GroupByLocale['DistantR'].length).toFixed(4));},0);

  GroupByRegion["Lakes"] = data.filter(function(d){return d.Region == 'Great Lakes';});
  GroupByRegion["Rocky"] = data.filter(function(d){return d.Region == 'Rocky Mountains';});
  GroupByRegion["Plains"] = data.filter(function(d){return d.Region == 'Great Plains';});
  GroupByRegion["England"] = data.filter(function(d){return d.Region == 'New England';});
  GroupByRegion["FarWest"] = data.filter(function(d){return d.Region == 'Far West';});
  GroupByRegion["Outlying"] = data.filter(function(d){return d.Region == 'Outlying Areas';});
  GroupByRegion["Atlantic"] = data.filter(function(d){return d.Region == 'Mid-Atlantic';});
  GroupByRegion["Southeast"] = data.filter(function(d){return d.Region == 'Southeast';});
  GroupByRegion["Southwest"] = data.filter(function(d){return d.Region == 'Southwest';});

  var avgWhiteR = {}
  avgWhiteR["Lakes"] = GroupByRegion["Lakes"].reduce((acc, curRow) => {return acc + (curRow.White.toFixed(4) / (GroupByRegion["Lakes"].length).toFixed(4)); },0);
  avgWhiteR["Rocky"] = GroupByRegion["Rocky"].reduce((acc, curRow) => {return acc + (curRow.White.toFixed(4) / (GroupByRegion["Rocky"].length).toFixed(4)); },0);
  avgWhiteR["Plains"] = GroupByRegion["Plains"].reduce((acc, curRow) => {return acc + (curRow.White.toFixed(4) / (GroupByRegion["Plains"].length).toFixed(4)); },0);
  avgWhiteR["England"] = GroupByRegion["England"].reduce((acc, curRow) => {return acc + (curRow.White.toFixed(4) / (GroupByRegion["England"].length).toFixed(4)); },0);
  avgWhiteR["FarWest"] = GroupByRegion["FarWest"].reduce((acc, curRow) => {return acc + (curRow.White.toFixed(4) / (GroupByRegion["FarWest"].length).toFixed(4)); },0);
  avgWhiteR["Outlying"] = GroupByRegion["Outlying"].reduce((acc, curRow) => {return acc + (curRow.White.toFixed(4) / (GroupByRegion["Outlying"].length).toFixed(4)); },0);
  avgWhiteR["Atlantic"] = GroupByRegion["Atlantic"].reduce((acc, curRow) => {return acc + (curRow.White.toFixed(4) / (GroupByRegion["Atlantic"].length).toFixed(4)); },0);
  avgWhiteR["Southeast"] = GroupByRegion["Southeast"].reduce((acc, curRow) => {return acc + (curRow.White.toFixed(4) / (GroupByRegion["Southeast"].length).toFixed(4)); },0);
  avgWhiteR["Southwest"] = GroupByRegion["Southwest"].reduce((acc, curRow) => {return acc + (curRow.White.toFixed(4) / (GroupByRegion["Southwest"].length).toFixed(4)); },0);

  var avgBlackR = {}
  avgBlackR["Lakes"] = GroupByRegion["Lakes"].reduce((acc, curRow) => {return acc + (curRow.Black.toFixed(4) / (GroupByRegion["Lakes"].length).toFixed(4)); },0);
  avgBlackR["Rocky"] = GroupByRegion["Rocky"].reduce((acc, curRow) => {return acc + (curRow.Black.toFixed(4) / (GroupByRegion["Rocky"].length).toFixed(4)); },0);
  avgBlackR["Plains"] = GroupByRegion["Plains"].reduce((acc, curRow) => {return acc + (curRow.Black.toFixed(4) / (GroupByRegion["Plains"].length).toFixed(4)); },0);
  avgBlackR["England"] = GroupByRegion["England"].reduce((acc, curRow) => {return acc + (curRow.Black.toFixed(4) / (GroupByRegion["England"].length).toFixed(4)); },0);
  avgBlackR["FarWest"] = GroupByRegion["FarWest"].reduce((acc, curRow) => {return acc + (curRow.Black.toFixed(4) / (GroupByRegion["FarWest"].length).toFixed(4)); },0);
  avgBlackR["Outlying"] = GroupByRegion["Outlying"].reduce((acc, curRow) => {return acc + (curRow.Black.toFixed(4) / (GroupByRegion["Outlying"].length).toFixed(4)); },0);
  avgBlackR["Atlantic"] = GroupByRegion["Atlantic"].reduce((acc, curRow) => {return acc + (curRow.Black.toFixed(4) / (GroupByRegion["Atlantic"].length).toFixed(4)); },0);
  avgBlackR["Southeast"] = GroupByRegion["Southeast"].reduce((acc, curRow) => {return acc + (curRow.Black.toFixed(4) / (GroupByRegion["Southeast"].length).toFixed(4)); },0);
  avgBlackR["Southwest"] = GroupByRegion["Southwest"].reduce((acc, curRow) => {return acc + (curRow.Black.toFixed(4) / (GroupByRegion["Southwest"].length).toFixed(4)); },0);

  var avgHispanicR = {}
  avgHispanicR["Lakes"] = GroupByRegion["Lakes"].reduce((acc, curRow) => {return acc + (curRow.Hispanic.toFixed(4) / (GroupByRegion["Lakes"].length).toFixed(4)); },0);
  avgHispanicR["Rocky"] = GroupByRegion["Rocky"].reduce((acc, curRow) => {return acc + (curRow.Hispanic.toFixed(4) / (GroupByRegion["Rocky"].length).toFixed(4)); },0);
  avgHispanicR["Plains"] = GroupByRegion["Plains"].reduce((acc, curRow) => {return acc + (curRow.Hispanic.toFixed(4) / (GroupByRegion["Plains"].length).toFixed(4)); },0);
  avgHispanicR["England"] = GroupByRegion["England"].reduce((acc, curRow) => {return acc + (curRow.Hispanic.toFixed(4) / (GroupByRegion["England"].length).toFixed(4)); },0);
  avgHispanicR["FarWest"] = GroupByRegion["FarWest"].reduce((acc, curRow) => {return acc + (curRow.Hispanic.toFixed(4) / (GroupByRegion["FarWest"].length).toFixed(4)); },0);
  avgHispanicR["Outlying"] = GroupByRegion["Outlying"].reduce((acc, curRow) => {return acc + (curRow.Hispanic.toFixed(4) / (GroupByRegion["Outlying"].length).toFixed(4)); },0);
  avgHispanicR["Atlantic"] = GroupByRegion["Atlantic"].reduce((acc, curRow) => {return acc + (curRow.Hispanic.toFixed(4) / (GroupByRegion["Atlantic"].length).toFixed(4)); },0);
  avgHispanicR["Southeast"] = GroupByRegion["Southeast"].reduce((acc, curRow) => {return acc + (curRow.Hispanic.toFixed(4) / (GroupByRegion["Southeast"].length).toFixed(4)); },0);
  avgHispanicR["Southwest"] = GroupByRegion["Southwest"].reduce((acc, curRow) => {return acc + (curRow.Hispanic.toFixed(4) / (GroupByRegion["Southwest"].length).toFixed(4)); },0);

  var avgAsianR = {}
  avgAsianR["Lakes"] = GroupByRegion["Lakes"].reduce((acc, curRow) => {return acc + (curRow.Asian.toFixed(4) / (GroupByRegion["Lakes"].length).toFixed(4)); },0);
  avgAsianR["Rocky"] = GroupByRegion["Rocky"].reduce((acc, curRow) => {return acc + (curRow.Asian.toFixed(4) / (GroupByRegion["Rocky"].length).toFixed(4)); },0);
  avgAsianR["Plains"] = GroupByRegion["Plains"].reduce((acc, curRow) => {return acc + (curRow.Asian.toFixed(4) / (GroupByRegion["Plains"].length).toFixed(4)); },0);
  avgAsianR["England"] = GroupByRegion["England"].reduce((acc, curRow) => {return acc + (curRow.Asian.toFixed(4) / (GroupByRegion["England"].length).toFixed(4)); },0);
  avgAsianR["FarWest"] = GroupByRegion["FarWest"].reduce((acc, curRow) => {return acc + (curRow.Asian.toFixed(4) / (GroupByRegion["FarWest"].length).toFixed(4)); },0);
  avgAsianR["Outlying"] = GroupByRegion["Outlying"].reduce((acc, curRow) => {return acc + (curRow.Asian.toFixed(4) / (GroupByRegion["Outlying"].length).toFixed(4)); },0);
  avgAsianR["Atlantic"] = GroupByRegion["Atlantic"].reduce((acc, curRow) => {return acc + (curRow.Asian.toFixed(4) / (GroupByRegion["Atlantic"].length).toFixed(4)); },0);
  avgAsianR["Southeast"] = GroupByRegion["Southeast"].reduce((acc, curRow) => {return acc + (curRow.Asian.toFixed(4) / (GroupByRegion["Southeast"].length).toFixed(4)); },0);
  avgAsianR["Southwest"] = GroupByRegion["Southwest"].reduce((acc, curRow) => {return acc + (curRow.Asian.toFixed(4) / (GroupByRegion["Southwest"].length).toFixed(4)); },0);

  var debtExtent = d3.extent(data, function(row) { return row.MedianDebt;});
  var expenditureExtent = d3.extent(data, function(row) { return row.Expenditure;});
  var incomeExtent = d3.extent(data,  function(row) { return row.MedianFamilyIncome;});
  var loansExtent = d3.extent(data,  function(row) {return row.FederalLoans;});

  var width = 500;
  var height = 510;

  var size = 160;
  var padding = 30;
  var x = d3.scale.linear().range([padding/2, size - padding / 2]);

  var y = d3.scale.linear().range([size - padding / 2, padding / 2]);

  var xAxis = d3.svg.axis().scale(x).orient("bottom").ticks(6);
  xAxis.tickFormat(function(d){
    if (parseInt(d)<1000){
      return d;}
    return (parseInt(d)/1000).toString() + "k";
  });

  var yAxis = d3.svg.axis().scale(y).orient("left").ticks(6);
  yAxis.tickFormat(function(d){
    if (parseInt(d)<1000){
      return d;}
    return (parseInt(d)/1000).toString() + "k";
  });

  var color = d3.scale.ordinal().range(["#98abc5", "#8a89a6", "#7b6888", "#6b486b"]);
  var color_scatter = d3.scale.ordinal().range(["#b3ff66","#00FA9A","#00BFFF","#80ced6","#778899","#e0a4f4","#a845bf","#A52A2A","#B8860B","#f18973","#feb236","#f2f24c"]);
  var color_scatter1 = d3.scale.ordinal().range(["#ccff33","#99cc00","#208000","#80ffaa","#0088cc","#4db8ff","#ccb3ff","#ff66cc","#ff8080"]);
  var color_scatter2 = d3.scale.ordinal().range(["#66d9ff", "#6699ff"]);

  var domainByTrait = {},
      traits = d3.keys(data[0]).filter(function(d){return d=="MedianDebt"||d=="Expenditure"||d=="MedianFamilyIncome";}),
      n = traits.length;
  domainByTrait["FederalLoans"] = loansExtent;
  domainByTrait["MedianFamilyIncome"] = incomeExtent;
  domainByTrait["Expenditure"] = expenditureExtent;
  domainByTrait["MedianDebt"] = debtExtent;

//   traits.forEach(function(trait) {
// 	  console.log(trait);
// 	domainByTrait[trait] = d3.extent(data, function(d) {return d[trait];});
// 	//domainByTrait[trait] = [d3.min(data, trait)-1, d3.max(data, trait)+1];
//   });

  xAxis.tickSize(size * n);
  yAxis.tickSize(-size * n);

  var brush = d3.svg.brush()
      .x(x)
      .y(y)
      .on("brushstart", brushstart)
      .on("brush", brushmove)
      .on("brushend", brushend);

  var svg = d3.select("#scatter").append("svg")
      //.attr("width", size * n + padding)
      //.attr("height", size * n + padding)
	  .attr("width", width)
	  .attr("height", height)
	  .append("g")
      .attr("transform", "translate(" + padding + "," + padding / 2 + ")");

  svg.selectAll(".x.axis")
      .data(traits)
      .enter().append("g")
      .attr("class", "x axis")
      .attr("transform", function(d, i) { return "translate(" + (n - i - 1) * size + ",0)"; })
      .each(function(d) {x.domain(domainByTrait[d]); d3.select(this).call(xAxis); });

  svg.selectAll(".y.axis")
      .data(traits)
      .enter().append("g")
      .attr("class", "y axis")
      .attr("transform", function(d, i) { return "translate(0," + i * size + ")"; })
      .each(function(d) {y.domain(domainByTrait[d]); d3.select(this).call(yAxis); });

  var cell = svg.selectAll(".cell")
      .data(cross(traits, traits))
      .enter().append("g")
      .attr("class", "cell")
      .attr("transform", function(d) { return "translate(" + (n - d.i - 1) * size + "," + d.j * size + ")"; });

  var brush_cell = cell.append('g');
  brush_cell.call(brush);
  var circles;
  cell.each(plot);
  // Titles for the diagonal.
  cell.filter(function(d) { return d.i === d.j; }).append("text")
      .attr("x", padding)
      .attr("y", padding)
      .attr("dy", ".71em")
      .text(function(d) { return d.x; });

  function plot(p) {
    var cell = d3.select(this);
    x.domain(domainByTrait[p.x]);
	  y.domain(domainByTrait[p.y]);

    cell.append("rect")
        .attr("class", "frame")
        .attr("x", padding / 2)
        .attr("y", padding / 2)
        .attr("width", size - padding)
        .attr("height", size - padding);

    circles = cell.selectAll("circle")
        .data(data)
        .enter().append("circle")
        .attr("id",function(d,i) {return 'a' + i;} )
        .attr("cx", function(d) { return x(d[p.x]); })
        .attr("cy", function(d) { return y(d[p.y]); })
        .attr("r", 2.5)
        .style("fill", function(d) { return color_scatter2(d.Control); })
        .on("mouseover", function(d){
          div2.transition()
                  .duration(200)
                  .style("opacity", .9);
          div2.html("Name: " + d.Name + "<br/>"  + option + ": " + d[option])
                  .style("left", (d3.event.pageX) + "px")
                  .style("top", (d3.event.pageY - 28) + "px");
        })
        .on("mouseout", function(d) {
              div2.transition()
                  .duration(500)
                  .style("opacity", 0);
        });
  }

  var brushCell;

  // Clear the previously-active brush, if any.
  function brushstart(p) {
    if (brushCell !== this) {
      d3.select(brushCell).call(brush.clear());
      x.domain(domainByTrait[p.x]);
      y.domain(domainByTrait[p.y]);
      brushCell = this;
    }
  }

  // Highlight the selected circles.
  function brushmove(p) {
    var e = brush.extent();
    svg.selectAll("circle").classed("hidden", function(d) {
      return e[0][0] > d[p.x] || d[p.x] > e[1][0]
          || e[0][1] > d[p.y] || d[p.y] > e[1][1];
    });
  }

  // If the brush is empty, select all circles.
  function brushend() {
    if (brush.empty()){ svg.selectAll(".hidden").classed("hidden", false);
      if (option == "Control") UpdateRaceByControl_noBrush();
      else if (option == "Locale") UpdateRaceByLocale_noBrush();
      else UpdateRaceByRegion_noBrush();
    }
    else{
      if (option == "Control") UpdateRaceByControl();
      else if (option == "Locale") UpdateRaceByLocale();
      else UpdateRaceByRegion();
    }
  }

  var width2 = 400;
  var height2 = 430;
  var svg2 = d3.select("#bar").append("svg")
  .attr("width", width2)
  .attr("height", height2)
  .append("g")
  .attr("transform", "translate(" + 0 + "," + 0 + ")");

  // Legend for bar chart
  var legendVals = ["% White", "% Black", "% Hispanic", "% Asian"];
  var mylegend_container = d3.select("#legend").append('svg').attr("width", 100).attr("height", height2/2);
  var mylegend = mylegend_container.selectAll("#legend")
      .data(legendVals).enter().append('g')
      .attr("class", 'legend')
      .attr("transform", function (d, i) {return "translate(0," + (i * 20+padding*2) + ")"});
  mylegend.append('rect').attr("x", 0).attr("y", 0)
      .attr("width", 10)
      .attr("height", 10)
      .style("fill", function (d, i) {return color(i)});

  mylegend.append('text').attr("x", 20).attr("y", 10)
        //.attr("dy", ".35em")
      .text(function (d, i) {return d})
      .attr("class", "textselected")
      .style("text-anchor", "start")
      .style("font-size", 15);
  //var mylegend = d3.select('#legend').selectAll("legend").data(legendVals)

  //mylegend.enter().append("div").attr("class","legend");

  // var p = mylegend.append("p").attr("class","country-name");
  // p.append("span").attr("class","key-dot").style("background",function(d,i) { return color(i) } )
  // p.insert("text").text(function(d,i) { return d } )

  // Legend for scatter plot
  var scatter_legend_container = d3.select("#scatter_legend").append("svg").attr("width", 150).attr("height", height);
  var scatter_legend = scatter_legend_container.selectAll('#scatter_legend')
      .data(d3.set(data.map( function(d) { return d.Control } ) ).values())
      .enter().append('g')
      .attr("class", "legend")
      .attr("transform", function (d, i) {return "translate(0," + (i * 20+padding*2) + ")"});
  scatter_legend.append('rect').attr("x", 0).attr("y", 0)
      .attr("width", 10)
      .attr("height", 10)
      .style("fill", function (d, i) {return color_scatter2(i)});

  scatter_legend.append('text').attr("x", 20).attr("y", 10)
        //.attr("dy", ".35em")
      .text(function (d, i) {return d})
      .attr("class", "textselected")
      .style("text-anchor", "start")
      .style("font-size", 15);

  // Three buttons
  d3.select("#button").append('g').append('button')
    .attr("class", "button")
    .attr("id", "buttonL")
    .attr("transform", "translate(0,20)")
    .text('Summarize Race by Locality')
    .on('click', function(){
        d3.select(this).style("background-color", "#e6f2ff");
        d3.select("#buttonC").style("background-color", "white");
        d3.select("#buttonR").style("background-color", "white");
        UpdateRaceByLocale(); });
  d3.select("#button").append('g').append('button')
    .attr("class", "button")
    .attr("id", "buttonR")
    .attr("transform", "translate(0,20)")
    .text('Summarize Race by Region')
    .on('click', function(){
        d3.select(this).style("background-color", "#e6f2ff");
        d3.select("#buttonC").style("background-color", "white");
        d3.select("#buttonL").style("background-color", "white");
        UpdateRaceByRegion(); });
  d3.select("#button").append('g').append('button')
    .attr("class", "button")
    .attr("id", "buttonC")
    .attr("transform", "translate(0,20)")
    .text('Summarize Race by Control')
    .on('click', function(){
        d3.select(this).style("background-color", "#e6f2ff");
        d3.select("#buttonL").style("background-color", "white");
        d3.select("#buttonR").style("background-color", "white");
        UpdateRaceByControl(); });

  // Update By Control ////////////////////////////////////////////////////////////////////////////////////////////////////
  function UpdateRaceByControl_noBrush(){
    svg2.selectAll("*").remove();
    option = "Control";
    cell.selectAll("circle").style("fill", function(d) { return color_scatter2(d.Control); });

    d3.select("#scatter_legend").selectAll('*').remove();
    var scatter_legend_container = d3.select("#scatter_legend").append("svg").attr("width", 150).attr("height", height);
    var scatter_legend = scatter_legend_container.selectAll('#scatter_legend')
        .data(d3.set(data.map( function(d) { return d.Control } ) ).values())
        .enter().append('g')
        .attr("class", "legend")
        .attr("transform", function (d, i) {return "translate(0," + (i * 20+padding*2) + ")"});
    scatter_legend.append('rect').attr("x", 0).attr("y", 0)
        .attr("width", 10)
        .attr("height", 10)
        .style("fill", function (d, i) {return color_scatter2(i)});

    scatter_legend.append('text').attr("x", 20).attr("y", 10)
          //.attr("dy", ".35em")
        .text(function (d, i) {return d})
        .attr("class", "textselected")
        .style("text-anchor", "start")
        .style("font-size", 15);

    var x2 = d3.scale.linear().range([0, width2-padding]);
    var y2 =d3.scale.ordinal().rangeRoundBands([height2-padding, padding], .1);
    var xAxis2 = d3.svg.axis().scale(x2).orient("bottom");
    var yAxis2 = d3.svg.axis().scale(y2).orient("left");

    var factorsB = [[avgWhiteC, "White"], [avgBlackC, "Black"], [avgHispanicC, "Hispanic"], [avgAsianC, "Asian"]];
    var controls = ["Private", "Public"];
    var layers = d3.layout.stack()(factorsB.map(function(f){
      return controls.map(function(r){
        return {x: [r, f[1]], y: f[0][r]};
      });
    }));

    x2.domain([0,1]).nice();
    y2.domain(layers[0].map(function(d) { return d.x[0]; }));
    var layer = svg2.selectAll(".layers")
      .data(layers)
      .enter().append("g")
      .attr("class", "layer")
      .style("fill", function(d,i){ return color(i); });

    layer.selectAll("rect")
      .data(function(d){ return d; })
      .enter().append("rect")
      .attr("y", function(d) { return y2(d.x[0]); })
      .attr("x", function(d) { return x2(d.y0); })
      .attr("width", function(d) { return x2(d.y); })
      .attr("height", y2.rangeBand())
      .attr("transform", "translate(" + padding*2 + "," + 0 + ")")
      .on("mouseover", function(d){
        div.transition()
                .duration(200)
                .style("opacity", .9);
        div.html("Proportion of " + d.x[1] + " student: " + (d.y*100).toFixed(2) + "%")
                .style("left", (d3.event.pageX) + "px")
                .style("top", (d3.event.pageY - 28) + "px");
      })
      .on("mouseout", function(d) {
            div.transition()
                .duration(500)
                .style("opacity", 0);
      });

    svg2.append("g")
      .attr("class", "x axis")
      .attr("transform", "translate(" + padding*2 + "," + (height2-padding*1.5) + ")")
      .call(xAxis2);

    svg2.append("g")
      .attr("class", "y axis")
      .attr("transform", "translate(" + padding*2 + "," + 0 + ")")
      .call(yAxis2);

    svg2.append("text")
      .attr("class", "label")
      .attr("x", width2-padding*2.5)
      .attr("y", height2)
      .style("text-anchor", "end")
      .style("font-size", "14px")
      .text("X-axis: Race Distribution");

  }

  // --------------------------------------------------------------------------------------------------------------
  function UpdateRaceByControl(){
    if (brush.empty()){
      UpdateRaceByControl_noBrush();
      return;
    }
    var GroupByControl = {}
    GroupByControl['Private'] = data.filter(function(d,i){return (svg.select('#a' + i)[0][0].className.baseVal != "hidden") && d.Control == 'Private';});
    GroupByControl['Public'] = data.filter(function(d,i){return (svg.select('#a' + i)[0][0].className.baseVal != "hidden") && d.Control == 'Public';});
    var avgWhiteC = {}
    avgWhiteC['Private'] = GroupByControl['Private'].reduce((acc, curRow) => {return acc + (curRow.White.toFixed(4) / (GroupByControl['Private'].length).toFixed(4));},0);
    avgWhiteC['Public'] = GroupByControl['Public'].reduce((acc, curRow) => {return acc + (curRow.White.toFixed(4) / (GroupByControl['Public'].length).toFixed(4));},0);
    var avgBlackC = {}
    avgBlackC['Private'] = GroupByControl['Private'].reduce((acc, curRow) => {return acc + (curRow.Black.toFixed(4) / (GroupByControl['Private'].length).toFixed(4));},0);
    avgBlackC['Public'] = GroupByControl['Public'].reduce((acc, curRow) => {return acc + (curRow.Black.toFixed(4) / (GroupByControl['Public'].length).toFixed(4));},0);
    var avgHispanicC = {}
    avgHispanicC['Private'] = GroupByControl['Private'].reduce((acc, curRow) => {return acc + (curRow.Hispanic.toFixed(4) / (GroupByControl['Private'].length).toFixed(4));},0);
    avgHispanicC['Public'] = GroupByControl['Public'].reduce((acc, curRow) => {return acc + (curRow.Hispanic.toFixed(4) / (GroupByControl['Public'].length).toFixed(4));},0);
    var avgAsianC = {}
    avgAsianC['Private'] = GroupByControl['Private'].reduce((acc, curRow) => {return acc + (curRow.Asian.toFixed(4) / (GroupByControl['Private'].length).toFixed(4));},0);
    avgAsianC['Public'] = GroupByControl['Public'].reduce((acc, curRow) => {return acc + (curRow.Asian.toFixed(4) / (GroupByControl['Public'].length).toFixed(4));},0);

    svg2.selectAll("*").remove();
    option = "Control";
    cell.selectAll("circle").style("fill", function(d) { return color_scatter2(d.Control); });

    d3.select("#scatter_legend").selectAll('*').remove();
    var scatter_legend_container = d3.select("#scatter_legend").append("svg").attr("width", 150).attr("height", height);
    var scatter_legend = scatter_legend_container.selectAll('#scatter_legend')
        .data(d3.set(data.map( function(d) { return d.Control } ) ).values())
        .enter().append('g')
        .attr("class", "legend")
        .attr("transform", function (d, i) {return "translate(0," + (i * 20+padding*2) + ")"});
    scatter_legend.append('rect').attr("x", 0).attr("y", 0)
        .attr("width", 10)
        .attr("height", 10)
        .style("fill", function (d, i) {return color_scatter2(i)});

    scatter_legend.append('text').attr("x", 20).attr("y", 10)
          //.attr("dy", ".35em")
        .text(function (d, i) {return d})
        .attr("class", "textselected")
        .style("text-anchor", "start")
        .style("font-size", 15);

    var x2 = d3.scale.linear().range([0, width2-padding]);
    var y2 =d3.scale.ordinal().rangeRoundBands([height2-padding, padding], .1);
    var xAxis2 = d3.svg.axis().scale(x2).orient("bottom");
    var yAxis2 = d3.svg.axis().scale(y2).orient("left");

    var factorsB = [[avgWhiteC, "White"], [avgBlackC, "Black"], [avgHispanicC, "Hispanic"], [avgAsianC, "Asian"]];
    var controls = ["Private", "Public"];
    var layers = d3.layout.stack()(factorsB.map(function(f){
      return controls.map(function(r){
        return {x: [r, f[1]], y: f[0][r]};
      });
    }));
    x2.domain([0,1]).nice();
    y2.domain(layers[0].map(function(d) { return d.x[0]; }));
    var layer = svg2.selectAll(".layers")
      .data(layers)
      .enter().append("g")
      .attr("class", "layer")
      .style("fill", function(d,i){ return color(i); });

    layer.selectAll("rect")
      .data(function(d){ return d; })
      .enter().append("rect")
      .attr("y", function(d) { return y2(d.x[0]); })
      .attr("x", function(d) { return x2(d.y0); })
      .attr("width", function(d) { return x2(d.y); })
      .attr("height", y2.rangeBand())
      .attr("transform", "translate(" + padding*2 + "," + 0 + ")")
      .on("mouseover", function(d){
        div.transition()
                .duration(200)
                .style("opacity", .9);
        div.html("Proportion of " + d.x[1] + " student: " + (d.y*100).toFixed(2) + "%")
                .style("left", (d3.event.pageX) + "px")
                .style("top", (d3.event.pageY - 28) + "px");
      })
      .on("mouseout", function(d) {
            div.transition()
                .duration(500)
                .style("opacity", 0);
      });

    svg2.append("g")
      .attr("class", "x axis")
      .attr("transform", "translate(" + padding*2 + "," + (height2-padding*1.5) + ")")
      .call(xAxis2);

    svg2.append("g")
      .attr("class", "y axis")
      .attr("transform", "translate(" + padding*2 + "," + 0 + ")")
      .call(yAxis2);

    svg2.append("text")
      .attr("class", "label")
      .attr("x", width2-padding*2.5)
      .attr("y", height2)
      .style("text-anchor", "end")
      .style("font-size", "14px")
      .text("X-axis: Race Distribution");
  }

  // Update by Locale ////////////////////////////////////////////////////////////////////////////////////////////
  function UpdateRaceByLocale_noBrush(){
    svg2.selectAll("*").remove();
    option = "Locale";
    cell.selectAll("circle").style("fill", function(d) { return color_scatter(d.Locale); });

    d3.select("#scatter_legend").selectAll('*').remove();
    var scatter_legend_container = d3.select("#scatter_legend").append("svg").attr("width", 150).attr("height", height);
    var scatter_legend = scatter_legend_container.selectAll('#scatter_legend')
        .data(d3.set(data.map( function(d) { return d.Locale } ) ).values())
        .enter().append('g')
        .attr("class", "legend")
        .attr("transform", function (d, i) {return "translate(0," + (i * 20+padding*2) + ")"});
    scatter_legend.append('rect').attr("x", 0).attr("y", 0)
        .attr("width", 10)
        .attr("height", 10)
        .style("fill", function (d, i) {return color_scatter(i)});

    scatter_legend.append('text').attr("x", 20).attr("y", 10)
          //.attr("dy", ".35em")
        .text(function (d, i) {return d})
        .attr("class", "textselected")
        .style("text-anchor", "start")
        .style("font-size", 15);

    var x2 = d3.scale.linear().range([0, width2-padding]);
    var y2 =d3.scale.ordinal().rangeRoundBands([height2-padding*1.5, padding], .1);
    var xAxis2 = d3.svg.axis().scale(x2).orient("bottom");
    var yAxis2 = d3.svg.axis().scale(y2).orient("left");
    var factorsL = [[avgWhiteL, "White"], [avgBlackL, "Black"], [avgHispanicL, "Hispanic"], [avgAsianL, "Asian"]];
    var locales = ['MidC', 'MidS', 'LargeC', 'LargeS', 'SmallC', 'SmallS', 'FringeT', 'RemoteT', 'FringeR', 'RemoteR', 'DistantT', 'DistantR'];

    var layers = d3.layout.stack()(factorsL.map(function(f){
      return locales.map(function(r){
        return {x: [r,f[1]], y: f[0][r]};
      });
    }));
    x2.domain([0,1]).nice();
    y2.domain(layers[0].map(function(d) { return d.x[0]; }));
    var layer = svg2.selectAll(".layers")
      .data(layers)
      .enter().append("g")
      .attr("class", "layer")
      .style("fill", function(d,i){ return color(i); });

    layer.selectAll("rect")
      .data(function(d){ return d; })
      .enter().append("rect")
      .attr("y", function(d) { return y2(d.x[0]); })
      .attr("x", function(d) { return x2(d.y0); })
      .attr("width", function(d) { return x2(d.y); })
      .attr("height", y2.rangeBand())
      .attr("transform", "translate(" + padding*2 + "," + 0 + ")")
      .on("mouseover", function(d){
        div.transition()
                .duration(200)
                .style("opacity", .9);
        div.html("Proportion of " + d.x[1] + " student: " + (d.y*100).toFixed(2) + "%")
                .style("left", (d3.event.pageX) + "px")
                .style("top", (d3.event.pageY - 28) + "px");
      })
      .on("mouseout", function(d) {
            div.transition()
                .duration(500)
                .style("opacity", 0);
      });

    svg2.append("g")
      .attr("class", "x axis")
      .attr("transform", "translate(" + padding*2 + "," + (height2-padding*1.5) + ")")
      .call(xAxis2);

    svg2.append("g")
      .attr("class", "y axis")
      .attr("transform", "translate(" + padding*2+ "," + 0 + ")")
      .call(yAxis2);

    svg2.append("text")
      .attr("class", "label")
      .attr("x", width2-padding*2.5)
      .attr("y", height2)
      //.attr("transform", "translate(0,5)")
      .style("text-anchor", "end")
      .style("font-size", "14px")
      .text("X-axis: Race Distribution");
  }

  // -------------------------------------------------------------------------------------------------------------------
  function UpdateRaceByLocale(){
    if (brush.empty()){
      UpdateRaceByLocale_noBrush();
      return;
    }

    option = "Locale";
    cell.selectAll("circle").style("fill", function(d) { return color_scatter(d.Locale); });

    d3.select("#scatter_legend").selectAll('*').remove();
    var scatter_legend_container = d3.select("#scatter_legend").append("svg").attr("width", 150).attr("height", height);
    var scatter_legend = scatter_legend_container.selectAll('#scatter_legend')
        .data(d3.set(data.map( function(d) { return d.Locale } ) ).values())
        .enter().append('g')
        .attr("class", "legend")
        .attr("transform", function (d, i) {return "translate(0," + (i * 20+padding*2) + ")"});
    scatter_legend.append('rect').attr("x", 0).attr("y", 0)
        .attr("width", 10)
        .attr("height", 10)
        .style("fill", function (d, i) {return color_scatter(i)});

    scatter_legend.append('text').attr("x", 20).attr("y", 10)
          //.attr("dy", ".35em")
        .text(function (d, i) {return d})
        .attr("class", "textselected")
        .style("text-anchor", "start")
        .style("font-size", 15);

    var GroupByLocale = {}
    GroupByLocale['MidC'] = data.filter(function(d,i){return (svg.select('#a' + i)[0][0].className.baseVal != "hidden") && d.Locale == "Mid-size City";});
    GroupByLocale['MidS'] = data.filter(function(d,i){return (svg.select('#a' + i)[0][0].className.baseVal != "hidden") && d.Locale == "Mid-size Suburb";});
    GroupByLocale['LargeC'] = data.filter(function(d,i){return (svg.select('#a' + i)[0][0].className.baseVal != "hidden") && d.Locale == "Large City";});
    GroupByLocale['SmallC'] = data.filter(function(d,i){return (svg.select('#a' + i)[0][0].className.baseVal != "hidden") && d.Locale == "Small City";});
    GroupByLocale['SmallS'] = data.filter(function(d,i){return (svg.select('#a' + i)[0][0].className.baseVal != "hidden") && d.Locale == "Small Suburb";});
    GroupByLocale['LargeS'] = data.filter(function(d,i){return (svg.select('#a' + i)[0][0].className.baseVal != "hidden") && d.Locale == "Large Suburb";});
    GroupByLocale['FringeT'] = data.filter(function(d,i){return (svg.select('#a' + i)[0][0].className.baseVal != "hidden") && d.Locale == "Fringe Town";});
    GroupByLocale['RemoteT'] = data.filter(function(d,i){return (svg.select('#a' + i)[0][0].className.baseVal != "hidden") && d.Locale == "Remote Town";});
    GroupByLocale['FringeR'] = data.filter(function(d,i){return (svg.select('#a' + i)[0][0].className.baseVal != "hidden") && d.Locale == "Fringe Rural";});
    GroupByLocale['RemoteR'] = data.filter(function(d,i){return (svg.select('#a' + i)[0][0].className.baseVal != "hidden") && d.Locale == "Remote Rural";});
    GroupByLocale['DistantT'] = data.filter(function(d,i){return (svg.select('#a' + i)[0][0].className.baseVal != "hidden") && d.Locale == "Distant Town";});
    GroupByLocale['DistantR'] = data.filter(function(d,i){return (svg.select('#a' + i)[0][0].className.baseVal != "hidden") && d.Locale == "Distant Rural";});

    var avgWhiteL = {}
    avgWhiteL['MidC'] = GroupByLocale['MidC'].reduce((acc, curRow) => {return acc + (curRow.White.toFixed(4) / (GroupByLocale['MidC'].length).toFixed(4));},0);
    avgWhiteL['MidS'] = GroupByLocale['MidS'].reduce((acc, curRow) => {return acc + (curRow.White.toFixed(4) / (GroupByLocale['MidS'].length).toFixed(4));},0);
    avgWhiteL['LargeC'] = GroupByLocale['LargeC'].reduce((acc, curRow) => {return acc + (curRow.White.toFixed(4) / (GroupByLocale['LargeC'].length).toFixed(4));},0);
    avgWhiteL['SmallC'] = GroupByLocale['SmallC'].reduce((acc, curRow) => {return acc + (curRow.White.toFixed(4) / (GroupByLocale['SmallC'].length).toFixed(4));},0);
    avgWhiteL['LargeS'] = GroupByLocale['LargeS'].reduce((acc, curRow) => {return acc + (curRow.White.toFixed(4) / (GroupByLocale['LargeS'].length).toFixed(4));},0);
    avgWhiteL['SmallS'] = GroupByLocale['SmallS'].reduce((acc, curRow) => {return acc + (curRow.White.toFixed(4) / (GroupByLocale['SmallS'].length).toFixed(4));},0);
    avgWhiteL['FringeT'] = GroupByLocale['FringeT'].reduce((acc, curRow) => {return acc + (curRow.White.toFixed(4) / (GroupByLocale['FringeT'].length).toFixed(4));},0);
    avgWhiteL['RemoteT'] = GroupByLocale['RemoteT'].reduce((acc, curRow) => {return acc + (curRow.White.toFixed(4) / (GroupByLocale['RemoteT'].length).toFixed(4));},0);
    avgWhiteL['FringeR'] = GroupByLocale['FringeR'].reduce((acc, curRow) => {return acc + (curRow.White.toFixed(4) / (GroupByLocale['FringeR'].length).toFixed(4));},0);
    avgWhiteL['RemoteR'] = GroupByLocale['RemoteR'].reduce((acc, curRow) => {return acc + (curRow.White.toFixed(4) / (GroupByLocale['RemoteR'].length).toFixed(4));},0);
    avgWhiteL['DistantT'] = GroupByLocale['DistantT'].reduce((acc, curRow) => {return acc + (curRow.White.toFixed(4) / (GroupByLocale['DistantT'].length).toFixed(4));},0);
    avgWhiteL['DistantR'] = GroupByLocale['DistantR'].reduce((acc, curRow) => {return acc + (curRow.White.toFixed(4) / (GroupByLocale['DistantR'].length).toFixed(4));},0);
    var avgBlackL = {};
    avgBlackL['MidC'] = GroupByLocale['MidC'].reduce((acc, curRow) => {return acc + (curRow.Black.toFixed(4) / (GroupByLocale['MidC'].length).toFixed(4));},0);
    avgBlackL['MidS'] = GroupByLocale['MidS'].reduce((acc, curRow) => {return acc + (curRow.Black.toFixed(4) / (GroupByLocale['MidS'].length).toFixed(4));},0);
    avgBlackL['LargeC'] = GroupByLocale['LargeC'].reduce((acc, curRow) => {return acc + (curRow.Black.toFixed(4) / (GroupByLocale['LargeC'].length).toFixed(4));},0);
    avgBlackL['SmallC'] = GroupByLocale['SmallC'].reduce((acc, curRow) => {return acc + (curRow.Black.toFixed(4) / (GroupByLocale['SmallC'].length).toFixed(4));},0);
    avgBlackL['LargeS'] = GroupByLocale['LargeS'].reduce((acc, curRow) => {return acc + (curRow.Black.toFixed(4) / (GroupByLocale['LargeS'].length).toFixed(4));},0);
    avgBlackL['SmallS'] = GroupByLocale['SmallS'].reduce((acc, curRow) => {return acc + (curRow.Black.toFixed(4) / (GroupByLocale['SmallS'].length).toFixed(4));},0);
    avgBlackL['FringeT'] = GroupByLocale['FringeT'].reduce((acc, curRow) => {return acc + (curRow.Black.toFixed(4) / (GroupByLocale['FringeT'].length).toFixed(4));},0);
    avgBlackL['RemoteT'] = GroupByLocale['RemoteT'].reduce((acc, curRow) => {return acc + (curRow.Black.toFixed(4) / (GroupByLocale['RemoteT'].length).toFixed(4));},0);
    avgBlackL['FringeR'] = GroupByLocale['FringeR'].reduce((acc, curRow) => {return acc + (curRow.Black.toFixed(4) / (GroupByLocale['FringeR'].length).toFixed(4));},0);
    avgBlackL['RemoteR'] = GroupByLocale['RemoteR'].reduce((acc, curRow) => {return acc + (curRow.Black.toFixed(4) / (GroupByLocale['RemoteR'].length).toFixed(4));},0);
    avgBlackL['DistantT'] = GroupByLocale['DistantT'].reduce((acc, curRow) => {return acc + (curRow.Black.toFixed(4) / (GroupByLocale['DistantT'].length).toFixed(4));},0);
    avgBlackL['DistantR'] = GroupByLocale['DistantR'].reduce((acc, curRow) => {return acc + (curRow.Black.toFixed(4) / (GroupByLocale['DistantR'].length).toFixed(4));},0);
    var avgHispanicL = {};
    avgHispanicL['MidC'] = GroupByLocale['MidC'].reduce((acc, curRow) => {return acc + (curRow.Hispanic.toFixed(4) / (GroupByLocale['MidC'].length).toFixed(4));},0);
    avgHispanicL['MidS'] = GroupByLocale['MidS'].reduce((acc, curRow) => {return acc + (curRow.Hispanic.toFixed(4) / (GroupByLocale['MidS'].length).toFixed(4));},0);
    avgHispanicL['LargeC'] = GroupByLocale['LargeC'].reduce((acc, curRow) => {return acc + (curRow.Hispanic.toFixed(4) / (GroupByLocale['LargeC'].length).toFixed(4));},0);
    avgHispanicL['SmallC'] = GroupByLocale['SmallC'].reduce((acc, curRow) => {return acc + (curRow.Hispanic.toFixed(4) / (GroupByLocale['SmallC'].length).toFixed(4));},0);
    avgHispanicL['LargeS'] = GroupByLocale['LargeS'].reduce((acc, curRow) => {return acc + (curRow.Hispanic.toFixed(4) / (GroupByLocale['LargeS'].length).toFixed(4));},0);
    avgHispanicL['SmallS'] = GroupByLocale['SmallS'].reduce((acc, curRow) => {return acc + (curRow.Hispanic.toFixed(4) / (GroupByLocale['SmallS'].length).toFixed(4));},0);
    avgHispanicL['FringeT'] = GroupByLocale['FringeT'].reduce((acc, curRow) => {return acc + (curRow.Hispanic.toFixed(4) / (GroupByLocale['FringeT'].length).toFixed(4));},0);
    avgHispanicL['RemoteT'] = GroupByLocale['RemoteT'].reduce((acc, curRow) => {return acc + (curRow.Hispanic.toFixed(4) / (GroupByLocale['RemoteT'].length).toFixed(4));},0);
    avgHispanicL['FringeR'] = GroupByLocale['FringeR'].reduce((acc, curRow) => {return acc + (curRow.Hispanic.toFixed(4) / (GroupByLocale['FringeR'].length).toFixed(4));},0);
    avgHispanicL['RemoteR'] = GroupByLocale['RemoteR'].reduce((acc, curRow) => {return acc + (curRow.Hispanic.toFixed(4) / (GroupByLocale['RemoteR'].length).toFixed(4));},0);
    avgHispanicL['DistantT'] = GroupByLocale['DistantT'].reduce((acc, curRow) => {return acc + (curRow.Hispanic.toFixed(4) / (GroupByLocale['DistantT'].length).toFixed(4));},0);
    avgHispanicL['DistantR'] = GroupByLocale['DistantR'].reduce((acc, curRow) => {return acc + (curRow.Hispanic.toFixed(4) / (GroupByLocale['DistantR'].length).toFixed(4));},0);
    var avgAsianL = {};
    avgAsianL['MidC'] = GroupByLocale['MidC'].reduce((acc, curRow) => {return acc + (curRow.Asian.toFixed(4) / (GroupByLocale['MidC'].length).toFixed(4));},0);
    avgAsianL['MidS'] = GroupByLocale['MidS'].reduce((acc, curRow) => {return acc + (curRow.Asian.toFixed(4) / (GroupByLocale['MidS'].length).toFixed(4));},0);
    avgAsianL['LargeC'] = GroupByLocale['LargeC'].reduce((acc, curRow) => {return acc + (curRow.Asian.toFixed(4) / (GroupByLocale['LargeC'].length).toFixed(4));},0);
    avgAsianL['SmallC'] = GroupByLocale['SmallC'].reduce((acc, curRow) => {return acc + (curRow.Asian.toFixed(4) / (GroupByLocale['SmallC'].length).toFixed(4));},0);
    avgAsianL['LargeS'] = GroupByLocale['LargeS'].reduce((acc, curRow) => {return acc + (curRow.Asian.toFixed(4) / (GroupByLocale['LargeS'].length).toFixed(4));},0);
    avgAsianL['SmallS'] = GroupByLocale['SmallS'].reduce((acc, curRow) => {return acc + (curRow.Asian.toFixed(4) / (GroupByLocale['SmallS'].length).toFixed(4));},0);
    avgAsianL['FringeT'] = GroupByLocale['FringeT'].reduce((acc, curRow) => {return acc + (curRow.Asian.toFixed(4) / (GroupByLocale['FringeT'].length).toFixed(4));},0);
    avgAsianL['RemoteT'] = GroupByLocale['RemoteT'].reduce((acc, curRow) => {return acc + (curRow.Asian.toFixed(4) / (GroupByLocale['RemoteT'].length).toFixed(4));},0);
    avgAsianL['FringeR'] = GroupByLocale['FringeR'].reduce((acc, curRow) => {return acc + (curRow.Asian.toFixed(4) / (GroupByLocale['FringeR'].length).toFixed(4));},0);
    avgAsianL['RemoteR'] = GroupByLocale['RemoteR'].reduce((acc, curRow) => {return acc + (curRow.Asian.toFixed(4) / (GroupByLocale['RemoteR'].length).toFixed(4));},0);
    avgAsianL['DistantT'] = GroupByLocale['DistantT'].reduce((acc, curRow) => {return acc + (curRow.Asian.toFixed(4) / (GroupByLocale['DistantT'].length).toFixed(4));},0);
    avgAsianL['DistantR'] = GroupByLocale['DistantR'].reduce((acc, curRow) => {return acc + (curRow.Asian.toFixed(4) / (GroupByLocale['DistantR'].length).toFixed(4));},0);

    svg2.selectAll("*").remove();
    var x2 = d3.scale.linear().range([0, width2-padding]);
    var y2 =d3.scale.ordinal().rangeRoundBands([height2-padding*1.5, padding], .1);
    var xAxis2 = d3.svg.axis().scale(x2).orient("bottom");
    var yAxis2 = d3.svg.axis().scale(y2).orient("left");

    var factorsL = [[avgWhiteL, "White"], [avgBlackL, "Black"], [avgHispanicL, "Hispanic"], [avgAsianL, "Asian"]];
    var locales = ['MidC', 'MidS', 'LargeC', 'LargeS', 'SmallC', 'SmallS', 'FringeT', 'RemoteT', 'FringeR', 'RemoteR', 'DistantT', 'DistantR'];

    var layers = d3.layout.stack()(factorsL.map(function(f){
      return locales.map(function(r){
        return {x:[r,f[1]], y: f[0][r]};
      });
    }));
    x2.domain([0,1]).nice();
    y2.domain(layers[0].map(function(d) { return d.x[0]; }));
    var layer = svg2.selectAll(".layers")
      .data(layers)
      .enter().append("g")
      .attr("class", "layer")
      .style("fill", function(d,i){ return color(i); });

    layer.selectAll("rect")
      .data(function(d){ return d; })
      .enter().append("rect")
      .attr("y", function(d) { return y2(d.x[0]); })
      .attr("x", function(d) { return x2(d.y0); })
      .attr("width", function(d) { return x2(d.y); })
      .attr("height", y2.rangeBand())
      .attr("transform", "translate(" + padding*2 + "," + 0 + ")")
      .on("mouseover", function(d){
        div.transition()
                .duration(200)
                .style("opacity", .9);
        div.html("Proportion of " + d.x[1] + " student: " + (d.y*100).toFixed(2) + "%")
                .style("left", (d3.event.pageX) + "px")
                .style("top", (d3.event.pageY - 28) + "px");
      })
      .on("mouseout", function(d) {
            div.transition()
                .duration(500)
                .style("opacity", 0);
      });

    svg2.append("g")
      .attr("class", "x axis")
      .attr("transform", "translate(" + padding*2 + "," + (height2-padding*1.5) + ")")
      .call(xAxis2);

    svg2.append("g")
      .attr("class", "y axis")
      .attr("transform", "translate(" + padding*2+ "," + 0 + ")")
      .call(yAxis2);

    svg2.append("text")
      .attr("class", "label")
      .attr("x", width2-padding*2.5)
      .attr("y", height2)
      .style("text-anchor", "end")
      .style("font-size", "14px")
      .text("X-axis: Race Distribution");
  }

  // Update by Region ////////////////////////////////////////////////////////////////////////////////////////////
  function UpdateRaceByRegion_noBrush(){
    svg2.selectAll("*").remove();
    option = "Region";
    cell.selectAll("circle").style("fill", function(d) { return color_scatter1(d.Region); });

    d3.select("#scatter_legend").selectAll('*').remove();
    var scatter_legend_container = d3.select("#scatter_legend").append("svg").attr("width", 150).attr("height", height);
    var scatter_legend = scatter_legend_container.selectAll('#scatter_legend')
        .data(d3.set(data.map( function(d) { return d.Region } ) ).values())
        .enter().append('g')
        .attr("class", "legend")
        .attr("transform", function (d, i) {return "translate(0," + (i * 20+padding*2) + ")"});
    scatter_legend.append('rect').attr("x", 0).attr("y", 0)
        .attr("width", 10)
        .attr("height", 10)
        .style("fill", function (d, i) {return color_scatter1(i)});

    scatter_legend.append('text').attr("x", 20).attr("y", 10)
          //.attr("dy", ".35em")
        .text(function (d, i) {return d})
        .attr("class", "textselected")
        .style("text-anchor", "start")
        .style("font-size", 15);

    var x2 = d3.scale.linear().range([0, width2-padding]);
    var y2 =d3.scale.ordinal().rangeRoundBands([height2-padding*1.5, padding], .1);
    var xAxis2 = d3.svg.axis().scale(x2).orient("bottom");
    var yAxis2 = d3.svg.axis().scale(y2).orient("left");

    var factorsR = [[avgWhiteR, "White"], [avgBlackR, "Black"], [avgHispanicR, "Hispanic"], [avgAsianR, "Asian"]];
    var regions = ["Lakes", "Rocky", "Plains", "England", "FarWest", "Outlying", "Atlantic", "Southeast", "Southwest"];
    var layers = d3.layout.stack()(factorsR.map(function(f){
      return regions.map(function(r){
        return {x: [r,f[1]], y: f[0][r]};
      });
    }));
    x2.domain([0,1]).nice();
    y2.domain(layers[0].map(function(d) { return d.x[0]; }));
    var layer = svg2.selectAll(".layers")
      .data(layers)
      .enter().append("g")
      .attr("class", "layer")
      .style("fill", function(d,i){ return color(i); });

    layer.selectAll("rect")
      .data(function(d){ return d; })
      .enter().append("rect")
      .attr("y", function(d) { return y2(d.x[0]); })
      .attr("x", function(d) { return x2(d.y0); })
      .attr("width", function(d) { return x2(d.y); })
      .attr("height", y2.rangeBand())
      .attr("transform", "translate(" + padding*2 + "," + 0 + ")")
      .on("mouseover", function(d){
        div.transition()
                .duration(200)
                .style("opacity", .9);
        div.html("Proportion of " + d.x[1] + " student: " + (d.y*100).toFixed(2) + "%")
                .style("left", (d3.event.pageX) + "px")
                .style("top", (d3.event.pageY - 28) + "px");
      })
      .on("mouseout", function(d) {
            div.transition()
                .duration(500)
                .style("opacity", 0);
      });

    svg2.append("g")
      .attr("class", "x axis")
      .attr("transform", "translate(" + padding*2 + "," + (height2-padding*1.5) + ")")
      .call(xAxis2);

    svg2.append("g")
      .attr("class", "y axis")
      .attr("transform", "translate(" + padding*2+ "," + 0 + ")")
      .call(yAxis2);

    svg2.append("text")
      .attr("class", "label")
      .attr("x", width2-padding*2.5)
      .attr("y", height2)
      .style("text-anchor", "end")
      .style("font-size", "14px")
      .text("X-axis: Race Distribution");
  }

  // -------------------------------------------------------------------------------------------------------------
  function UpdateRaceByRegion(){
    if (brush.empty()){
      UpdateRaceByRegion_noBrush();
      return;
    }
    var GroupByRegion = {}
    GroupByRegion["Lakes"] = data.filter(function(d,i){return (svg.select('#a' + i)[0][0].className.baseVal != "hidden") && d.Region == 'Great Lakes';});
    GroupByRegion["Rocky"] = data.filter(function(d,i){return (svg.select('#a' + i)[0][0].className.baseVal != "hidden") && d.Region == 'Rocky Mountains';});
    GroupByRegion["Plains"] = data.filter(function(d,i){return (svg.select('#a' + i)[0][0].className.baseVal != "hidden") && d.Region == 'Great Plains';});
    GroupByRegion["England"] = data.filter(function(d,i){return (svg.select('#a' + i)[0][0].className.baseVal != "hidden") && d.Region == 'New England';});
    GroupByRegion["FarWest"] = data.filter(function(d,i){return (svg.select('#a' + i)[0][0].className.baseVal != "hidden") && d.Region == 'Far West';});
    GroupByRegion["Outlying"] = data.filter(function(d,i){return (svg.select('#a' + i)[0][0].className.baseVal != "hidden") && d.Region == 'Outlying Areas';});
    GroupByRegion["Atlantic"] = data.filter(function(d,i){return (svg.select('#a' + i)[0][0].className.baseVal != "hidden") && d.Region == 'Mid-Atlantic';});
    GroupByRegion["Southeast"] = data.filter(function(d,i){return (svg.select('#a' + i)[0][0].className.baseVal != "hidden") && d.Region == 'Southeast';});
    GroupByRegion["Southwest"] = data.filter(function(d,i){return (svg.select('#a' + i)[0][0].className.baseVal != "hidden") && d.Region == 'Southwest';});
    var avgWhiteR = {}
    avgWhiteR["Lakes"] = GroupByRegion["Lakes"].reduce((acc, curRow) => {return acc + (curRow.White.toFixed(4) / (GroupByRegion["Lakes"].length).toFixed(4)); },0);
    avgWhiteR["Rocky"] = GroupByRegion["Rocky"].reduce((acc, curRow) => {return acc + (curRow.White.toFixed(4) / (GroupByRegion["Rocky"].length).toFixed(4)); },0);
    avgWhiteR["Plains"] = GroupByRegion["Plains"].reduce((acc, curRow) => {return acc + (curRow.White.toFixed(4) / (GroupByRegion["Plains"].length).toFixed(4)); },0);
    avgWhiteR["England"] = GroupByRegion["England"].reduce((acc, curRow) => {return acc + (curRow.White.toFixed(4) / (GroupByRegion["England"].length).toFixed(4)); },0);
    avgWhiteR["FarWest"] = GroupByRegion["FarWest"].reduce((acc, curRow) => {return acc + (curRow.White.toFixed(4) / (GroupByRegion["FarWest"].length).toFixed(4)); },0);
    avgWhiteR["Outlying"] = GroupByRegion["Outlying"].reduce((acc, curRow) => {return acc + (curRow.White.toFixed(4) / (GroupByRegion["Outlying"].length).toFixed(4)); },0);
    avgWhiteR["Atlantic"] = GroupByRegion["Atlantic"].reduce((acc, curRow) => {return acc + (curRow.White.toFixed(4) / (GroupByRegion["Atlantic"].length).toFixed(4)); },0);
    avgWhiteR["Southeast"] = GroupByRegion["Southeast"].reduce((acc, curRow) => {return acc + (curRow.White.toFixed(4) / (GroupByRegion["Southeast"].length).toFixed(4)); },0);
    avgWhiteR["Southwest"] = GroupByRegion["Southwest"].reduce((acc, curRow) => {return acc + (curRow.White.toFixed(4) / (GroupByRegion["Southwest"].length).toFixed(4)); },0);

    var avgBlackR = {}
    avgBlackR["Lakes"] = GroupByRegion["Lakes"].reduce((acc, curRow) => {return acc + (curRow.Black.toFixed(4) / (GroupByRegion["Lakes"].length).toFixed(4)); },0);
    avgBlackR["Rocky"] = GroupByRegion["Rocky"].reduce((acc, curRow) => {return acc + (curRow.Black.toFixed(4) / (GroupByRegion["Rocky"].length).toFixed(4)); },0);
    avgBlackR["Plains"] = GroupByRegion["Plains"].reduce((acc, curRow) => {return acc + (curRow.Black.toFixed(4) / (GroupByRegion["Plains"].length).toFixed(4)); },0);
    avgBlackR["England"] = GroupByRegion["England"].reduce((acc, curRow) => {return acc + (curRow.Black.toFixed(4) / (GroupByRegion["England"].length).toFixed(4)); },0);
    avgBlackR["FarWest"] = GroupByRegion["FarWest"].reduce((acc, curRow) => {return acc + (curRow.Black.toFixed(4) / (GroupByRegion["FarWest"].length).toFixed(4)); },0);
    avgBlackR["Outlying"] = GroupByRegion["Outlying"].reduce((acc, curRow) => {return acc + (curRow.Black.toFixed(4) / (GroupByRegion["Outlying"].length).toFixed(4)); },0);
    avgBlackR["Atlantic"] = GroupByRegion["Atlantic"].reduce((acc, curRow) => {return acc + (curRow.Black.toFixed(4) / (GroupByRegion["Atlantic"].length).toFixed(4)); },0);
    avgBlackR["Southeast"] = GroupByRegion["Southeast"].reduce((acc, curRow) => {return acc + (curRow.Black.toFixed(4) / (GroupByRegion["Southeast"].length).toFixed(4)); },0);
    avgBlackR["Southwest"] = GroupByRegion["Southwest"].reduce((acc, curRow) => {return acc + (curRow.Black.toFixed(4) / (GroupByRegion["Southwest"].length).toFixed(4)); },0);

    var avgHispanicR = {}
    avgHispanicR["Lakes"] = GroupByRegion["Lakes"].reduce((acc, curRow) => {return acc + (curRow.Hispanic.toFixed(4) / (GroupByRegion["Lakes"].length).toFixed(4)); },0);
    avgHispanicR["Rocky"] = GroupByRegion["Rocky"].reduce((acc, curRow) => {return acc + (curRow.Hispanic.toFixed(4) / (GroupByRegion["Rocky"].length).toFixed(4)); },0);
    avgHispanicR["Plains"] = GroupByRegion["Plains"].reduce((acc, curRow) => {return acc + (curRow.Hispanic.toFixed(4) / (GroupByRegion["Plains"].length).toFixed(4)); },0);
    avgHispanicR["England"] = GroupByRegion["England"].reduce((acc, curRow) => {return acc + (curRow.Hispanic.toFixed(4) / (GroupByRegion["England"].length).toFixed(4)); },0);
    avgHispanicR["FarWest"] = GroupByRegion["FarWest"].reduce((acc, curRow) => {return acc + (curRow.Hispanic.toFixed(4) / (GroupByRegion["FarWest"].length).toFixed(4)); },0);
    avgHispanicR["Outlying"] = GroupByRegion["Outlying"].reduce((acc, curRow) => {return acc + (curRow.Hispanic.toFixed(4) / (GroupByRegion["Outlying"].length).toFixed(4)); },0);
    avgHispanicR["Atlantic"] = GroupByRegion["Atlantic"].reduce((acc, curRow) => {return acc + (curRow.Hispanic.toFixed(4) / (GroupByRegion["Atlantic"].length).toFixed(4)); },0);
    avgHispanicR["Southeast"] = GroupByRegion["Southeast"].reduce((acc, curRow) => {return acc + (curRow.Hispanic.toFixed(4) / (GroupByRegion["Southeast"].length).toFixed(4)); },0);
    avgHispanicR["Southwest"] = GroupByRegion["Southwest"].reduce((acc, curRow) => {return acc + (curRow.Hispanic.toFixed(4) / (GroupByRegion["Southwest"].length).toFixed(4)); },0);

    var avgAsianR = {}
    avgAsianR["Lakes"] = GroupByRegion["Lakes"].reduce((acc, curRow) => {return acc + (curRow.Asian.toFixed(4) / (GroupByRegion["Lakes"].length).toFixed(4)); },0);
    avgAsianR["Rocky"] = GroupByRegion["Rocky"].reduce((acc, curRow) => {return acc + (curRow.Asian.toFixed(4) / (GroupByRegion["Rocky"].length).toFixed(4)); },0);
    avgAsianR["Plains"] = GroupByRegion["Plains"].reduce((acc, curRow) => {return acc + (curRow.Asian.toFixed(4) / (GroupByRegion["Plains"].length).toFixed(4)); },0);
    avgAsianR["England"] = GroupByRegion["England"].reduce((acc, curRow) => {return acc + (curRow.Asian.toFixed(4) / (GroupByRegion["England"].length).toFixed(4)); },0);
    avgAsianR["FarWest"] = GroupByRegion["FarWest"].reduce((acc, curRow) => {return acc + (curRow.Asian.toFixed(4) / (GroupByRegion["FarWest"].length).toFixed(4)); },0);
    avgAsianR["Outlying"] = GroupByRegion["Outlying"].reduce((acc, curRow) => {return acc + (curRow.Asian.toFixed(4) / (GroupByRegion["Outlying"].length).toFixed(4)); },0);
    avgAsianR["Atlantic"] = GroupByRegion["Atlantic"].reduce((acc, curRow) => {return acc + (curRow.Asian.toFixed(4) / (GroupByRegion["Atlantic"].length).toFixed(4)); },0);
    avgAsianR["Southeast"] = GroupByRegion["Southeast"].reduce((acc, curRow) => {return acc + (curRow.Asian.toFixed(4) / (GroupByRegion["Southeast"].length).toFixed(4)); },0);
    avgAsianR["Southwest"] = GroupByRegion["Southwest"].reduce((acc, curRow) => {return acc + (curRow.Asian.toFixed(4) / (GroupByRegion["Southwest"].length).toFixed(4)); },0);

    svg2.selectAll("*").remove();
    option = "Region";
    cell.selectAll("circle").style("fill", function(d) { return color_scatter1(d.Region); });

    d3.select("#scatter_legend").selectAll('*').remove();
    var scatter_legend_container = d3.select("#scatter_legend").append("svg").attr("width", 150).attr("height", height);
    var scatter_legend = scatter_legend_container.selectAll('#scatter_legend')
        .data(d3.set(data.map( function(d) { return d.Region } ) ).values())
        .enter().append('g')
        .attr("class", "legend")
        .attr("transform", function (d, i) {return "translate(0," + (i * 20+padding*2) + ")"});
    scatter_legend.append('rect').attr("x", 0).attr("y", 0)
        .attr("width", 10)
        .attr("height", 10)
        .style("fill", function (d, i) {return color_scatter1(i)});

    scatter_legend.append('text').attr("x", 20).attr("y", 10)
          //.attr("dy", ".35em")
        .text(function (d, i) {return d})
        .attr("class", "textselected")
        .style("text-anchor", "start")
        .style("font-size", 15);

    var x2 = d3.scale.linear().range([0, width2-padding]);
    var y2 =d3.scale.ordinal().rangeRoundBands([height2-padding*1.5, padding], .1);
    var xAxis2 = d3.svg.axis().scale(x2).orient("bottom");
    var yAxis2 = d3.svg.axis().scale(y2).orient("left");

    var factorsR = [[avgWhiteR, "White"], [avgBlackR, "Black"], [avgHispanicR, "Hispanic"], [avgAsianR, "Asian"]];
    var regions = ["Lakes", "Rocky", "Plains", "England", "FarWest", "Outlying", "Atlantic", "Southeast", "Southwest"];
    var layers = d3.layout.stack()(factorsR.map(function(f){
        return regions.map(function(r){
        return {x: [r,f[1]], y: f[0][r]};
      });
    }));
    x2.domain([0,1]).nice();
    y2.domain(layers[0].map(function(d) { return d.x[0]; }));
    var layer = svg2.selectAll(".layers")
      .data(layers)
      .enter().append("g")
      .attr("class", "layer")
      .style("fill", function(d,i){ return color(i); });

    layer.selectAll("rect")
      .data(function(d){ return d; })
      .enter().append("rect")
      .attr("y", function(d) { return y2(d.x[0]); })
      .attr("x", function(d) { return x2(d.y0); })
      .attr("width", function(d) { return x2(d.y); })
      .attr("height", y2.rangeBand())
      .attr("transform", "translate(" + padding*2 + "," + 0 + ")")
      .on("mouseover", function(d){
        div.transition()
            .duration(200)
            .style("opacity", .9);
        div.html("Proportion of " + d.x[1] + " student: " + (d.y*100).toFixed(2) + "%")
            .style("left", (d3.event.pageX) + "px")
            .style("top", (d3.event.pageY - 28) + "px");
      })
      .on("mouseout", function(d) {
        div.transition()
            .duration(500)
            .style("opacity", 0);
      });

    svg2.append("g")
      .attr("class", "x axis")
      .attr("transform", "translate(" + padding*2 + "," + (height2-padding*1.5) + ")")
      .call(xAxis2);

    svg2.append("g")
      .attr("class", "y axis")
      .attr("transform", "translate(" + padding*2+ "," + 0 + ")")
      .call(yAxis2);

    svg2.append("text")
      .attr("class", "label")
      .attr("x", width2-padding*2.5)
      .attr("y", height2)
      .style("text-anchor", "end")
      .style("font-size", "14px")
      .text("X-axis: Race Distribution");
  }
});

function cross(a, b) {
  var c = [], n = a.length, m = b.length, i, j;
  for (i = -1; ++i < n;) for (j = -1; ++j < m;) c.push({x: a[i], i: i, y: b[j], j: j});
  return c;
}

<file_sep># GT-CS4460-Information-Visualization
 Course I took during my exchange period in Georiga Tech, 2019 Spring
 Course Website: http://va.gatech.edu/courses/cs4460/
 The programming projects were written in html, svg, javascript and d3.
<file_sep>// **** Your JavaScript code goes here ****
//NOTE: this is the D3 v4 loading syntax. For more details, see https://piazza.com/class/jnzgy0ktwi34lk?cid=75.
d3.csv("./data/coffee_data.csv", function(error, data){
	if (error) throw error;
	var df = []
	for (var i=0; i<data.length; i++){
		df.push({"sales": parseInt(data[i].sales), "region": data[i].region, "category": data[i].category});
	}
	console.log(df[0]);
	var R = d3.nest().key(function(d) {return d.region;}).rollup(function(v) {return d3.sum(v,function(d) {return d.sales;});}).entries(df);
	console.log(R);
	var keys = []
	var values = []
	for (var i=0; i<R.length; i++){
		keys.push(R[i].key);
		values.push(R[i].value);
	}

	var width = 760;
	var height = 600;
	var svg = d3.select("body").append('svg').attr('width', width).attr('height', height).attr('style',"border: 1px solid #777;");
	var padding = {top: 100, right: 30, bottom: 100, left: 70};

	var xAxisWidth = 600;
	var yAxisWidth = 400;
	var xScale = d3.scaleOrdinal().domain(["Central","East","South","West"]).range([0,70, 140, 210]);
	//var xScale = d3.scaleOrdinal().domain(["Central","East","South","West"]).range([0,120,240,360]);
	var yScale = d3.scaleLinear().domain([0,d3.max(values)]).range([400,0]);
	var colors = d3.scaleOrdinal().range(["#336699", "darkorange", "#009900", "#cc0000"]);
	svg.append("g").selectAll("rect")
					.data(values)
					.enter()
					.append("rect")
					.attr("fill",function(d,i){
						return colors(i);
					})
					.attr("x",function(d,i){
						// return padding.left + i * rectStep;
						return padding.left + 30 + xScale(i);

					})
					.attr("y",function(d,i){
						// return height - padding.bottom - d;
						return padding.top + yScale(d);
					})
					.attr("width",40)
					.attr("height",function(d){
						return 400 - yScale(d);
					})

	//var xAxis = d3.axisBottom().scale(xScale);
	//var yAxis = d3.axisLeft().scale(yScale);
    var customTickFormat = function (d){
		console.log("format" + d);
		console.log(parseInt(d)/1000);
		return (parseInt(d)/1000).toString() + "k";}

	svg.append("g")
	  .attr("class","axis")
	  .attr("transform","translate(" + (padding.left+47.5) + "," + (height - padding.bottom+10) + ")")
	  .call(d3.axisBottom(xScale).tickFormat(function(d) {return xScale.domain()[d];}))
	  .call(g => g.select(".domain").remove());

	svg.append("g")
	  .attr("class","axis")
	  .attr("transform","translate(" + padding.left + "," + (height - padding.bottom - yAxisWidth) + ")")
	  .call(d3.axisLeft(yScale).ticks(5).tickFormat(customTickFormat));

	svg.append("text")
		.attr("class", "label")
		.attr("transform", "translate(100,60)")
		.attr("font-weight", "bold")
		.text("Coffee Sales by Region (USD)");

	svg.append("text")
		.attr("class", "label")
		.attr("font-size", "12")
		.attr("font-weight", "bold")
		.attr("transform", "translate(20,350) rotate(270)")
		.text("Coffee Sales (USD)");

	svg.append("text")
		.attr("class", "label")
		.attr("font-size", "12")
		.attr("font-weight", "bold")
		.attr("transform", "translate(190,550)")
		.text("Region");

	var C = d3.nest().key(function(d) {return d.category;}).rollup(function(v) {return d3.sum(v,function(d) {return d.sales;});}).entries(df);
	var ckeys = []
	var cvalues = []
	for (var i=0; i<C.length; i++){
		ckeys.push(C[i].key);
		cvalues.push(C[i].value);
	}

	var cpadding = {top: 100, right: 30, bottom: 100, left: 450};
	var cxScale = d3.scaleOrdinal().domain(ckeys).range([0,70,140,210]);
	//var xScale = d3.scaleOrdinal().domain(["Central","East","South","West"]).range([0,120,240,360]);
	var cyScale = d3.scaleLinear().domain([0,d3.max(values)]).range([400,0]);
	var ccolors = d3.scaleOrdinal().range(["#663300", "firebrick", "#cc6600", "darkkhaki"]);

	svg.append("g")
		.selectAll("rect")
		.data(cvalues)
		.enter()
		.append("rect")
		.attr("fill",function(d,i){
			return ccolors(i);
		})
		.attr("x",function(d,i){
			// return padding.left + i * rectStep;
			return cpadding.left + 30 + cxScale(i);

		})
		.attr("y",function(d,i){
			// return height - padding.bottom - d;
			return cpadding.top + cyScale(d);
		})
		.attr("width",40)
		.attr("height",function(d){
			return 400 - cyScale(d);
		})

	svg.append("g")
	  .attr("class","x axis")
	  .attr("transform","translate(" + (cpadding.left+47.5) + "," + (height - cpadding.bottom +10) + ")")
	  .call(d3.axisBottom(cxScale).tickFormat(function(d){return cxScale.domain()[d];}))
	  .call(g => g.select(".domain").remove());

	svg.append("g")
	  .attr("class","axis")
	  .attr("transform","translate(" + cpadding.left + "," + (height - cpadding.bottom - yAxisWidth) + ")")
	  .call(d3.axisLeft(cyScale).ticks(5).tickFormat(customTickFormat));

	svg.append("text")
	  .attr("class", "label")
	  .attr("transform", "translate(480,60)")
	  .attr("font-weight", "bold")
	  .text("Coffee Sales by Product (USD)");

	svg.append("text")
	  .attr("class", "label")
	  .attr("transform", "translate(400,350) rotate(270)")
	  .attr("font-size", "12")
	  .attr("font-weight", "bold")
	  .text("Coffee Sales (USD)");

    svg.append("text")
	  .attr("class", "label")
	  .attr("transform", "translate(570,550)")
	  .attr("font-size", "12")
	  .attr("font-weight", "bold")
	  .text("Product");
})

languages: Markdown JavaScript

repo_language: Markdown


text: <file_sep># technomart.githab.io