關(guān)鍵字:相關(guān)性分析、調(diào)整字體、Seaborn、Python
涉及Seaborn常用的畫圖函數(shù),以及常用的調(diào)整字體,設(shè)置坐標(biāo)軸標(biāo)簽、設(shè)置刻度、保存圖片時(shí)不留白邊等技巧。示例使用了紐約市出租車數(shù)據(jù),要注意我對(duì)數(shù)據(jù)進(jìn)行了預(yù)處理。
(New York City. tlc-trip-record-data. https://www1.nyc.gov/site/tlc/about/tlc-trip-record-data.page)
在使用這些代碼時(shí)要調(diào)整輸入的數(shù)據(jù),根據(jù)需要改變坐標(biāo)軸標(biāo)簽和字體大小。
0 全局設(shè)置
可以全局地對(duì)seaborn字體進(jìn)行調(diào)整:
import seaborn as sns
sns.set(style="darkgrid") # 這是seaborn默認(rèn)的風(fēng)格
sns.set(font_scale=1.5)
plt.rcParams['font.sans-serif'] = ['SimHei'] # 使用中文字體
Mac畫圖中文亂碼,需要:
plt.rcParams['font.sans-serif'] = ['Arial Unicode MS']
plt.rcParams['image.interpolation'] = 'nearest'
plt.rcParams['image.cmap'] = 'gray'
plt.rcParams['axes.unicode_minus'] = False
1. 單變量統(tǒng)計(jì)分析
1.1 概率密度圖:連續(xù)型變量的分布
適用于連續(xù)型變量:
ax = sns.distplot(dataframe_name[col_name])
# 設(shè)置刻度字體, 坐標(biāo)標(biāo)簽字體大小
plt.xticks(fontsize=20)
plt.yticks(fontsize=20)
# ax.set_xticks([0, 200000, 400000]) # 設(shè)置x軸刻度
ax.set_xlabel("LabelName", fontsize=20)
ax.set_ylabel("LabelName", fontsize=20)
1.2 柱狀圖:離散型變量的分布
柱狀圖;這個(gè)函數(shù)最好對(duì)離散型變量使用,對(duì)于dataframe中的一列數(shù)據(jù),它會(huì)統(tǒng)計(jì)不同種類的數(shù)據(jù)項(xiàng)出現(xiàn)的次數(shù),然后畫柱狀圖。
ax = sns.countplot(x=col_name, data=dataframe_name)
# 設(shè)置刻度字體, 坐標(biāo)標(biāo)簽字體大小
plt.xticks(fontsize=20)
plt.yticks(fontsize=20)
# ax.set_xticks([0, 1, 2, 3, 4, 5]) # 設(shè)置x軸刻度
ax.set_xlabel("LabelName", fontsize=20)
ax.set_ylabel("LabelName", fontsize=20)
2 多變量相關(guān)性分析
2.1 散點(diǎn)圖
選dataframe中的兩列畫散點(diǎn)
ax = sns.scatterplot(x=x_name, y=y_name, data=dataframe_name)
# 設(shè)置刻度,坐標(biāo)軸大小,名字。
ax.set_xlabel(x_label, fontsize=20)
ax.set_ylabel(y_label, fontsize=20)
plt.xticks(fontsize=20)
plt.yticks(fontsize=20)
2.2 聯(lián)合分布圖/核密度圖:連續(xù)型變量之間的相關(guān)性
選dataframe中的兩列畫聯(lián)合分布,易于發(fā)現(xiàn)兩個(gè)變量間的關(guān)系。這里為了讓圖片顯示更清晰,我用了疫情數(shù)據(jù)和百度遷徙數(shù)據(jù)。然后核密度圖的數(shù)據(jù)是使用了紐約出租車的數(shù)據(jù),核密度圖可用于聚類分析。
# kind='reg' 會(huì)畫出那條擬合的直線和置信區(qū)間
ax = sns.jointplot(x=x_name, y=y_name, data=dataframe_name, kind='reg', height=5)
# 核密度圖:(實(shí)際畫圖的時(shí)候一個(gè)一個(gè)畫)
# ax = sns.kdeplot(dataframe_name[x_name], dataframe_name[y_name], shade=True, shade_lowest=False, cbar=True, color='r')
# 設(shè)置刻度字體大小,注意這里對(duì)坐標(biāo)軸的設(shè)置與前面不同,核密度圖和聯(lián)合分布圖要用set_axis_labels
ax.set_axis_labels(x_label, y_label, fontsize=20) # label of the coordinate axis
plt.xticks(fontsize=20)
plt.yticks(fontsize=20)
2.3 小提琴圖與箱線圖:連續(xù)型變量與離散型變量之間的相關(guān)性
注意它在設(shè)置刻度的時(shí)候是和前面的散點(diǎn)圖,柱狀圖,概率密度圖等一致的。
這里的三行代碼分別畫小提琴圖,箱線圖,分布密度散點(diǎn)圖,畫圖時(shí),我在x軸放的是離散型變量。
另外有許多參數(shù)可調(diào),我在這里舉了箱線圖中hue='taxi_type'的例子
# ax = sns.violinplot(x=x_name, y=y_name, data=dataframe_name, inner=None, whis=np.inf)
ax = sns.boxplot(x=x_name, y=y_name, data=dataframe_name, hue='taxi_type')
# ax = sns.swarmplot(x=x_name, y=y_name, data=dataframe_name, color="c")
# 設(shè)置刻度字體大小
ax.set_xlabel(x_label, fontsize=20)
ax.set_ylabel(y_label, fontsize=20)
plt.xticks(fontsize=20)
plt.yticks(fontsize=20)
2.4 相關(guān)性的計(jì)算
這里相關(guān)性計(jì)算使用scipy中的函數(shù),計(jì)算的結(jié)果包括斜率,截距,R-value,P-value,標(biāo)準(zhǔn)差。
選取的y1, y2兩列數(shù)據(jù)應(yīng)具有同樣長(zhǎng)度。
import scipy
slope, intercept, r_value, p_value, std_err = scipy.stats.linregress(y1, y2)
3 類別與聚類分析
3.1 點(diǎn)圖:直接地看出兩種類別的區(qū)別
簡(jiǎn)單地理解,點(diǎn)圖可以畫出多個(gè)類別地均值和方差,可以直觀地看出不同類別地區(qū)別。
如圖7,可以看出黃色出租車的收入均值更小,方差更小。
sample_taxi = all_taxi.sample(n=10000, random_state=1) # 畫圖前先采樣了,不然數(shù)據(jù)太多畫的慢
ax = sns.pointplot(x="taxi_type", y="total_amount", data=sample_taxi)
# ax = sns.pointplot(x="taxi_type", y="total_amount", data=sample_taxi, estimator=np.median,
# dodge=True, palette="Set2", markers=["o", "x"], linestyles=["-", "--"])
# 這里設(shè)置坐標(biāo)軸的方法和上面一致
ax.set_xlabel(x_label, fontsize=20)
ax.set_ylabel(y_label, fontsize=20)
plt.xticks(fontsize=20)
plt.yticks(fontsize=20)
3.2 聚類
注意我選取了原始數(shù)據(jù)中的兩列進(jìn)行聚類。
可以調(diào)整sns.clustermap()中的method參數(shù)以改變聚類的方式:默認(rèn)為為average算法,可選’single’,’complete’ ,’weighted’,’centroid’,’median’。
lo_number = lo_number[['engaged number', 'disengaged number']]
g = sns.clustermap(lo_number, fmt="d", cmap='YlGnBu', figsize=(6, 9))
ax = g.ax_heatmap
label_y = ax.get_yticklabels()
plt.setp(label_y, rotation=360, horizontalalignment='left')
4 畫圖技巧總結(jié)
4.1 調(diào)整坐標(biāo)軸標(biāo)簽及大小
這里分成兩部分,一是坐標(biāo)軸的刻度,二是坐標(biāo)軸的標(biāo)簽。
調(diào)整坐標(biāo)軸刻度大小,以及旋轉(zhuǎn)角度,對(duì)于所有的圖都可以使用如下代碼(因?yàn)槭侵苯诱{(diào)整plt的):
plt.xticks(fontsize=20, rotation=30)
plt.yticks(fontsize=20, rotation=30)
調(diào)整坐標(biāo)軸標(biāo)簽和字體大小,聯(lián)合分布圖和核密度圖需要這樣:
ax.set_axis_labels(x_label, y_label, fontsize=20) # label of the coordinate axis
其他的如概率密度圖,柱狀圖,散點(diǎn)圖,小提琴圖,箱線圖,點(diǎn)圖等,調(diào)整坐標(biāo)軸標(biāo)簽時(shí)可以這樣:
# ax.set_xticks([0, 200000, 400000]) # 設(shè)置x軸刻度
# ax.set_xticks([0, 1, 2, 3, 4, 5]) # 設(shè)置x軸刻度
ax.set_xlabel(x_label, fontsize=20)
ax.set_ylabel(y_label, fontsize=20)
4.2 保存圖片時(shí)常用技巧
保存圖片時(shí),保存為svg格式(可以任意放縮)。且不保留圖片四周的白邊:
plt.savefig($FigName + '.svg', format='svg', bbox_inches='tight')