2017-09-15 724 views
0

我的數據框有三列SKU,保存和標籤(categorical var)。當我打電話給plt.legend()時,它添加了「保存」的圖例,但我想爲我的顏色添加圖例(a,b,c,d)?Matplotlib:如何將圖例添加到散點圖的顏色?

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

回答

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

plt.legend是可調用的。通過寫plt.legend={'a', 'b', 'c', 'd'},要更換調用由set,這本身並沒有什麼(除了使其無法事後打電話legend。你想要做的是調用plt.legend()https://matplotlib.org/users/legend_guide.html

+0

謝謝,但是當我打電話給plt.legend時,它顯示Saving,而不是a,b,c,d組。 –

+0

不幸的是,從問題本身知道你想要繪製的圖像幾乎是不可能的,但考慮到你的評論,這聽起來像你正在尋找類似於https://stackoverflow.com/questions/21654635/scatter-plots-in-pandas-pyplot-how-to-plot-by-category#21655256。 – fuglede