Voronoi diagram gives unexpected results in scipy

80 Views Asked by At

I have the following pandas dataframe:

import pandas as pd
pd.DataFrame({'cl': {0: 'A', 1: 'C', 2: 'H', 3: 'M', 4: 'S'},
 'd': {0: 245.059986986012,
  1: 320.49044143557785,
  2: 239.79023081978914,
  3: 263.38325791238833,
  4: 219.53334398353175},
 'p': {0: 10.971011721360075,
  1: 10.970258360366753,
  2: 13.108487516946218,
  3: 12.93241352743668,
  4: 13.346107628161008}})

    cl  d           p
0   A   245.059987  10.971012
1   C   320.490441  10.970258
2   H   239.790231  13.108488
3   M   263.383258  12.932414
4   S   219.533344  13.346108

I want to create a Voronoi diagram. To do so I am using the package from scipy.

I am using the following code:

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

centers2 = np.array(
    centers_dt[['d', 'p']]
)

scatter_x = np.array(centers_dt['d'])
scatter_y = np.array(centers_dt['p'])
group = np.array(centers_dt['cl'])
cdict = {'C': 'red', 'A': 'blue', 'H': 'green', 'M': 'yellow', 'S': 'black'}

fig, ax = plt.subplots()
for g in np.unique(group):
    ix = np.where(group == g)
    ax.scatter(scatter_x[ix], scatter_y[ix], c = cdict[g], label = g, s = 100)
ax.legend()

vor = Voronoi(centers2)
fig = voronoi_plot_2d(vor,plt.gca())

plt.show()
plt.close()

But the result I am getting is unexpected:

enter image description here

Since there is a boarder missing plus the boarders seem a bit off.

Any ideas ?

1

There are 1 best solutions below

0
Warren Weckesser On

The code in voronoi_plot_2d draws segments with finite length, even for borders that should extend to infinity. It is possible that with the default axis limits chosen by voronoi_plot_2d, a border segment doesn't appear in the plot, because the finite length chosen by vorono_plot_2d is too small for it to extend into the displayed window.

Here's the plot that I get from your code if I add plt.ylim(-400, 400).
enter image description here

Note that the dashed line extending upwards from the lowest intersection point should continue upwards to infinity, but the code draws only a finite segment.

Also note that the axis scales are not equal, so the dividing lines between points appear to be not perpendicular to the lines that would connect the points. Here's the plot with equal axis scales:

enter image description here