Reputation: 73
I'm making a time series boxplot using seaborn package but I can't put a label on my outliers.
My data is a dataFrame of 3 columns : [Month , Id , Value]
that we can fake like that :
### Sample Data ###
Month = numpy.repeat(numpy.arange(1,11),10)
Id = numpy.arange(1,101)
Value = numpy.random.randn(100)
### As a pandas DataFrame ###
Ts = pandas.DataFrame({'Value' : Value,'Month':Month, 'Id': Id})
### Time series boxplot ###
ax = seaborn.boxplot(x="Month",y="Value",data=Ts)
I have one boxplot for each month and I'm trying to put the Id
as a label of the three outliers on the plot here:
Upvotes: 7
Views: 3940
Reputation: 12496
First of all, you need to detect which Id
in your dataframe are outliers, you can use this:
outliers_df = pd.DataFrame(columns = ['Value', 'Month', 'Id'])
for month in Ts['Month'].unique():
outliers = [y for stat in boxplot_stats(Ts[Ts['Month'] == month]['Value']) for y in stat['fliers']]
if outliers != []:
for outlier in outliers:
outliers_df = outliers_df.append(Ts[(Ts['Month'] == month) & (Ts['Value'] == outlier)])
which creates a dataframe, similar to the original one, containing outliers only.
Then you can annotare Id
on your plot with this:
for row in outliers_df.iterrows():
ax.annotate(row[1]['Id'], xy=(row[1]['Month'] - 1, row[1]['Value']), xytext=(2,2), textcoords='offset points', fontsize=14)
The complete code:
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from matplotlib.cbook import boxplot_stats
sns.set_style('darkgrid')
Month = np.repeat(np.arange(1,11),10)
Id = np.arange(1,101)
Value = np.random.randn(100)
Ts = pd.DataFrame({'Value' : Value,'Month':Month, 'Id': Id})
fig, ax = plt.subplots()
sns.boxplot(ax=ax, x="Month",y="Value",data=Ts)
outliers_df = pd.DataFrame(columns = ['Value', 'Month', 'Id'])
for month in Ts['Month'].unique():
outliers = [y for stat in boxplot_stats(Ts[Ts['Month'] == month]['Value']) for y in stat['fliers']]
if outliers != []:
for outlier in outliers:
outliers_df = outliers_df.append(Ts[(Ts['Month'] == month) & (Ts['Value'] == outlier)])
for row in outliers_df.iterrows():
ax.annotate(row[1]['Id'], xy=(row[1]['Month'] - 1, row[1]['Value']), xytext=(2,2), textcoords='offset points', fontsize=14)
plt.show()
output:
Upvotes: 4