import pandas as pd

# import a ticker formatting class from matplotlib
from matplotlib.ticker import FuncFormatter

"""
Explanation: Simple charts in pandas
In this session, we're gonna revisit our MLB data to rock a quick chart in pandas. Our goal: A horizontal bar chart of the top 10 teams by payroll.
Import pandas and a some chart formatting help
End of explanation
"""


%matplotlib inline

"""
Explanation: Let Jupyter know that you're gonna be charting inline
(Don't worry if you get a warning about building a font library.)
End of explanation
"""


# create a data frame
df = pd.read_csv('data/mlb.csv')

# use head to check it out
df.head()

"""
Explanation: Read in MLB data
End of explanation
"""


# group by team, aggregate on sum
grouped_by_team = df[['TEAM', 'SALARY']].groupby('TEAM') \
                                        .sum() \
                                        .reset_index() \
                                        .set_index('TEAM') \
                                        .sort_values('SALARY', ascending=False)

# get top 10
top_10 = grouped_by_team.head(10)

top_10

"""
Explanation: Prep data for charting
Let's chart total team payroll, most to least. Let's repeat the grouping we did before.
End of explanation
"""


# make a horizontal bar chart
# set the figure size
bar_chart = top_10.plot.barh(figsize=(14, 6))

# sort the bars top to bottom
bar_chart.invert_yaxis()

# set the title
bar_chart.set_title('Top 10 opening day MLB payrolls, 2017')

# kill the legend
bar_chart.legend_.remove()

# kill y axis label
bar_chart.set_ylabel('')

# define a function to format x axis ticks
# otherwise they'd all run together (100000000)
# via https://stackoverflow.com/a/46454637
def millions(num, pos, m=1000000):
    if num % m == 0:
        num = int(num/m)
    else:
        num = float(num/m)
    
    return '${}M'.format(num)

# format the x axis ticks using the function we just defined
bar_chart.xaxis.set_major_formatter(FuncFormatter(millions))

"""
Explanation: Make a horizonal bar chart
End of explanation
"""


