Python中的多色散点图图例

时间:2018-05-18 16:21:57

标签: python pandas matplotlib scatter-plot legend-properties

我有一些基本的汽车发动机尺寸,马力和车身类型数据(样品如下所示)

         body-style  engine-size  horsepower
0   convertible          130       111.0
2     hatchback          152       154.0
3         sedan          109       102.0
7         wagon          136       110.0
69      hardtop          183       123.0

其中我制作了一个散点图,其中x轴为马力,y轴为引擎尺寸,并使用体型作为颜色方案来区分身体类别和。 我还使用了#34;压缩率"每个汽车从单独的数据框中指定点数大小

这很好,除了我不能显示我的情节的颜色传说。我需要帮助,因为我是初学者。

这是我的代码:

dict = {'convertible':'red' ,  'hatchback':'blue' , 'sedan':'purple' , 'wagon':'yellow' , 'hardtop':'green'}

wtf["colour column"] = wtf["body-style"].map(dict)
wtf["comp_ratio_size"] = df['compression-ratio'].apply ( lambda x : x*x)

fig = plt.figure(figsize=(8,8),dpi=75)
ax = fig.gca()
plt.scatter(wtf['engine-size'],wtf['horsepower'],c=wtf["colour column"],s=wtf['comp_ratio_size'],alpha=0.4)
ax.set_xlabel('horsepower')
ax.set_ylabel("engine-size")
ax.legend()

1 个答案:

答案 0 :(得分:3)

matplotlib中,您可以轻松生成custom legends。在您的示例中,只需从字典中检索颜色标签组合,然后为图例创建custom patches

import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
import matplotlib.patches as mpatches
import pandas as pd

#this part just recreates your dataset
wtf =  pd.read_csv("test.csv", delim_whitespace=True)
col_dict = {'convertible':'red' ,  'hatchback':'blue' , 'sedan':'purple' , 'wagon':'yellow' , 'hardtop':'green'}
wtf["colour_column"] = wtf["body-style"].map(col_dict)
wtf["comp_ratio_size"] = np.square(wtf["horsepower"] - wtf["engine-size"])

fig = plt.figure(figsize=(8,8),dpi=75)
ax = fig.gca()
ax.scatter(wtf['engine-size'],wtf['horsepower'],c=wtf["colour_column"],s=wtf['comp_ratio_size'],alpha=0.4)
ax.set_xlabel('horsepower')
ax.set_ylabel("engine size")

#retrieve values from color dictionary and attribute it to corresponding labels
leg_el = [mpatches.Patch(facecolor = value, edgecolor = "black", label = key, alpha = 0.4) for key, value in col_dict.items()]
ax.legend(handles = leg_el)

plt.show()

输出:

enter image description here