目錄
- 前言
- 1.常用視圖
- 1.1 折線圖
- 1.2 柱狀圖
- 1.2.1 堆疊柱狀圖
- 1.2.2 分組帶標簽柱狀圖
- 1.3 極坐標圖
- 1.3.1 線性極坐標
- 1.3.2 條形極坐標
- 1.4 直方圖
- 1.5 箱形圖
- 1.6 散點圖
- 1.7 餅圖
- 1.7.1 一般餅圖
- 1.7.2 甜甜圈
- 1.8 熱力圖
- 1.9 面積圖
- 1.10 蜘蛛圖
- 2.3D圖形
- 2.1 三維折線圖
- 2.2 三維散點圖
- 2.3 三維柱狀圖
- 3.Seaborn
- 1.安裝
- 2.快速上手
- 2.1 模式設定
- 2.2 線形圖
- 3.各種圖形繪制
- 3.1 調色板
- 3.2 線形圖
- 3.3 散點圖
- 3.4 柱狀圖
- 3.5 箱式圖
- 3.6 直方圖
- 3.7 分類散點圖
- 3.8 熱力圖
- 4.訓練場
- 4.1 資料處理
- 4.2 資料挖掘與可視化
前言
本文其實屬于:Python的進階之道【AIoT階段一】的一部分內容,本篇把這部分內容單獨截取出來,方便大家的觀看,本文介紹Matplotlib資料可視化進階,讀本文之前,如果沒有 Matplotlib基礎建議先看博客:Matplotlib資料可視化入門,Matplotlib資料可視化高級,
🌟 學習本文之前,需要先自修:NumPy從入門到進階,pandas從入門到進階本文中很多的操作在 NumPy從入門到進階 ,pandas從入門到進階二文中有詳細的介紹,包含一些軟體以及擴展庫,圖片的安裝和下載流程,本文會直接進行使用,
下載 M a t p l o t l i b Matplotlib Matplotlib 見博客:matplotlib的安裝教程以及簡單呼叫,這里不再贅述
1.常用視圖
1.1 折線圖
import numpy as np
import matplotlib.pyplot as plt
y = np.random.randint(0, 10, size = 15)
# 一圖多線
plt.figure(figsize = (9, 6))
# 只給了y,不給x,則x有默認值:0、1、2、3、...
plt.plot(y, marker = '*', color = 'r')
plt.plot(y.cumsum(), marker = 'o')
# 多圖布局
fig,axs = plt.subplots(2, 1)
# 設定寬高
fig.set_figwidth(9)
fig.set_figheight(6)
axs[0].plot(y, marker = '*', color = 'red')
axs[1].plot(y.cumsum(), marker = 'o')

1.2 柱狀圖
1.2.1 堆疊柱狀圖
import numpy as np
import matplotlib.pyplot as plt
labels = ['G1', 'G2', 'G3', 'G4', 'G5','G6'] # 級別
# 生成資料
men_means = np.random.randint(20, 35, size = 6)
women_means = np.random.randint(20, 35, size = 6)
men_std = np.random.randint(1, 7, size = 6)
women_std = np.random.randint(1, 7, size = 6)
width = 0.35 # 柱狀圖中柱的寬度
plt.bar(labels, # 橫坐標
men_means, # 柱高
width, # 線寬
yerr = men_std, # 誤差條(標準差)
label = 'Men') # 標簽
plt.bar(labels,
women_means,
width,
yerr = women_std,
bottom = men_means, # 把女生畫成男生的上面
# 沒有上一行代碼柱狀圖會發生重疊覆寫,讀者可以自行嘗試
label = 'Women')
plt.ylabel('Scores')
plt.title('Scores by group and gender')
plt.legend()

