i want to get data from a contour of different iso-line. the question matplotlib - extracting data from contour lines gives an example
import matplotlib.pyplot as plt
x = [1,2,3,4]
y = [1,2,3,4]
m = [[15,14,13,12],[14,12,10,8],[13,10,7,4],[12,8,4,0]]
cs = plt.contour(x,y,m, [9.5])
plt.show()
coord = cs.collections[0].get_paths()
it get the coordinates of line with value euqal to 9.5.
now, i need to get the coordinate of multi-isoline from one contour, so i need to change the value to represent different line, but when i use loop, it means python needs to construct the contour at each loop, how can i construct the contour once and then change the value to represent different line?
CodePudding user response:
You can plot several contours at once with plt.contour
by giving a list of the values you wish to contour. Then, you can access them all from the returned ContourSet using cs.allsegs
or by using get_paths
on each item in the cs.collections
list.
For example:
import matplotlib.pyplot as plt
x = [1,2,3,4]
y = [1,2,3,4]
m = [[15,14,13,12],[14,12,10,8],[13,10,7,4],[12,8,4,0]]
cs = plt.contour(x,y,m, [9.5, 10.5, 11.5])
plt.show()
# Option 1: use allsegs
all_coords = cs.allsegs
print(all_coords)
# Option 2: use cs.collections[X].get_paths()
coords1 = cs.collections[0].get_paths()
coords2 = cs.collections[1].get_paths()
coords3 = cs.collections[2].get_paths()
print(coords1)
print(coords2)
print(coords3)
Where the printed coords are then:
Option 1 (allsegs
):
[[array([[4. , 1.625 ],
[3.25 , 2. ],
[3. , 2.16666667],
[2.16666667, 3. ],
[2. , 3.25 ],
[1.625 , 4. ]])],
[array([[4. , 1.375 ],
[3. , 1.83333333],
[2.75 , 2. ],
[2. , 2.75 ],
[1.83333333, 3. ],
[1.375 , 4. ]])],
[array([[4. , 1.125],
[3. , 1.5 ],
[2.25 , 2. ],
[2. , 2.25 ],
[1.5 , 3. ],
[1.125, 4. ]])]]
Option 2 (get_paths()
):
[Path(array([[4. , 1.625 ],
[3.25 , 2. ],
[3. , 2.16666667],
[2.16666667, 3. ],
[2. , 3.25 ],
[1.625 , 4. ]]), array([1, 2, 2, 2, 2, 2], dtype=uint8))]
[Path(array([[4. , 1.375 ],
[3. , 1.83333333],
[2.75 , 2. ],
[2. , 2.75 ],
[1.83333333, 3. ],
[1.375 , 4. ]]), array([1, 2, 2, 2, 2, 2], dtype=uint8))]
[Path(array([[4. , 1.125],
[3. , 1.5 ],
[2.25 , 2. ],
[2. , 2.25 ],
[1.5 , 3. ],
[1.125, 4. ]]), array([1, 2, 2, 2, 2, 2], dtype=uint8))]