Python 數據分析畫圖

Python 數據分析畫圖&one-hot編碼

標籤(空格分隔): python


Matplotlib畫圖

fig, axes = plt.subplots(2, 2) #axes是一個數組
fig = plt.figure()
fig.set(alpha=0.2) 

#把圖分爲2行3列,當前在(0,0)位置畫圖
plt.subplot2grid((2, 3), (0, 0))

#data_train是DataFrame數據類型 bar表示柱形圖
data_train.Survived.value_counts().plot(kind='bar')

plt.plot(randn(30).cumsum(), 'ko--') #k表示顏色,o表示標記強調數據點,--表示線條類型
plt.plot(randn(30).cumsum(), color='k', linestyle='dashed', marker='o') #和上面等價

設置軸標籤 刻度

  • xlim控制圖標的範圍,plt.xlim()返回當前X軸範圍,plt.xlim([0, 10]).我們也可以用過subplot的實例ax,如ax.get_xlim和ax.set_xlim來獲取設置
  • set_xticks控制刻度位置
  • set_xticklabels控制刻度上面的標籤
    實例
fig = plt.figure()
ax = fig.add_subplot(2, 2, 1)
ax.plot(np.random.randn(1000).cumsum(), 'ko--')
ticks = ax.set_xticks([0, 250, 500, 750, 1000])
labels = ax.set_xticklabels(['one', 'two', 'three', 'four', 'five'], rotation=3, fontsize='small')
ax.set_title('My Title')
ax.set_xlabel('xlabel')

添加圖例(legend)

fig = plt.figure()
ax = fig.add_subplot(1,1, 1)
ax.plot(np.random.randn(1000).cumsum(), 'k', label='one') #這裏不寫label的話,後面圖例就不會顯示
ax.plot(np.random.randn(1000).cumsum(), 'g--', label='two')
ax.plot(np.random.randn(1000).cumsum(), 'b.', label='three')
ax.legend(loc='best') #這裏是將每條線段對應哪個label顯示出來,刪除這句也不影響上面三條線段的顯示,loc告訴將圖例放在哪個位置,還有其他center,right等選項

添加基本幾何圖形

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.set_xlim([0, 10])
ax.set_ylim([0, 10])
#以下函數第一個參數都是點座標
rect = plt.Rectangle((0, 0), 2, 1, color='k', alpha=0.3)
circ = plt.Circle((5, 5), 2, color='r', alpha=0.3)
pgon = plt.Polygon([[0, 0], [1, 1], [1, 0]], color='g', alpha=0.3)
ax.add_patch(rect)
ax.add_patch(circ)
ax.add_patch(pgon)

保存圖片

plt.savefig('figpath.png', dpi=400, bbox_inches='tight')
#函數會根據輸入的文件名後綴自動判斷保存類型, dpi設置分辨率, bbox_inches表示要保存的部分tight是土建處圖像周圍白邊
#還有參數edgecolor,facecolor可以設置背景色,format顯示設置文件格式

關於matlibplot全局配置

plt.rc('figure', figsize=(10,10))
#第一個參數是想要設置的對象,第二個是參數配置

Pandas畫圖函數

Series和DataFrame都有用於生成各類圖表的plot方法
Series

s = Series(np.random.rand(1000).cumsum(), index=np.arange(0, 1000, 1))
s.plot()

DataFrame

df = DataFrame(np.random.randn(10, 4).cumsum(0), columns=['A', 'B', 'C', 'D'],
              index=np.arange(0,100,10))
fig, axes = plt.subplots(2, 2)
df.plot(kind='bar', ax=axes[0,0]) #ax參數是表明要在其上進行繪製
df.plot(kind='line', ax=axes[0,1])
df.plot(kind='bar', ax=axes[1,0])
df.plot(kind='barh', ax=axes[1,1])
#plot還可以設置style('ko--'等), alpha, logy(在Y軸上對數標尺), rot(旋轉刻度標籤) xticks xlim

這裏有一個問題,就是這裏書上沒有一個明確的對於Series或者DataFrame plot方法的解釋,因爲不會所以對我不可控

one-hot編碼

  • 對於離散屬性並且之間的取值沒有大小意義,一般採取one-hot編碼也就是對每一個取值都用一個0,1表示
  • 對於離散屬性取值有大小意義的,直接映射成1~n

pd.get_dummies可以很方便的將離散數據轉換成one-hot編碼

pd.get_dummies(data_train.Sex[:8])

這裏需要注意的是可能測試數據集和訓練數據集不一致
比如訓練數據集A屬性有3個取值,測試數據集中只有2個取值,這樣使用one-hot的話,測試數據集就會缺少一個屬性列.(這裏我在Titanic遇到了,其中我把訓練數據集中缺失當做一個屬性,而測試數據集中並沒有缺失,導致debug半天.這裏還是需要預先對數據集仔細分析)


axis=1 表示函數對列上進行作用
axis=0 表示函數對行上進行作用

關於seaborn畫圖介紹

sns.barplot(cnt_srs.index, cnt_srs.values, alpha=0.8, color=color[0])

train_df['bathrooms'].ix[train_df['bathrooms']>3] = 3
plt.figure(figsize=(8,4))
sns.violinplot(x='interest_level', y='bathrooms', data=train_df)
plt.xlabel('Interest level', fontsize=12)
plt.ylabel('bathrooms', fontsize=12)
plt.show()

sns.violinplot(x=”TARGET”, y=”ZCZB”, data=test2[test2[“ZCZB”].notnull()])
sns.swarmplot(x=”TARGET”, y=”ZCZB”, data=test2[test2[“ZCZB”].notnull()])

畫出各個變量和目標值的協方差

# Let us just impute the missing values with mean values to compute correlation coefficients #
mean_values = train_df.mean(axis=0)
train_df_new = train_df.fillna(mean_values, inplace=True)

# Now let us look at the correlation coefficient of each of these variables #
x_cols = [col for col in train_df_new.columns if col not in ['logerror'] if train_df_new[col].dtype=='float64']

labels = []
values = []
for col in x_cols:
    labels.append(col)
    values.append(np.corrcoef(train_df_new[col].values, train_df_new.logerror.values)[0,1])
corr_df = pd.DataFrame({'col_labels':labels, 'corr_values':values})
corr_df = corr_df.sort_values(by='corr_values')

ind = np.arange(len(labels))
width = 0.9
fig, ax = plt.subplots(figsize=(12,40))
rects = ax.barh(ind, np.array(corr_df.corr_values.values), color='y')
ax.set_yticks(ind)
ax.set_yticklabels(corr_df.col_labels.values, rotation='horizontal')
ax.set_xlabel("Correlation coefficient")
ax.set_title("Correlation coefficient of the variables")
#autolabel(rects)

#設置label的字體大小
ax.tick_params(axis='both', which='major', labelsize=30)
ax.tick_params(axis='both', which='minor', labelsize=24)
plt.show()
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章