Matplotlib:如何将图例添加到散点图的颜色?
问题描述:
我的数据框有三列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()
答
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()
答
plt.legend
是可调用的。通过写plt.legend={'a', 'b', 'c', 'd'}
,要更换调用由set
,这本身并没有什么(除了使其无法事后打电话legend
。你想要做的是调用plt.legend()
见https://matplotlib.org/users/legend_guide.html。
谢谢,但是当我打电话给plt.legend时,它显示Saving,而不是a,b,c,d组。 –
不幸的是,从问题本身知道你想要绘制的图像几乎是不可能的,但考虑到你的评论,这听起来像你正在寻找类似于https://stackoverflow.com/questions/21654635/scatter-plots-in-pandas-pyplot-how-to-plot-by-category#21655256。 – fuglede