Stackoverflow

Colorize Voronoi Diagram

https://stackoverflow.com/questions/20515554/colorize-voronoi-diagram/20678647#20678647

IPython Cookbook, Second Edition (2018)

14.5. Computing the Voronoi diagram of a set of points

https://ipython-books.github.io/145-computing-the-voronoi-diagram-of-a-set-of-points/

template

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
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 对象变成原先组合前的数据。

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

    Change polygon from interator to iterable.