python散点图图例_Matplotlib:如何将图例添加到散点图的颜色?

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值