文章目錄
- scatter_plot
- lmplot
- jointplot
seaborn是matplotlib的補充包,提供了一系列高顏值的figure,并且集成了多種 在線資料集,通過
sns.load_dataset()進行呼叫,可供學習,如果網路不穩定,可下載到本地,然后在呼叫的時候使用把
cache設為
True,
scatter_plot
官方的示例就很不錯,繪制了diamonds資料集中的鉆石資料,diamonds中總共包含十項資料,分別是重量/克拉、切割水平、顏色、透明度、深度、table、價格以及x、y、z方向的尺寸,
我們可以先來看看x和y方向的尺寸是否有一定的相關性
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() #用于顯示圖片,后文就不寫了

其中x,y分別代表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代表顏色映射,當其輸入值為字串時,其含義為
| 縮寫 | 取值范圍 | ||
|---|---|---|---|
| start | s | [0,3] | 漸變始點顏色 |
| rot | r | 用于調控色相 | |
| gamma | g | 不小于0 | 小于1時,提高暗部;大于1時,加強高光 |
| hue | h | [0,1] | Saturation of the colors. |
| dark | d | [0,1] | 最暗處的強度 |
| light | l | [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",
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/332105.html
標籤:python


