Python中的彩色散点图图例

2024-06-16 09:38:29 发布

您现在位置: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轴上显示发动机尺寸,并使用车身样式作为配色方案来区分车身等级和。 我还使用了“压缩比”每辆车从一个单独的数据帧来规定点的大小

这一切都很好,除了我不能显示我的情节颜色图例。我是初学者,需要帮助。

我的代码是:

^{pr2}$

Tags: 数据示例类型sizestyle尺寸body汽车
1条回答
网友
1楼 · 发布于 2024-06-16 09:38:29

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

相关问题 更多 >