您好,登錄后才能下訂單哦!
這篇文章主要講解了“python繪圖中的技巧有哪些”,文中的講解內(nèi)容簡單清晰,易于學(xué)習(xí)與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學(xué)習(xí)“python繪圖中的技巧有哪些”吧!
數(shù)據(jù)集:
讓我們導(dǎo)入包并更新圖表的默認設(shè)置,為圖表添加一點個人風(fēng)格。 我們將在提示上使用 Seaborn
的內(nèi)置數(shù)據(jù)集:
import seaborn as sns # v0.11.2 import matplotlib.pyplot as plt # v3.4.2 sns.set(style='darkgrid', context='talk', palette='rainbow')df = sns.load\_dataset('tips') df.head()
繪制多個子圖的一種簡單方法是使用 plt.subplots()
。
這是繪制 2 個并排子圖的示例語法:
fig, ax = plt.subplots(nrows=1, ncols=2, figsize=(10,4)) sns.histplot(data=df, x='tip', ax=ax[0]) sns.boxplot(data=df, x='tip', ax=ax[1]);
在這里,我們在一個圖中繪制了兩個子圖。 我們可以進一步自定義每個子圖。
例如,我們可以像這樣為每個子圖添加標(biāo)題:
fig, ax = plt.subplots(1, 2, figsize=(10,4)) sns.histplot(data=df, x='tip', ax=ax[0]) ax[0].set\_title("Histogram") sns.boxplot(data=df, x='tip', ax=ax[1]) ax[1].set\_title("Boxplot");
在循環(huán)中將所有數(shù)值變量用同一組圖表示:
numerical = df.select\_dtypes('number').columnsfor col in numerical: fig, ax = plt.subplots(1, 2, figsize=(10,4)) sns.histplot(data=df, x=col, ax=ax[0]) sns.boxplot(data=df, x=col, ax=ax[1]);
另一種可視化多個圖形的方法是使用 plt.subplot(),
末尾沒有 s
語法與之前略有不同:
plt.figure(figsize=(10,4)) ax1 = plt.subplot(1,2,1) sns.histplot(data=df, x='tip', ax=ax1) ax2 = plt.subplot(1,2,2) sns.boxplot(data=df, x='tip', ax=ax2);
當(dāng)我們想為多個圖繪制相同類型的圖形并在單個圖中查看所有圖形,該方法特別有用:
plt.figure(figsize=(14,4)) for i, col in enumerate(numerical): ax = plt.subplot(1, len(numerical), i+1) sns.boxplot(data=df, x=col, ax=ax)
我們同樣能定制子圖形。例如加個title
plt.figure(figsize=(14,4)) for i, col in enumerate(numerical): ax = plt.subplot(1, len(numerical), i+1) sns.boxplot(data=df, x=col, ax=ax) ax.set\_title(f"Boxplot of {col}")
通過下面的比較,我們能更好的理解它們的相似處與不同處熟悉這兩種方法很有用,因為它們可以在不同情況下派上用場。
在繪制多個圖形時,經(jīng)常會看到一些子圖的標(biāo)簽在它們的相鄰子圖上重疊,
如下所示:
categorical = df.select\_dtypes('category').columnsplt.figure(figsize=(8, 8)) for i, col in enumerate(categorical): ax = plt.subplot(2, 2, i+1) sns.countplot(data=df, x=col, ax=ax)
頂部兩個圖表的 x 軸上的變量名稱被剪掉,右側(cè)圖的 y 軸標(biāo)簽與左側(cè)子圖重疊.使用plt.tight_layout
很方便
plt.figure(figsize=(8, 8)) for i, col in enumerate(categorical): ax = plt.subplot(2, 2, i+1) sns.countplot(data=df, x=col, ax=ax) plt.tight\_layout()
專業(yè) 看起來更好了。
真?zhèn)€圖形添加標(biāo)題:
plt.figure(figsize=(8, 8)) for i, col in enumerate(categorical): ax = plt.subplot(2, 2, i+1) sns.countplot(data=df, x=col, ax=ax) plt.suptitle('Category counts for all categorical variables') plt.tight\_layout()
此外,您可以根據(jù)自己的喜好自定義各個圖。 例如,您仍然可以為每個子圖添加標(biāo)題。
感謝各位的閱讀,以上就是“python繪圖中的技巧有哪些”的內(nèi)容了,經(jīng)過本文的學(xué)習(xí)后,相信大家對python繪圖中的技巧有哪些這一問題有了更深刻的體會,具體使用情況還需要大家實踐驗證。這里是億速云,小編將為大家推送更多相關(guān)知識點的文章,歡迎關(guān)注!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。