本文的文字及圖檔來源于網絡,僅供學習、交流使用,不具有任何商業用途,版權歸原作者所有,如有問題請及時聯系我們以作處理
以下文章來源于騰訊雲 作者:Python進擊者
( 想要學習Python?Python學習交流群:1039649593,滿足你的需求,資料都已經上傳群檔案流,可以自行下載下傳!還有海量最新2020python學習資料。 )
seaborn
Seaborn is a library for making statistical graphics in Python. It is
built on top of matplotlib and closely integrated with pandas data
structures.
上面這段話是摘自seaborn的官網,翻譯過來的意思就是Seaborn是一個制作統計圖形的第三方Python庫。它是基于matplotlib而建立的并且它與pandas資料結構有着緊密的連接配接。
其實簡單來說,它就是一個matplotlib的更新版,作為更新版固然會讓我們的使用更加的簡單,下面我們來看看seaborn。
安裝seaborn
pip安裝:
pip install seaborn
conda安裝:
conda install seaborn
這裡需要注意的一點是,seaborn依賴于Python3.6及其以上的版本。
并且需要強制安裝以下的依賴第三方庫:
numpy (>= 1.13.3)
scipy (>= 1.0.1)
pandas (>= 0.22.0)
matplotlib (>= 2.1.2)
内置資料集
seaborn有一個讓我比較驚豔的地方是它自帶有資料集,我們可以直接通過相關的函數就可以進行調用,資料集的檔案也可以在下面的GitHub位址中擷取。
https://github.com/mwaskom/seaborn-data
對于資料集的使用,我們這裡可以引用一個官方的例子來實作:
importseaborn as snsimportmatplotlib.pyplot as pltimportssl#此處的代碼是防止ssl報錯
ssl._create_default_https_context =ssl._create_unverified_context
sns.set(style="ticks")#導入anscombe資料集
df = sns.load_dataset("anscombe")
sns.lmplot(x="x", y="y", col="dataset", hue="dataset", data=df,
col_wrap=2, ci=None, palette="muted", height=4,
scatter_kws={"s": 50, "alpha": 1})#在pycharm中,我們需要通過matplotlib來讓seaborn圖形顯示
plt.show()
效果圖:
seaborn API
要想知道seaborn怎麼使用,能夠畫哪些圖形,了解它的API是必不可少的。這裡需要注意的是seaborn中的資料集必須是pandas中的Dataframe或者Numpy中的數組,這就說明了為什麼pandas和numpy是必備的依賴庫。
1.lineplot
seaborn.lineplot(x=None, y=None, hue=None, size=None, style=None, data=None, palette=None, hue_order=None, hue_norm=None, sizes=None, size_order=None, size_norm=None, dashes=True, markers=None, style_order=None, units=None, estimator='mean', ci=95, n_boot=1000, seed=None, sort=True, err_style='band', err_kws=None, legend='brief', ax=None, **kwargs)
通過單詞的字面意思,我們可以想到的是折線圖,确實lineplot可以幫助我們畫出漂亮的折線圖。它的屬性值非常的多,這裡我們也不會一一全部介紹。
首先直接扔出代碼
importseaborn as snsimportmatplotlib.pyplot as pltimportssl
ssl._create_default_https_context= ssl._create_unverified_context #解決ssl報錯
#拿到名字為 fmri 的資料集
fmri = sns.load_dataset("fmri")#解析請繼續往下看
ax = sns.lineplot(x="timepoint", y="signal",data=fmri,
style="event", hue="event", markers=True
, ci=0, lw=1,
)
plt.show()
效果圖
首先,大家可以看下資料集
https://github.com/mwaskom/seaborn-data/blob/master/fmri.csv
ax =sns.lineplot(
x="timepoint",
y="signal",
data=fmri,
style="event",
hue="event",
markers=True,
ci=0,
lw=1,
)
lw控制的是折線的寬度,如果lw=10則為
2.barplot
importseaborn as snsimportnumpy as npimportpandas as pdimportmatplotlib.pyplot as plt
x= np.arange(8)
y= np.array([12,15,13,16,23,11,5,6])
df= pd.DataFrame({"x": x,"y": y})
sns.barplot("x","y",palette="RdBu_r",data=df)
plt.xticks(rotation=90)
plt.show()
效果圖:
這裡的代碼顧名思義就非常的簡單易懂了,其中palette="RdBu_r"是使用一種顔色模闆。