首頁 > 軟體

python視覺化分析繪製散點圖和邊界氣泡圖

2022-06-23 22:00:27

一、繪製散點圖

實現功能:

python繪製散點圖,展現兩個變數間的關係,當資料包含多組時,使用不同顏色和形狀區分。

實現程式碼:

import numpy as np
import pandas as pd
import matplotlib as mpl
import matplotlib.pyplot as plt
import seaborn as sns
import warnings
warnings.filterwarnings(action='once')
plt.style.use('seaborn-whitegrid')
sns.set_style("whitegrid")
print(mpl.__version__)
print(sns.__version__)
def draw_scatter(file):
    # Import dataset
    midwest = pd.read_csv(file)
    # Prepare Data
    # Create as many colors as there are unique midwest['category']
    categories = np.unique(midwest['category'])
    colors = [plt.cm.Set1(i / float(len(categories) - 1)) for i in range(len(categories))]
    # Draw Plot for Each Category
    plt.figure(figsize=(10, 6), dpi=100, facecolor='w', edgecolor='k')

    for i, category in enumerate(categories):
        plt.scatter('area', 'poptotal', data=midwest.loc[midwest.category == category, :],s=20,c=colors[i],label=str(category))
    # Decorations
    plt.gca().set(xlim=(0.0, 0.1), ylim=(0, 90000),)
    plt.xticks(fontsize=10)
    plt.yticks(fontsize=10)
    plt.xlabel('Area', fontdict={'fontsize': 10})
    plt.ylabel('Population', fontdict={'fontsize': 10})
    plt.title("Scatterplot of Midwest Area vs Population", fontsize=12)
    plt.legend(fontsize=10)
    plt.show()
draw_scatter("F:資料雜壇datasetsmidwest_filter.csv")

實現效果:

二、繪製邊界氣泡圖

實現功能:

氣泡圖是散點圖中的一種型別,可以展現三個數值變數之間的關係,之前的文章介紹過一般的散點圖都是反映兩個數值型變數的關係,所以如果還想通過散點圖新增第三個數值型變數的資訊,一般可以使用氣泡圖。氣泡圖的實質就是通過第三個數值型變數控制每個散點的大小,點越大,代表的第三維數值越高,反之亦然。而邊界氣泡圖則是在氣泡圖新增第四個類別型變數的資訊,將一些重要的點選出來並連線。

實現程式碼:

import numpy as np
import pandas as pd
import matplotlib as mpl
import matplotlib.pyplot as plt
import seaborn as sns
import warnings
from scipy.spatial import ConvexHull
warnings.filterwarnings(action='once')
plt.style.use('seaborn-whitegrid')
sns.set_style("whitegrid")
print(mpl.__version__)
print(sns.__version__)

def draw_scatter(file):
    # Step 1: Prepare Data
    midwest = pd.read_csv(file)

    # As many colors as there are unique midwest['category']
    categories = np.unique(midwest['category'])
    colors = [plt.cm.Set1(i / float(len(categories) - 1)) for i in range(len(categories))]

    # Step 2: Draw Scatterplot with unique color for each category
    fig = plt.figure(figsize=(10, 6), dpi=80, facecolor='w', edgecolor='k')

    for i, category in enumerate(categories):
        plt.scatter('area','poptotal',data=midwest.loc[midwest.category == category, :],s='dot_size',c=colors[i],label=str(category),edgecolors='black',linewidths=.5)
    # Step 3: Encircling
    # https://stackoverflow.com/questions/44575681/how-do-i-encircle-different-data-sets-in-scatter-plot
    def encircle(x, y, ax=None, **kw):  # 定義encircle函數,圈出重點關注的點
        if not ax: ax = plt.gca()
        p = np.c_[x, y]
        hull = ConvexHull(p)
        poly = plt.Polygon(p[hull.vertices, :], **kw)
        ax.add_patch(poly)
    # Select data to be encircled
    midwest_encircle_data1 = midwest.loc[midwest.state == 'IN', :]
    encircle(midwest_encircle_data1.area,midwest_encircle_data1.poptotal,ec="pink",fc="#74C476",alpha=0.3)
    encircle(midwest_encircle_data1.area,midwest_encircle_data1.poptotal,ec="g",fc="none",linewidth=1.5)
    midwest_encircle_data6 = midwest.loc[midwest.state == 'WI', :]
    encircle(midwest_encircle_data6.area,midwest_encircle_data6.poptotal,ec="pink",fc="black",alpha=0.3)
    encircle(midwest_encircle_data6.area,midwest_encircle_data6.poptotal,ec="black",fc="none",linewidth=1.5,linestyle='--')
    # Step 4: Decorations
    plt.gca().set(xlim=(0.0, 0.1),ylim=(0, 90000),)
    plt.xticks(fontsize=12)
    plt.yticks(fontsize=12)
    plt.xlabel('Area', fontdict={'fontsize': 14})
    plt.ylabel('Population', fontdict={'fontsize': 14})
    plt.title("Bubble Plot with Encircling", fontsize=14)
    plt.legend(fontsize=10)
    plt.show()
draw_scatter("F:資料雜壇datasetsmidwest_filter.csv")

實現效果:

到此這篇關於python視覺化分析繪製散點圖和邊界氣泡圖的文章就介紹到這了,更多相關python繪製內容請搜尋it145.com以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援it145.com!


IT145.com E-mail:sddin#qq.com