1.2.2 分組帶標簽柱狀圖
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
# 創造資料
labels = ['G1', 'G2', 'G3', 'G4', 'G5','G6'] # 級別
men_means = np.random.randint(20, 35,size = 6)
women_means = np.random.randint(20, 35,size = 6)
x = np.arange(len(men_means))
plt.figure(figsize = (9, 6))
# 把男生的柱狀圖整體左移 width / 2
rects1 = plt.bar(x - width / 2, men_means, width)
# 把女生的柱狀圖整體右移 width / 2
rects2 = plt.bar(x + width / 2, women_means, width)
# 設定標簽標題,圖例
plt.ylabel('Scores')
plt.title('Scores by group and gender')
plt.xticks(x, labels)
plt.legend(['Men','Women'])
# 放置文本 text
def set_label(rects):
for rect in rects:
height = rect.get_height() # 獲取高度
plt.text(x = rect.get_x() + rect.get_width() / 2, # 水平坐標
y = height + 0.5, # 豎直坐標
s = height, # 文本
ha = 'center') # 水平居中
set_label(rects1)
set_label(rects2)
# 設定緊湊布局
plt.tight_layout()

1.3 極坐標圖
1.3.1 線性極坐標
🚩對于極坐標,我們先來繪制一個普通的直角坐標系下的直線
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 4 * np.pi, 200)
y = np.linspace(0, 2, 200)
plt.plot(x, y)

我們對上述代碼加上一行代碼后,就可以轉為極坐標:
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 4 * np.pi, 200)
y = np.linspace(0, 2, 200)
plt.subplot(111, projection = 'polar')
plt.plot(x, y)

接下來,為了讓這個極坐標圖更加的美觀,我們對其屬性進行一些設定:
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 4 * np.pi, 200)
y = np.linspace(0, 2, 200)
ax = plt.subplot(111, projection = 'polar', facecolor = 'lightgreen')
plt.plot(x, y)
# 設定
ax.set_rmax(3) # 最大半徑設定為3
ax.set_rticks([0.5, 1, 1.5, 2]) # 設定刻度
ax.grid(True) # 設定網格線
1.3.2 條形極坐標
import numpy as np
import matplotlib.pyplot as plt
# 分成8份 (0~360)
N = 8
# 橫坐標
x = np.linspace(0.0, 2 * np.pi, N, endpoint = False)
# 縱坐標
y = np.random.randint(3, 15, size = N)
# 寬度(8個柱子沾滿圓)
width = np.pi / 4
# 8個柱子隨機生成顏色
colors = np.random.rand(8,3)
# polar表示極坐標
ax = plt.subplot(111, projection = 'polar')
ax.bar(x, y, width = width, color = colors)

1.4 直方圖
🚩繪制的直方圖其實就是一個概率分布,直方圖可以看成很多個柱子的柱狀圖
import numpy as np
import matplotlib.pyplot as plt
mu = 100 # 平均值
sigma = 15 # 標準差
x = np.random.normal(loc = mu, scale = 15, size = 10000)
fig, ax = plt.subplots()
# 直方圖一般用于描述統計性的資料
# 資料量比較大,通過繪制直方圖,看出資料內部的關系
# density = True 統計的是概率
# density = False 統計數字在某個范圍內的次數
n, bins, patches = ax.hist(x, 200, density = True) # 直方圖
# 概率密度函式
y = ((1 / (np.sqrt(2 * np.pi) * sigma)) *
np.exp(-0.5 * (1 / sigma * (bins - mu)) ** 2))
plt.plot(bins, y, '--')
plt.xlabel('Smarts')
plt.ylabel('Probability density')
plt.title(r'Histogram of IQ: $\mu=100$, $\sigma=15$')
# 緊湊布局
fig.tight_layout()

1.5 箱形圖
import numpy as np
import matplotlib.pyplot as plt
# 正態分布
data = np.random.normal(size = (500, 4))
lables = ['A', 'B', 'C', 'D']
# 用Matplotlib畫箱線圖
# 黃色的線就是中位數,紅色的圓點是例外值
_ = plt.boxplot(data, 1, 'ro', labels = lables)

1.6 散點圖
import numpy as np
import matplotlib.pyplot as plt
data = np.random.randn(100, 2)
s = np.random.randint(100, 300, size = 100)
color = np.random.randn(100)
plt.scatter(data[:, 0], # 橫坐標
data[:, 1], # 縱坐標
s = s, # 尺寸
c = color, # 顏色
alpha = 0.5) # 透明度

1.7 餅圖
1.7.1 一般餅圖
import numpy as np
import matplotlib.pyplot as plt
# 解決中文字體亂碼的問題
plt.rcParams['font.sans-serif'] = 'KaiTi'
labels = ["五星", "四星", "三星", "二星", "一星"] # 標簽
percent = [95, 261, 105, 30, 9] # 某市星級酒店數量
# 設定圖片大小和解析度
fig = plt.figure(figsize = (5, 5), dpi = 120)
# 偏移中心量,突出某一部分
# 0.1 表示 10%,自身高度的10%,是一個相對值
explode = (0, 0.1, 0, 0, 0)
# 繪制餅圖:autopct顯示百分比,這里保留一位小數;shadow控制是否顯示陰影
_ = plt.pie(x = percent, # 資料
explode = explode, # 偏移中心量
labels = labels, # 顯示標簽
autopct = '%0.1f%%', # 顯示百分比
shadow = True) # 陰影,3D效果

1.7.2 甜甜圈
import numpy as np
import matplotlib.pyplot as plt
plt.figure(figsize = (6, 6))
# 甜甜圈原料
recipe = ["225g flour",
"90g sugar",
"1 egg",
"60g butter",
"100ml milk",
"1/2package of yeast"]
# 原料比例
data = [225, 90, 50, 60, 100, 5]
wedges, texts = plt.pie(data, startangle = 40)
bbox_props = dict(boxstyle = "square,pad=0.3", fc = "w", ec = "k", lw = 0.72)
kw = dict(arrowprops = dict(arrowstyle = "-"),
bbox = bbox_props, va = "center")
for i, p in enumerate(wedges):
ang = (p.theta2 - p.theta1) / 2. + p.theta1 # 角度計算
# 角度轉弧度----->弧度轉坐標
y = np.sin(np.deg2rad(ang))
x = np.cos(np.deg2rad(ang))
ha = {-1 : "right", 1 : "left"}[int(np.sign(x))] # 水平對齊方式
connectionstyle = "angle,angleA=0,angleB={}".format(ang) # 箭頭連接樣式
kw["arrowprops"].update({"connectionstyle" : connectionstyle}) # 更新箭頭連接方式
plt.annotate(recipe[i], xy=(x, y), xytext = (1.35 * np.sign(x), 1.4 * y),
ha = ha, **kw, fontsize = 18, weight = 'bold')
plt.title("Matplotlib bakery: A donut", fontsize = 18, pad = 25)
plt.tight_layout()

1.8 熱力圖
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
# 標簽
vegetables = ["cucumber", "tomato", "lettuce", "asparagus", "potato", "wheat", "barley"]
farmers = list('ABCDEFG')
# 創建資料,亂數
harvest = np.random.randn(7, 7) * 5 # 農民豐收資料
plt.rcParams['font.size'] = 18
plt.rcParams['font.weight'] = 'heavy'
plt.figure(figsize = (9, 9))
# imshow() 顯示圖片,因為數值不同,所以圖片顏色不同
im = plt.imshow(harvest)
plt.xticks(np.arange(len(farmers)), farmers, rotation = 45, ha = 'right')
plt.yticks(np.arange(len(vegetables)), vegetables)
# 繪制文本
for i in range(len(vegetables)):
for j in range(len(farmers)):
text = plt.text(j, i, round(harvest[i, j], 1),
ha = "center", va = "center", color = 'r')
plt.title("Harvest of local farmers (in tons/year)", pad = 20)

1.9 面積圖
import matplotlib.pyplot as plt
plt.figure(figsize = (9, 6))
days = [1, 2, 3, 4, 5]
sleeping = [7, 8, 6, 11, 7]
eating = [2, 3, 4, 3, 2]
working = [7, 8, 7, 2, 2]
playing = [8, 5, 7, 8, 13]
plt.stackplot(days, sleeping, eating, working, playing)
plt.xlabel('x')
plt.ylabel('y')
plt.title('Stack Plot', fontsize = 18)
plt.legend(['Sleeping', 'Eating', 'Working', 'Playing'],
fontsize = 18)

1.10 蜘蛛圖
import numpy as np
import matplotlib.pyplot as plt
# 畫圖資料
plt.rcParams['font.family'] = 'KaiTi'
labels = np.array(["個人能力", "IQ", "服務意識",
"團隊精神", "解決問題能力", "持續學習"])
y = [83, 61, 95, 67, 76, 88]
x = np.linspace(0, 2 * np.pi, len(labels), endpoint = False)
# 首位相接,我們要把 "持續學習" 和 "個人能力相連起來"
y = np.concatenate((y, [y[0]])) # 首尾相接
x = np.concatenate((x, [x[0]])) # 首尾相接
# 用Matplotlib畫蜘蛛圖
fig = plt.figure(figsize = (6, 6))
ax = fig.add_subplot(111, polar = True)
# 連線
# o:表示形狀,圓形
# -:表示實線
# o-:屬性連用
ax.plot(x, y, 'o-', linewidth = 2)
ax.fill(x, y, alpha = 0.25) # 填充顏色
# 設定角度
ax.set_thetagrids(x[:-1] * 180 / np.pi,# 角度值
# 由于首位相接時候相當于給x增加了一個元素,現在需要切片去掉這個元素
labels,
fontsize = 18)
_ = ax.set_rgrids([20, 40, 60, 80], fontsize = 18)

2.3D圖形
2.1 三維折線圖
🚩創建一個三維空間有兩種方法:
方法一:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d.axes3d import Axes3D # 3D引擎
plt.rcParams['font.family'] = 'KaiTi'
plt.rcParams['axes.unicode_minus'] = False
x = np.linspace(0, 60, 300)
y = np.sin(x)
z = np.cos(x)
fig = plt.figure(figsize = (9, 6)) # 二維圖形
ax3 = Axes3D(fig) # 二維變成了三維
ax3.plot(x, y, z) # 3維折線圖
ax3.set_xlabel('X')
ax3.set_ylabel('Y')
ax3.set_zlabel('Z')

方法二:
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams['font.family'] = 'KaiTi'
plt.rcParams['axes.unicode_minus'] = False
x = np.linspace(0, 60, 300)
y = np.sin(x)
z = np.cos(x)
fig = plt.figure(figsize = (9, 6))
ax3 = plt.subplot(111, projection = '3d')
ax3.plot(x, y, z)
ax3.set_xlabel('X')
ax3.set_ylabel('Y')
ax3.set_zlabel('Z')

如果你覺得這個視角不好看,我們還可以調整視角:
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams['font.family'] = 'KaiTi'
plt.rcParams['axes.unicode_minus'] = False
x = np.linspace(0, 60, 300)
y = np.sin(x)
z = np.cos(x)
fig = plt.figure(figsize = (9, 6))
ax3 = plt.subplot(111, projection = '3d')
ax3.plot(x, y, z)
ax3.set_xlabel('X')
ax3.set_ylabel('Y')
ax3.set_zlabel('Z')
# 圖形可以調整角度
# 第一個引數是 x,y軸的角度,第二個引數是z軸的角度
ax3.view_init(elev = 30, azim = -80)

2.2 三維散點圖
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams['font.family'] = 'KaiTi'
plt.rcParams['axes.unicode_minus'] = False
x = np.linspace(0, 60, 300)
y = np.sin(x)
z = np.cos(x)
fig = plt.figure(figsize = (9, 6))
ax3 = plt.subplot(111, projection = '3d')
ax3.set_xlabel('X')
ax3.set_ylabel('Y')
ax3.set_zlabel('Z')
# 散點圖
x = np.random.randint(0, 60, size = 20)
y = np.random.randn(20)
z = np.random.randn(20)
ax3.scatter(x, y, z, color = 'red')

