Matplotlib:如何添加图例来分散绘图颜色?

时间:2017-09-15 18:38:03

标签: python pandas matplotlib

我的数据框有三列SKU,保存和标签(分类var)。当我拨打plt.legend()时,它会添加“保存”的图例,但我想在我的颜色(a,b,c,d)中添加图例?

from numpy import *
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
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]))

plt.show()

2 个答案:

答案 0 :(得分:1)

plt.legend是可调用的。通过编写plt.legend={'a', 'b', 'c', 'd'},您将set替换为legend,这本身不会做任何事情(除非之后无法调用plt.legend()。您要做的是调用{{ 1}}。见https://matplotlib.org/users/legend_guide.html

答案 1 :(得分:0)

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()