I have a scatter plot and many contour plots. There are many contours,some closed some not. How can I identify the values of the largest closed contour from [this].1
Asked
Active
Viewed 459 times
2
-
How do you define how large a closed contour is? Largest distance between any two points? Length? – jmetz Jul 07 '16 at 16:41
-
the largest peripheral distance – user6457831 Jul 07 '16 at 18:32
1 Answers
3
Finding the biggest closed contour can be done as follows; note though that this assumes that by "biggest" you meant largest point-to-point distance.
Other size metrics could be easily substituted in though.
Note also that if you use the extend3d=True
version, you would need to manipulate the Poly3DCollection
that get's created which is a little more tricky.
from mpl_toolkits.mplot3d import axes3d, art3d
import matplotlib.pyplot as plt
from matplotlib import cm
from scipy.spatial import distance_matrix
import numpy as np
fig = plt.figure()
ax = fig.gca(projection='3d')
X, Y, Z = axes3d.get_test_data(0.05)
cset = ax.contour(X, Y, Z, cmap=cm.coolwarm)
ax.clabel(cset, fontsize=9, inline=1)
maxsize = 0
# Iterate over all the contour segments and find the largest
for i, segs in enumerate(cset.allsegs):
for j, seg in enumerate(segs):
# First make sure it's closed
if (seg[0]-seg[-1]).any():
continue
# Now get it's size
size = distance_matrix(seg, seg).max()
if size > maxsize:
maxsize = size
maxseg = (i, j)
# Now highlight the "biggest" closed contour
cset.collections[maxseg[0]].set_color('y')
cset.collections[maxseg[0]].set_lw(5)
pts2d = cset.allsegs[maxseg[0]][maxseg[1]]
z = cset.levels[maxseg[0]]
coords = np.c_[ pts2d, z*np.ones(pts2d.shape[0]) ]
print(coords)
plt.show()
This results in:

jmetz
- 12,144
- 3
- 30
- 41
-
thanks @jmetz. Is there a chance to get the datapoints in this contour. .I mean x,y,z co-ordinates? – user6457831 Jul 07 '16 at 18:30
-
1np - data points are contained in the `seg` variables (they're 2d) and the z value is in the corresponding element of `cset.levels`. – jmetz Jul 07 '16 at 21:57
-
1I've updated the code to store them as `x,y,z` in the variable `coords`. – jmetz Jul 07 '16 at 22:04
-
@user6457831 - don't forget to accept the answer if you're happy with it ;) – jmetz Jul 07 '16 at 22:16
-
.Sure I was actually waiting to get this . Thanks a lot.Great work.Keep going – user6457831 Jul 08 '16 at 03:29
-
Just to know ,can we also find the largest contour by "AREA" ??? Now its point to point distance. @jmetz – user6457831 Jul 08 '16 at 13:34
-
1@user6457831 - you could add in a polygon area calculation, e.g. `def PolyArea(x,y): return 0.5*np.abs(np.dot(x,np.roll(y,1))-np.dot(y,np.roll(x,1)))` from http://stackoverflow.com/a/30408825/537098 – jmetz Jul 08 '16 at 14:03