%matplotlib inline
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
plt.rcParams['figure.figsize'] = (20.0, 10.0)
plt.rcParams['font.family'] = "serif"

df = pd.read_csv('../../datasets/movie_metadata.csv')

df.head()

"""
Explanation: seaborn.boxplot

Boxplots summarize numeric data over a set of categories. The data is divided into four groups called quartiles. A box is drawn connecting the innermost two quartiles, and a horizontal line is drawn at the position of the median (which always falls within the box). Usually, a second set of lines will be drawn some distance from the inner box denoting a "maximum" and "minimum" value for the data, and then values existing outside of these extrema are considered outliers and plotted as individual points. The location of these "whisker" lines is variable and generally some multiple of the innerquartile range (IQR), which is range of values covered by the inner box.
dataset: IMDB 5000 Movie Dataset
End of explanation
"""


# split each movie's genre list, then form a set from the unwrapped list of all genres
categories = set([s for genre_list in df.genres.unique() for s in genre_list.split("|")])

# one-hot encode each movie's classification
for cat in categories:
    df[cat] = df.genres.transform(lambda s: int(cat in s))
# drop other columns
df = df[['director_name','genres','duration'] + list(categories)]
df.head()


# convert from wide to long format and remove null classificaitons
df = pd.melt(df,
             id_vars=['duration'],
             value_vars = list(categories),
             var_name = 'Category',
             value_name = 'Count')
df = df.loc[df.Count>0]
top_categories = df.groupby('Category').aggregate(sum).sort_values('Count', ascending=False).index
howmany=10
df = df.loc[df.Category.isin(top_categories[:howmany])]
df.rename(columns={"duration":"Duration"},inplace=True)


df.head()

"""
Explanation: For the bar plot, let's look at the number of movies in each category, allowing each movie to be counted more than once.
End of explanation
"""


p = sns.boxplot(data=df,
                x = 'Category',
                y = 'Duration')

"""
Explanation: Basic plot
End of explanation
"""


df = df.loc[df.Duration < 250]

p = sns.boxplot(data=df,
                x = 'Category',
                y = 'Duration')

"""
Explanation: The outliers here are making things a bit squished, so I'll remove them since I am just interested in demonstrating the visualization tool.
End of explanation
"""


p = sns.boxplot(data=df,
                x = 'Category',
                y = 'Duration',
                order = sorted(df.Category.unique()))


"""
Explanation: Change the order of categories
End of explanation
"""


p = sns.boxplot(data=df,
                y = 'Category',
                x = 'Duration',
                order = sorted(df.Category.unique()),
                orient="h")

"""
Explanation: Change the order that the colors are chosen
Change orientation to horizontal
End of explanation
"""


p = sns.boxplot(data=df,
                x = 'Category',
                y = 'Duration',
                order = sorted(df.Category.unique()),
                saturation=.25)

"""
Explanation: Desaturate
End of explanation
"""


p = sns.boxplot(data=df,
                x = 'Category',
                y = 'Duration',
                order = sorted(df.Category.unique()),
                width=.25)

"""
Explanation: Adjust width of boxes
End of explanation
"""


p = sns.boxplot(data=df,
                x = 'Category',
                y = 'Duration',
                order = sorted(df.Category.unique()),
                fliersize=20)

"""
Explanation: Change the size of outlier markers
End of explanation
"""


p = sns.boxplot(data=df,
                x = 'Category',
                y = 'Duration',
                order = sorted(df.Category.unique()),
                whis=.2)

"""
Explanation: Adjust the position of the whiskers as a fraction of IQR
End of explanation
"""


p = sns.boxplot(data=df,
                x = 'Category',
                y = 'Duration',
                order = sorted(df.Category.unique()),
                notch=True)

p = sns.boxplot(data=df,
                x = 'Category',
                y = 'Duration',
                order = sorted(df.Category.unique()),
                notch=False,
                linewidth=2.5)


"""
Explanation: Add a notch to the box indicating a confidence interval for the median
End of explanation
"""


sns.set(rc={"axes.facecolor":"#ccddff",
            "axes.grid":False,
            'axes.labelsize':30,
            'figure.figsize':(20.0, 10.0),
            'xtick.labelsize':25,
            'ytick.labelsize':20})


p = sns.boxplot(data=df,
                x = 'Category',
                y = 'Duration',
                palette = 'Paired',
                order = sorted(df.Category.unique()),
                notch=True)
plt.xticks(rotation=45)
l = plt.xlabel('')
plt.ylabel('Duration (min)')
plt.text(5.4,200, "Box Plot", fontsize = 95, color="black", fontstyle='italic')

p.get_figure().savefig('../figures/boxplot.png')

"""
Explanation: Finalize
End of explanation
"""