2.3 三維柱狀圖
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d.axes3d import Axes3D # 3D引擎
month = np.arange(1, 5)
# 每個月 4周 每周都會產生資料
# 三個維度:月、周、銷量
fig = plt.figure(figsize = (9, 6))
ax3 = Axes3D(fig)
for m in month:
# 每個月都要繪制條形圖
ax3.bar(np.arange(1, 5), # 橫坐標
np.random.randint(1, 10, size = 4), # 縱坐標
zs = m ,
zdir = 'x', # 在哪個方向上,一排排排列,默認為'z'
alpha = 0.7, # alpha 透明度
width = 0.5) # 條形圖的寬度
plt.rcParams['font.family'] = 'KaiTi'
ax3.set_xlabel('月份', fontsize = 18, color = 'red')
ax3.set_xticks(month)
ax3.set_ylabel('周', fontsize = 18, color = 'red')
ax3.set_yticks([1, 2, 3, 4])
ax3.set_zlabel('銷量', fontsize = 18, color = 'green')

3.Seaborn
Seaborn是基于matplotlib的圖形可視化python包,它提供了一種高度互動式界面,便于用戶能夠做出各種有吸引力的統計圖表,
Seaborn是在matplotlib的基礎上進行了更高級的API封裝,從而使得作圖更加容易,在大多數情況下使用seaborn能做出很具有吸引力的圖,而使用matplotlib就能制作具有更多特色的圖,應該把Seaborn視 為matplotlib的補充,而不是替代物,
1.安裝
如果你讀過文章:matplotlib的安裝教程以及簡單呼叫,那么你只需要在命令列模式中輸入:pip install seaborn即可進行安裝,否則你也可以直接輸入:pip install seaborn -i https://pypi.tuna.tsinghua.edu.cn/simple
進入命令列模式: W i n d o w s Windows Windows系統:按下鍵盤上的 W i n d o w s + R Windows + R Windows+R,輸入 c m d cmd cmd 后即可進入
如果你讀過文章:最詳細的Anaconda Installers 的安裝【numpy,jupyter】(圖+文),那么你無序再安裝 S e a b o r n Seaborn Seaborn,安裝 A n a c o n d a Anaconda Anaconda 的時候已經安裝好了 S e a b o r n Seaborn Seaborn

出現上圖所示就是已經安裝過的意思,我們可以打開 jupyter 運行如下代碼,看是否報錯:
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
不報錯即為安裝成功,那么接下來,就讓我來介紹 s e a b o r n seaborn seaborn
2.快速上手
2.1 模式設定
import seaborn as sns
sns.set(style = 'darkgrid',context = 'talk',font = 'STKaiti')
s t y l e style style設定,修改主題風格,屬性如下:
| style | 效果 |
|---|---|
| darkgrid | 黑色網格(默認) |
| whitegrid | 白色網格 |
| dark | 黑色背景 |
| white | 白色背景 |
| ticks | 四周有刻度線的白背景 |
c o n t e x t context context設定,修改大小,屬性如下:
| context | 效果 |
|---|---|
| paper | 越來越大越來越粗 |
| notebook(默認) | 越來越大越來越粗 |
| talk | 越來越大越來越粗 |
| poster | 越來越大越來越粗 |
2.2 線形圖
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
sns.set(style = 'dark',context = 'poster',font = 'STKaiti') # 設定樣式
plt.figure(figsize = (9, 6))
x = np.linspace(0, 2 * np.pi, 20)
y = np.sin(x)
sns.lineplot(x = x, y = y, color = 'green', ls = '--')
sns.lineplot(x = x, y = np.cos(x), color = 'red',ls = '-.')

3.各種圖形繪制
首先我們需要下載幾個 c s v csv csv 檔案:
鏈接: https://pan.baidu.com/s/12CkTweXPT-El4z2M93HltQ?pwd=vaks
提取碼: vaks
下載完成之后,把該檔案和我們的代碼放到同一個檔案夾下,這一操作我們在之前的博客中已經反復說到,這里就不再進行演示
3.1 調色板
引數 p a l e t t e palette palette(調色板),用于調整顏色,系統默認提供了六種選擇: d e e p , m u t e d , b r i g h t , p a s t e l , d a r k , c o l o r b l i n d deep, muted, bright, pastel, dark, colorblind deep,muted,bright,pastel,dark,colorblind
引數
p
a
l
e
t
t
e
palette
palette調色板,可以有更多的顏色選擇,
M
a
t
p
l
o
t
l
i
b
Matplotlib
Matplotlib為我們提供了多達
178
178
178種,這足夠繪圖用,可以通過代碼print(plt.colormaps())查看選擇
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
print(plt.colormaps())

