import pandas as pd
import numpy as np
import matplotlib.patches as mpatches
import matplotlib.pyplot as plt
df = pd.DataFrame(np.random.rand(100,1), columns=['Saving'])
df['SKU'] = np.arange(100)
df['label'] = np.random.choice(['a', 'b', 'c','d'], 100)
fig, ax = plt.subplots()
colors = {'a':'red', 'b':'blue', 'c':'green', 'd':'white'}
figSaving = ax.scatter(df['SKU'], df['Saving'], c=df['label'].apply(lambda x: colors[x]))
# build the legend
red_patch = mpatches.Patch(color='red', label='a')
blue_patch = mpatches.Patch(color='blue', label='b')
green_patch = mpatches.Patch(color='green', label='c')
white_patch = mpatches.Patch(color='white', label='d')
# set up for handles declaration
patches = [red_patch, blue_patch, green_patch, white_patch]
# define and place the legend
#legend = ax.legend(handles=patches,loc='upper right')
# alternative declaration for placing legend outside of plot
legend = ax.legend(handles=patches,bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
plt.show()
2017-09-15 20:02:29