一.散點(diǎn)圖

  • 在Python中進(jìn)行可視化,我們需要的是這些庫(kù):

    • matplotlib:python中自帶的,也是最常用的可視化工具包,在Jupyter中甚至可以找到matplotlib的網(wǎng)站
    • seaborn:python中可視化的新起之秀,致力于統(tǒng)計(jì)數(shù)據(jù)可視化
    • brewer2mpl:brewer2mpl是一個(gè)專(zhuān)供python使用的,用于訪問(wèn)colorbrewer2色譜的工具,colorbrewer2是一個(gè)專(zhuān)業(yè)顏色顧問(wèn)公司。
  • 假設(shè)我有一個(gè)數(shù)據(jù)探索,我想了解下人口和面積的關(guān)系,是不是面積越大,人口數(shù)量就是越大?還是面積在一個(gè)指定的區(qū)間內(nèi),人口數(shù)量才是最多的,如果是,那么這個(gè)區(qū)間是多少呢?對(duì)于下圖,我們是如何畫(huà)出來(lái)的呢?[圖片上傳失敗...(image-b35bd1-1587003130440)]
    2020041501.png
# 查看必要庫(kù)的版本
import sys
import matplotlib as mlp
import seaborn as sns
import brewer2mpl 


print(mlp.__version__)
print(sns.__version__)
print(sys.version)

散點(diǎn)圖

  • 散點(diǎn)圖是用于觀測(cè)兩兩變量祝賀構(gòu)成的相關(guān)關(guān)系的直觀展現(xiàn),從圖中我們可以看出兩變量的相關(guān)性及其中的線性或非線性的變化規(guī)律。
  • 常用的畫(huà)散點(diǎn)圖函數(shù)scatte()
# 導(dǎo)入需要的繪圖

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

# 解決中文顯示問(wèn)題
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
#繪制超簡(jiǎn)單的散點(diǎn)圖:變量x1與x2的關(guān)系

#定義橫軸和縱軸數(shù)據(jù)
x1 = np.random.randn(10)
x2 = x1 + x1**2 - 10

#確定畫(huà)布,參數(shù)figsize(width, height)
plt.figure(figsize=(8,3))

#繪圖
plt.scatter(x1,x2,                    # 橫坐標(biāo),縱坐標(biāo)
            s=50,                    # 數(shù)據(jù)點(diǎn)的尺寸大小
            c="red",                # 數(shù)據(jù)點(diǎn)的顏色
            label = "Red Points"   # 標(biāo)簽
           )

#裝飾圖形
plt.legend() #顯示圖例,和scatter函數(shù)的label參數(shù)標(biāo)簽聯(lián)用
plt.show() #讓圖形顯示
2020041502.png
# 如果我們希望顯示多種顏色的散點(diǎn)圖,并且這個(gè)顏色是我們的標(biāo)簽y所代表的分類(lèi)
# 思路:每次畫(huà)同類(lèi)標(biāo)簽的散點(diǎn)圖


#確立顏色列表
colors = ["red","black"]
#確立標(biāo)簽的類(lèi)別列表
labels = ["負(fù)樣本","正樣本"] 

for i in range(2):
    plt.scatter(X[y==i,0],   # 橫坐標(biāo)
                X[y==i,1],   # 縱坐標(biāo)
                c=colors[i], # 顏色
                label = labels[i])
plt.legend()
plt.show()
2020041503.png
# 如何畫(huà)一張多分類(lèi)的散點(diǎn)圖呢?

#導(dǎo)入數(shù)據(jù)
midwest = pd.read_csv("https://raw.githubusercontent.com/selva86/datasets/master/midwest_filter.csv")

#探索數(shù)據(jù)
print(midwest.shape)
print(midwest.columns)

midwest.head(3)
# 豐富我們的圖像

# 預(yù)設(shè)圖像的各種屬性
large = 22; med = 16; small = 12
params = {'axes.titlesize': large,           #子圖上的標(biāo)題字體大小
          'legend.fontsize': med,           #圖例的字體大小
          'figure.figsize': (16, 10),      #圖像的畫(huà)布大小
          'axes.labelsize': med,          #標(biāo)簽的字體大小
          'xtick.labelsize': med,        #x軸上的標(biāo)尺的字體大小
          'ytick.labelsize': med,       #y軸上的標(biāo)尺的字體大小
          'figure.titlesize': large}   #整個(gè)畫(huà)布的標(biāo)題字體大小
plt.rcParams.update(params)           #設(shè)定各種各樣的默認(rèn)屬性
plt.style.use('seaborn-whitegrid')   #設(shè)定整體風(fēng)格
sns.set_style("white")              #設(shè)定整體背景風(fēng)格


# 準(zhǔn)備標(biāo)簽列表和顏色列表
categories = np.unique(midwest['category'])
colors = [plt.cm.tab10(i/float(len(categories)-1)) for i in range(len(categories))]

# 建立畫(huà)布
plt.figure(figsize=(16, 10),    #繪圖尺寸
           dpi=100,            #圖像分辨率
           facecolor='w',     #圖像的背景顏色,設(shè)置為白色,默認(rèn)也是白色
           edgecolor='k'     #圖像的邊框顏色,設(shè)置為黑色,默認(rèn)也是黑色
          )

# 循環(huán)繪圖
# 我們可以輸入橫縱坐標(biāo),也可以輸入橫縱坐標(biāo)的名字,然后使用data這個(gè)參數(shù)來(lái)傳入全數(shù)據(jù)集
for i, category in enumerate(categories):
    plt.scatter('area', 'poptotal', 
                data=midwest.loc[midwest.category==category, :], 
                s=20, 
                c=np.array(colors[i]).reshape(1,-1), 
                # c=np.array(plt.cm.tab10(i/len(categories))).reshape(1,-1),
                label=str(category))


# 對(duì)圖像進(jìn)行裝飾
# plt.gca() 獲取當(dāng)前的子圖,如果當(dāng)前沒(méi)有任何子圖的話(huà),就幫我創(chuàng)建一個(gè)新的子圖
plt.gca().set(xlim=(0, 0.12), ylim=(0, 80000)) #控制橫縱坐標(biāo)的范圍
plt.xticks(fontsize=12)                       #坐標(biāo)軸上的標(biāo)尺的字的大小
plt.yticks(fontsize=12)
plt.ylabel('Population',fontsize=22)         # 坐標(biāo)軸上的標(biāo)題和字體大小
plt.xlabel('Area',fontsize=22)
plt.title("Scatterplot of Midwest Area vs Population", fontsize=22) #整個(gè)圖像的標(biāo)題和字體的大小
plt.legend(fontsize=12)                    #圖例的字體大小
plt.show()
2020041501.png
# 分析數(shù)據(jù)

plt.figure(figsize=(16, 10),     # 繪圖尺寸
           dpi=60,               # 圖像分辨率
           facecolor='w',       # 圖像的背景顏色,設(shè)置為白色,默認(rèn)也是白色
           edgecolor='k'       # 圖像的邊框顏色,設(shè)置為黑色,默認(rèn)也是黑色
          )

#進(jìn)行循環(huán)繪圖
for i, category in enumerate(categories):
    plt.scatter('area', 'poptotal', 
                data=midwest.loc[midwest.category==category, :],
                s=20, c=np.array(plt.cm.tab10(i/float(len(categories)-1))).reshape(1,-1),label=str(category))

#高學(xué)歷,低貧困的地方
plt.scatter("area","poptotal",
           data = midwest.loc[midwest.category == "HLU",:],
            s=300,
            facecolors="None",  # 點(diǎn)的填充顏色
            edgecolors="red",   # 點(diǎn)的邊框顏色
            label = "Selected")

#對(duì)圖像進(jìn)行裝飾
plt.gca().set(xlim=(0.0, 0.12), ylim=(0, 90000)) #控制橫縱坐標(biāo)的范圍
plt.xticks(fontsize=12) #坐標(biāo)軸上的標(biāo)尺的字的大小
plt.yticks(fontsize=12)
plt.ylabel('Population',fontsize=22) #坐標(biāo)軸上的標(biāo)題和字體大小
plt.xlabel('Area',fontsize=22)
plt.title("Scatterplot of Midwest Area vs Population", fontsize=22) #整個(gè)圖像的標(biāo)題和字體的大小
plt.legend(fontsize=12) #圖例的字體大小
plt.show()
2020041504.png
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容