python中散点图_Python中的多色散点图图例

该博客介绍了如何使用Python的matplotlib库创建一个彩色散点图,其中点的颜色根据数据的不同类别变化,大小由'compression-ratio'属性决定。博主遇到了无法显示颜色图例的问题,然后通过创建自定义图例解决了这个问题。代码示例展示了如何从字典中获取颜色标签,并将它们与图例元素关联,从而成功生成图例。
摘要由CSDN通过智能技术生成

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

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

输出:

7cJGm.png

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

来源: https://codeday.me/bug/20191002/1844553.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值