1. 程式人生 > >Python資料視覺化:Matplotlib 直方圖、箱線圖、條形圖、熱圖、折線圖、散點圖。。。

Python資料視覺化:Matplotlib 直方圖、箱線圖、條形圖、熱圖、折線圖、散點圖。。。

介紹

      使用Python進行資料分析,資料的視覺化是資料分析結果最好的展示方式,這裡從Analytic Vidhya中找到的相關資料,進行一系列圖形的展示,從中得到更多的經驗。
      強烈推薦:Analytic Vidhya

Python資料視覺化庫

  • Matplotlib:其能夠支援所有的2D作圖和部分3D作圖。能通過互動環境做出印刷質量的影象。
  • Seaborn:基於Matplotlib,seaborn提供許多功能,比如:內建主題、顏色調色盤、函式和提供視覺化單變數、雙變數、線性迴歸的工具。其能幫助我們構建複雜的視覺化。

資料集

EMPID Gender Age Sales BMI Income
E001 M 34 123 Normal 350
E002 F 40 114 Overweight 450
E003 F 37 135 Obesity 169
E004 M 30 139 Underweight 189
E005 F 44 117 Underweight 183
E006 M 36 121 Normal 80
E007 M 32 133 Obesity 166
E008 F 26 140 Normal 120
E009 M 32 133 Normal 75
E010 M 36 133 Underweight 40

作圖

# -*- coding:UTF-8 -*-

import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
import numpy as np

# 0、匯入資料集
df = pd.read_excel('first.xlsx', 'Sheet1')
# 1、直方圖
fig = plt.figure() ax = fig.add_subplot(111) ax.hist(df['Age'], bins=7) plt.title('Age distribution') plt.xlabel('Age') plt.ylabel('Employee') plt.show()

這裡寫圖片描述

# 2、箱線圖  
fig = plt.figure()
ax = fig.add_subplot(111)
ax.boxplot(df['Age'])
plt.show()

這裡寫圖片描述

# 3、小提琴圖
sns.violinplot(df['Age'], df['Gender'])
sns.despine()
plt.show()

這裡寫圖片描述

# 4、條形圖
var = df.groupby('Gender').Sales.sum()
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.set_xlabel('Gender')
ax1.set_ylabel('Sum of Sales')
ax1.set_title('Gender wise Sum of Sales')
var.plot(kind='bar')
plt.show()

這裡寫圖片描述

# 5、折線圖
var = df.groupby('BMI').Sales.sum()
fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_xlabel('BMI')
ax.set_ylabel('Sum of Sales')
ax.set_title('BMI wise Sum of Sales')
var.plot(kind='line')
plt.show()

這裡寫圖片描述

# 6、堆積柱形圖
var = df.groupby(['BMI', 'Gender']).Sales.sum()
var.unstack().plot(kind='bar', stacked=True, color=['red', 'blue'])
plt.show()

這裡寫圖片描述

# 7、散點圖
fig = plt.figure()
ax = fig.add_subplot(111)
ax.scatter(df['Age'], df['Sales'])
plt.show()

這裡寫圖片描述

# 8、氣泡圖
fig = plt.figure()
ax = fig.add_subplot(111)
ax.scatter(df['Age'], df['Sales'], s=df['Income'])  # 第三個變量表明根據收入氣泡的大小
plt.show()

這裡寫圖片描述

# 9、餅圖
var = df.groupby(['Gender']).sum().stack()
temp = var.unstack()
type(temp)
x_list = temp['Sales']
label_list = temp.index
plt.axis('equal')
plt.pie(x_list, labels=label_list, autopct='%1.1f%%')
plt.title('expense')
plt.show()

這裡寫圖片描述

# 10、熱圖
data = np.random.rand(4, 2)
rows = list('1234')
columns = list('MF')
fig, ax = plt.subplots()
ax.pcolor(data, cmap=plt.cm.Reds, edgecolor='k')
ax.set_xticks(np.arange(0, 2)+0.5)
ax.set_yticks(np.arange(0, 4)+0.5)
ax.xaxis.tick_bottom()
ax.yaxis.tick_left()
ax.set_xticklabels(columns, minor=False, fontsize=20)
ax.set_yticklabels(rows, minor=False, fontsize=20)
plt.show()

這裡寫圖片描述