编程语言
首页 > 编程语言> > Python中的多色散点图图例

Python中的多色散点图图例

作者:互联网

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

         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轴上的发动机尺寸和使用体型作为颜色方案来制作散点图,以区分身体类别和.
我还从单独的数据框中使用每辆车的“压缩比”来指定点数大小

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

这是我的代码:

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

解决方法:

在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

标签:scatter-plot,python,pandas,matplotlib,legend-properties
来源: https://codeday.me/bug/20191002/1844553.html