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
"。
以上就是Python編程使用matplotlib挑鉆石seaborn畫圖入門的詳細內容,更多關于matplotlib挑鉆石seaborn畫圖入門的資料請關注服務器之家其它相關文章!
原文鏈接:https://blog.csdn.net/m0_37816922/article/details/120884878