In [1]:
import pandas as pd
import matplotlib.pyplot as plt
import ipywidgets
from IPython.display import display
from collections import OrderedDict
%matplotlib inline
pd.options.mode.chained_assignment = None # default='warn'
In [2]:
dfMaster = pd.read_csv('../data/dayByDayStandings2015.csv')
dfMaster.fillna(0, inplace=True)
dfMaster['date'] = pd.to_datetime(dfMaster['date'])
dfMaster['date'] = dfMaster['date'].apply(pd.datetools.normalize_date)
dfMaster.set_index(['division', 'date'], inplace=True)
dfMaster = dfMaster[['Tm', 'W', 'L', 'GB', 'RS', 'RA', 'W-L%', 'pythW-L%']]
In [3]:
dropList = OrderedDict(zip(dfMaster.index.levels[0].values, dfMaster.index.levels[0].values))
In [4]:
mlb_colors = {'HOU': '#072854', 'CIN': '#C6011F', 'NYM': '#FB4F14', 'PHI': '#BA0C2F', 'LAD': '#083C6B',
'LAA': '#B71234', 'COL': '#333366', 'TOR': '#003DA5', 'WSN': '#BA122B', 'BAL': '#ED4C09',
'STL': '#C41E3A', 'SDP': '#002147', 'ARI': '#A71930', 'MIL': '#92754C', 'MIN': '#C6011F',
'MIA': '#F9423A', 'BOS': '#C60C30', 'OAK': '#003831', 'PIT': '#FDB829', 'CHC': '#003279',
'CHW': '#000000', 'SFG': '#F2552C', 'DET': '#001742', 'TBR': '#00285D', 'KCR': '#15317E',
'ATL': '#B71234', 'TEX': '#BD1021', 'SEA': '#005C5C', 'CLE': '#003366', 'NYY': '#1C2841'}
In [5]:
def plot_division(division):
tmpMaster = dfMaster.ix[division, ['Tm', 'GB']]
tmpMaster.replace({'--': 0}, inplace=True)
tmpMaster['GB'] = tmpMaster['GB'].astype(float)
tmpMaster['GB'] = tmpMaster['GB'] * -1
tmpMaster.reset_index(inplace=True)
tmpMaster.pivot(index='date', columns='Tm', values='GB').to_csv('data.csv')
divW = ipywidgets.Dropdown(options=dropList, )
init = divW.value
j = ipywidgets.interactive(plot_division, division=divW)
display(j)
In [6]:
%%html
<div id="d3-example"></div>
<style>
body {
font: 10px sans-serif;
}
.axis path,
.axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
.x.axis path {
display: none;
}
.line {
fill: none;
stroke: steelblue;
stroke-width: 1.5px;
}
</style>
In [7]:
%%javascript
// We load the d3.js library from the Web.
require.config({paths: {d3: "http://d3js.org/d3.v3.min"}});
require(["d3"], function(d3) {
var margin = {top: 20, right: 80, bottom: 30, left: 50},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var parseDate = d3.time.format("%Y-%m-%d").parse;
var x = d3.time.scale()
.range([0, width]);
var y = d3.scale.linear()
.range([height, 0]);
var color = d3.scale.category10();
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left");
var line = d3.svg.line()
.interpolate("basis")
.x(function(d) { return x(d.date); })
.y(function(d) { return y(d.GB); });
var svg = d3.select("#d3-example").select("svg")
if (svg.empty()) {
svg = d3.select("#d3-example").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")")
.attr("elasticY", true);
}
d3.csv("data.csv", function(error, data) {
if (error) throw error;
color.domain(d3.keys(data[0]).filter(function(key) { return key !== "date"; }));
data.forEach(function(d) {
d.date = parseDate(d.date);
});
var teams = color.domain().map(function(name) {
return {
name: name,
values: data.map(function(d) {
return {date: d.date, GB: +d[name]};
})
};
});
x.domain(d3.extent(data, function(d) { return d.date; }));
y.domain([
d3.min(teams, function(c) { return d3.min(c.values, function(v) { return v.GB; }); }),
d3.max(teams, function(c) { return d3.max(c.values, function(v) { return v.GB; }); })
]);
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", -35)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Games Behind");
var team = svg.selectAll(".team")
.data(teams)
.enter().append("g")
.attr("class", "team");
team.append("path")
.attr("class", "line")
.attr("d", function(d) { return line(d.values); })
.style("stroke", function(d) { return color(d.name); });
team.append("text")
.datum(function(d) { return {name: d.name, value: d.values[d.values.length - 1]}; })
.attr("transform", function(d) { return "translate(" + x(d.value.date) + "," + y(d.value.GB) + ")"; })
.attr("x", 3)
.attr("dy", ".35em")
.text(function(d) { return d.name; });
});
});
In [ ]: