Matplotlib 3.0 Cookbook
上QQ阅读APP看书,第一时间看更新

There's more...

In the previous plot, we generated triangles automatically. Here, we will learn how to add triangles manually:

  1. Set up data for longitude and latitude in radians:
xy = np.array([[-0.101, 0.872], [-0.080, 0.883], [-0.069, 0.888], 
[-0.054, 0.890], [-0.045, 0.897], [-0.057, 0.895],
[-0.073, 0.900], [-0.087, 0.898],
[-0.090, 0.904], [-0.069, 0.907]])
  1. Convert xy from radians to degrees:
x = np.degrees(xy[:, 0])
y = np.degrees(xy[:, 1])
  1. Choose the points to form triangles from xy coordinates converted to degrees:
triangles = np.array([[1, 2, 3], [3, 4, 5], [4, 5, 6], [2, 5, 6], 
[6, 7, 8], [6, 8, 9], [0, 1, 7]])
  1. Plot the triangulation:
plt.triplot(x, y, triangles, 'go-', lw=1.0)
  1. Plot labels and the title:
plt.title('triplot of user-specified triangulation')
plt.xlabel('Longitude (degrees)')
plt.ylabel('Latitude (degrees)')
  1. Display the plot on the screen:
plt.show()

Here is how it works:

  • xy is an array of coordinates in radians.
  • np.degrees() converts radians to degrees; x and y are in radians and are then converted to degrees, where x and y stand for the longitude and latitude values, respectively.

A triangle is an array of three point tuples for each triangle to be plotted. Numbers are indices of the points in x and y (0 to 9, a total of 10 points). The output looks as follows: