2016-03-19 66 views
0

我想知道如何执行以下操作: 我有一个带点和类的DataFrame。我想绘制所有点,并为每个班级使用一种颜色。我如何指定类如何引用图例中的颜色?matplotlib中的图例

fig = plt.figure(figsize=(18,10), dpi=1600) 
df = pd.DataFrame(dict(points1 = data_plot[:,0], points2 = data_plot[:,1], \ 
      target = target[0:2000])) 
colors = {1: 'green', 2:'red', 3:'blue', 4:'yellow', 5:'orange', 6:'pink', \        
       7:'brown', 8:'black', 9:'white'} 
fig, ax = plt.subplots() 
ax.scatter(df['points1'], df['points2'], c = df['target'].apply(lambda x: colors[x])) 
+0

可以为用户提供的是你所得到的输出和你想获得输出最小的可运行的例子吗?这将更容易理解和回答你的问题。 –

回答

1

,最简单的办法让你的传奇有单独的条目为每种颜色(因此它的target值)创建一个单独的情节对象每个target值。

import matplotlib.pyplot as plt 
import pandas as pd 
import numpy as np 

x = np.random.rand(100) 
y = np.random.rand(100) 
target = np.random.randint(1,9, size=100) 

df = pd.DataFrame(dict(points1=x, points2=y, target=target)) 
colors = {1: 'green', 2:'red', 3:'blue', 4:'yellow', 5:'orange', 6:'pink', \ 
       7:'brown', 8:'black', 9:'white'} 
fig, ax = plt.subplots() 

for k,v in colors.items(): 
    series = df[df['target'] == k] 
    scat = ax.scatter(series['points1'], series['points2'], c=v, label=k) 

plt.legend() 

enter image description here

+0

我不会说'只'的方式,只是最直接的前进;)你可以用代理艺术家做一些有趣的事情。请参阅http://matplotlib.org/users/legend_guide.html#creating-artists-specifically-for-adding-to-the-legend-aka-proxy-artists – tacaswell