3.2 線形圖
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
# 設定樣式
sns.set(style = 'dark', context = 'notebook', font = 'STKaiti')
plt.figure(figsize = (9, 6))
# fmri 這一核磁共振資料
fmri = pd.read_csv('./fmri.csv')
ax = sns.lineplot(x = 'timepoint',y = 'signal',
hue = 'event', # 根據 event 進行分類繪制
style = 'event', # 根據 event 屬性分類指定樣式
# 如圖自動分配成了實作和虛線,●和×
data = fmri,
palette = 'deep', # 畫板、顏色
markers = True,
markersize = 10)
plt.xlabel('時間節點',fontsize = 30)

3.3 散點圖
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
data = pd.read_csv('./tips.csv') # 小費
plt.figure(figsize = (9, 6))
sns.set(style = 'darkgrid', context = 'talk')
# 散點圖
fig = sns.scatterplot(x = 'total_bill', y = 'tip',
hue = 'time', data = data,
palette = 'autumn', s = 100)

3.4 柱狀圖
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
plt.figure(figsize = (9, 6))
sns.set(style = 'whitegrid')
tips = pd.read_csv('./tips.csv') # 小費
ax = sns.barplot(x = "day", y = "total_bill",
data = tips,hue = 'sex',
palette = 'colorblind',
capsize = 0.2)

3.5 箱式圖
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
sns.set(style = 'ticks')
tips = pd.read_csv('./tips.csv')
ax = sns.boxplot(x = "day", y = "total_bill", data = tips, palette = 'colorblind')

3.6 直方圖
import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt
sns.set(style = 'dark')
x = np.random.randn(5000)
sns.histplot(x, kde = True)

import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
sns.set(style = 'darkgrid')
tips = pd.read_csv('./tips.csv')
sns.histplot(x = 'total_bill', data = tips, kde = True)

3.7 分類散點圖
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
sns.set(style = 'darkgrid')
exercise = pd.read_csv('./exercise.csv')
sns.catplot(x = "time", y = "pulse", hue = "kind", data = exercise)

3.8 熱力圖
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
plt.figure(figsize = (12, 9))
flights = pd.read_csv('./flights.csv') # 飛行資料
# pivot() 實作了資料重塑,改變了DataFrame的形狀
# month 作為行索引,year作為列索引,passengers作為資料
flights = flights.pivot("month", "year", "passengers") # 年,月,乘客
sns.heatmap(flights, annot = True, # 畫上數值
fmt = 'd', # 數值為整數
cmap = 'RdBu_r', # 設定顏色
linewidths = 0.5) # 線寬為 0.5

我們最后來說一下資料重塑,在本題的基礎上,我們查看一下我們的
f
l
i
g
h
t
s
flights
flights 資料:

咋們再來重新加載一下資料,看看原始的
f
l
i
g
h
t
s
flights
flights 資料:
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
flights = pd.read_csv('./flights.csv')
flights

不難看出,上述繪圖程序中涉及到了資料重塑:代碼:flights = flights.pivot("month", "year", "passengers")實作了資料的重塑,使得
m
o
n
t
h
month
month 作為行索引,
y
e
r
r
yerr
yerr 作為列索引,
p
a
s
s
e
n
g
e
r
s
passengers
passengers 作為資料,
4.訓練場
4.1 資料處理
- 加載資料,并查看相關資訊:基金總資料條目,基金公司數量,基金總數量,基金總規模,查看前五條資料
- 將基金規模小于1億元的資料過濾掉,將基金收益沒有資料的過濾掉,
- 將基金規模和基金收益轉換為浮點數,并將處理好的資料保存,
首先我們需要下載一個 Excel 檔案:
鏈接: https://pan.baidu.com/s/1j2pn0vVN3-wJmSZ-01oiUg?pwd=niye
提取碼: niye
下載完成之后,把該檔案和我們的代碼放到同一個檔案夾下,這一操作我們在之前的博客中已經反復說到,這里就不再進行演示
資料查看:
import numpy as np
import pandas as pd
fund = pd.read_excel('./fund.xlsx')
print('基金總資料條目:', fund.shape)
print('基金公司一共有:', fund['公司'].nunique()) # 去重
print('基金總數量是:', fund['基金數量'].sum())
# 計算基金總規模
cnt = fund['基金規模'].str.endswith('億元') # 判斷是否以'億元'結尾
fund2 = fund[cnt] # 資料篩選
size = fund2['基金規模'].str[: -2].astype('float').sum() # 去掉'億元'
print('基金總規模是:%0.2f億元' % (size))
print('查看前五條資料:')
fund.head(5)

資料清洗:
import pandas as pd
fund = pd.read_excel('./fund.xlsx')
print('資料清洗前:', fund.shape)
# 過濾基金規模為空的資料
cnt = fund['基金規模'].str.endswith('億元')
fund = fund[cnt]
# 過濾基金規模小于1億的資料
cnt2 = fund['基金規模'].str[: -2].astype('float') > 1
fund = fund[cnt2]
# 過濾基金收益為空的資料
cnt3 = fund['基金收益'].str.endswith('%')
fund = fund[cnt3]
print('資料清洗后:', fund.shape)
fund.to_excel('./fund_clean.xlsx', index = False)
fund.head()

資料轉換:
import pandas as pd
fund = pd.read_excel('./fund_clean.xlsx')
# 基金規模字串轉變為浮點數
fund['基金規模'] = fund['基金規模'].str[: -2].astype('float')
# 基金收益字串轉變為浮點數
def convert(x):
x = x[: -1]
x = float(x)
return x
fund['基金收益'] = fund['基金收益'].apply(convert)
# 修改列名
fund.columns = ['姓名', '公司', '基金數量', '年', '天', '基金規模(億元)', '基金收益(%)']
# 資料保存
fund.to_excel('./fund_end.xlsx', index = False)
fund.head(10)

4.2 資料挖掘與可視化
根據基金總規模,進行排序,水平條形圖展示前十大公司
根據收益率,對所有資料進行降序排名,繪制前十佳基金經理,并將金額和收益率繪制到圖片中,
十大基金公司:
%%time
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
plt.figure(figsize = (12, 9))
sns.set_theme(style = 'darkgrid', context = 'talk', font = 'KaiTi')
fund = pd.read_excel('./fund_end.xlsx')
# 分組聚合
com = fund.groupby(by = '公司')[['基金規模(億元)']].sum()
# 排序
com.sort_values(by = '基金規模(億元)',
ascending = False, # 降序排序
inplace = True) # 直接對原資料進行替換
# 行索引重置:變成自然數索引
com.reset_index(inplace = True)
# 畫條形圖
sns.barplot(x = '基金規模(億元)', y = '公司', # x軸和y軸
data = com.iloc[: 10], # 切片出來前十個
orient = 'h') # 水平條形圖

收益十佳基金經理:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
plt.figure(figsize = (12, 9))
sns.set_theme(style = 'darkgrid', context = 'talk', font = 'STKaiti')
fund = pd.read_excel('./fund_end.xlsx')
# 降序排序并直接替換原資料
fund.sort_values(by = '基金收益(%)', ascending = False, inplace = True)
sns.barplot(x = '基金收益(%)', y = '姓名',
data = fund.iloc[:10], orient = 'h',
palette = 'Set1') # 畫板、顏色
for i in range(10):
rate = fund.iloc[i]['基金收益(%)']
pe = fund.iloc[i]['基金規模(億元)']
# 繪制基金規模
plt.text(x = rate / 2, y = i, s = str(pe) + '億元', ha = 'center', va = 'center')
# 繪制基金收益
plt.text(x = rate + 50, y = i, s = str(rate) + '%', va = 'center')
_ = plt.xlim(0, 2500) # 橫坐標范圍
_ = plt.xticks(np.arange(0, 2500, 200)) # 橫坐標刻度

轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/421407.html
標籤:AI
下一篇:大資料分析那點事
