6

如何用python给女朋友挑钻石(seaborn画图入门)

 2 years ago
source link: https://blog.csdn.net/m0_37816922/article/details/120884878
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

挑钻石第二弹

seaborn是matplotlib的补充包,提供了一系列高颜值的figure,并且集成了多种在线数据集,通过sns.load_dataset()进行调用,可供学习,如果网络不稳定,可下载到本地,然后在调用的时候使用把cache设为True

scatter_plot

官方的示例就很不错,绘制了diamonds数据集中的钻石数据。diamonds中总共包含十项数据,分别是重量/克拉切割水平颜色透明度深度、table、价格以及x、y、z方向的尺寸。

我们可以先来看看xy方向的尺寸是否有一定的相关性

import seaborn as sns
import matplotlib.pyplot as plt
# 本地加载数据集
dia = sns.load_dataset("diamonds",data_home="seaborn-data", cache=True)
# 以上几行代码后面不再重复书写

sns.scatterplot(x=dia['x'],y=dia['y'],size=5)
plt.show()  #用于显示图片,后文就不写了

在这里插入图片描述

其中xy分别代表x轴和y轴数据,可见一般钻石还是比较规则的。

官方画廊绘制的图像如下

在这里插入图片描述

这个图的横坐标是重量(克拉),纵坐标是价格,我们发现钻石商人大多有强迫症,因为2.0克拉、1.5克拉、1.0克拉这种整十整五的钻石比周围重量的钻石更多。。。

f, ax = plt.subplots(figsize=(6.5, 6.5))
sns.set_theme(style="whitegrid")
sns.despine(f, left=True, bottom=True)
clarity =  ["I1", "SI2", "SI1", "VS2", "VS1", "VVS2", "VVS1", "IF"]   #颜色深浅的顺序
sns.scatterplot(x="carat", y="price",         #声明x轴和y轴的值
    hue="clarity", size="depth",  #clarity和depth分别调控颜色和尺寸
    palette="ch:rot=-.2,d=.3_r",    #调色板
    style_order=clarity,sizes=(1,10), #颜色标识的顺序和尺寸范围
    linewidth=0,data=dia, ax=ax)
plt.show()

首先,set_theme用于设置主题,其中style可以输入字符串或者字典,可调整主题风格。

其次,palette代表颜色映射,当其输入值为字符串时,其含义为

缩写取值范围starts[0,3]渐变始点颜色rotr用于调控色相gammag不小于0小于1时,提高暗部;大于1时,加强高光hueh[0,1]Saturation of the colors.darkd[0,1]最暗处的强度lightl[0,1]最亮处颜色的强度

sizes用于调整点的尺寸,当设置size时,将size中的值对应到ssizes中从而绘图。

我们注意到钻石属性中有一个是切割水平,那么接下来绘制一下切割水平和价格的关系。

fig, ax = plt.subplots(figsize=(6.5, 6.5))
sns.set_theme(style="whitegrid")
sns.despine(fig, left=True, bottom=True)
sns.scatterplot(data = dia, x="carat", y="price",
    style="cut",hue='cut',
    linewidth=0)
plt.show()

果然把渐变颜色去掉之后颜值狂掉,但同时可以发现,这个very good显然不是最好的切割等级,毕竟在3.0克拉级别的钻石中,有一颗very good级别的钻石买到了最低价。GIA评估的钻石等级为Excellent,Very Good,Good,Fair到最差Poor,可能在这个数据集中,ideal就代表了Excellent吧。

在这里插入图片描述

lmplot

如果想更准确地观察cut对钻石价格的影响,可以通过lmplot在散点图的基础上绘制一个趋势线出来。

sns.lmplot(data=dia, x="carat", y="price",hue='cut',markers = '.')
plt.show()

在这里插入图片描述

这样一看就发现果然ideal的钻石是最好的。

jointplot

以上诸图,都是消费者最关心的问题——价格、尺寸以及透明度等。但商家最关心的可能是价格、重量与销售量的关系,这就涉及到一个分布的问题。而seaborn提供了一个非常好的双变量关系图——jointplot,效果如下

在这里插入图片描述在这里插入图片描述

可见,还是便宜的钻石比较火爆,代码分别为

# 左图代码
sns.jointplot(data=dia, x="carat", y="price",xlim=(0,3),ylim=(0,17500), ratio=10,kind='hex',color="#4CB391")
# 右图代码
sns.jointplot(data=dia, x="carat", y="price",hue='cut', xlim=(0,3),ylim=(0,17500), ratio=10,marker='.')

其中,kind用于更改图像的风格,sns提供了六种风格:"scatter" | "kde" | "hist" | "hex" | "reg" | "resid"


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK