当前位置: 首页 > 工具软件 > Colorize > 使用案例 >

Python 泰森图上色 Colorize Voronoi Diagram Template

邹宏峻
2023-12-01

Stackoverflow

Colorize Voronoi Diagram

IPython Cookbook, Second Edition (2018)

14.5. Computing the Voronoi diagram of a set of points

template

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.spatial import Voronoi, voronoi_plot_2d

def normalizer(dataArray):
    if dataArray.max() - dataArray.min() == 0:
        return dataArray
    return (dataArray-dataArray.min())/(dataArray.max() - dataArray.min())

def comparisionPlot(columnName0, columnName1, hueColumn, dataDf):
    # add 4 distant dummy points to help coloring the edge
    # dataPoints = np.append((dataDfNormalized)[['P-MEAN', 'RANK']], [[2,2], [-2,2], [2,-2], [-2,-2]], axis = 0)

    # normal version
    dataPoints = dataDf[[columnName0, columnName1]]

    # plot Voronoi diagrame
    vor = Voronoi(dataPoints)
    voronoi_plot_2d(vor, show_vertices = True, point_size = 2)

    # color list 
    colorList = []
    for regionIndex in range(len(vor.regions)):
        if not -1 in vor.regions[regionIndex]:
            polygon = [vor.vertices[i] for i in vor.regions[regionIndex]]
            if len(polygon) == 0:
                colorList += colorList[-1:]
                continue
            colorList += [np.array(polygon).transpose().min()]
        colorList += colorList[-1:]
    colorList = normalizer(np.array(colorList))

    # colorize
    for regionIndex in range(len(vor.regions)):
        if not -1 in vor.regions[regionIndex]:
            polygon = [vor.vertices[i] for i in vor.regions[regionIndex]]
            plt.fill(*zip(*polygon),color=np.repeat(colorList[regionIndex],3))

    # fix the range of axes
    plt.xlim([-0.2,1.2]), plt.ylim([-0.2,1.2])

    plt.show()

Question answering

  1. What is the *zip in line 38

    *zip() 函数是 zip() 函数的逆过程,将 zip 对象变成原先组合前的数据。

    zip(*iterables)
    *zip(*iterables)
    
  2. What is the *polygon in line 38

    Change polygon from interator to iterable.

 类似资料: