五彩线条

此示例显示如何制作多色线。 在此示例中,线条基于其衍生物着色。

五彩线条示例1

  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. from matplotlib.collections import LineCollection
  4. from matplotlib.colors import ListedColormap, BoundaryNorm
  5. x = np.linspace(0, 3 * np.pi, 500)
  6. y = np.sin(x)
  7. dydx = np.cos(0.5 * (x[:-1] + x[1:])) # first derivative
  8. # Create a set of line segments so that we can color them individually
  9. # This creates the points as a N x 1 x 2 array so that we can stack points
  10. # together easily to get the segments. The segments array for line collection
  11. # needs to be (numlines) x (points per line) x 2 (for x and y)
  12. points = np.array([x, y]).T.reshape(-1, 1, 2)
  13. segments = np.concatenate([points[:-1], points[1:]], axis=1)
  14. fig, axs = plt.subplots(2, 1, sharex=True, sharey=True)
  15. # Create a continuous norm to map from data points to colors
  16. norm = plt.Normalize(dydx.min(), dydx.max())
  17. lc = LineCollection(segments, cmap='viridis', norm=norm)
  18. # Set the values used for colormapping
  19. lc.set_array(dydx)
  20. lc.set_linewidth(2)
  21. line = axs[0].add_collection(lc)
  22. fig.colorbar(line, ax=axs[0])
  23. # Use a boundary norm instead
  24. cmap = ListedColormap(['r', 'g', 'b'])
  25. norm = BoundaryNorm([-1, -0.5, 0.5, 1], cmap.N)
  26. lc = LineCollection(segments, cmap=cmap, norm=norm)
  27. lc.set_array(dydx)
  28. lc.set_linewidth(2)
  29. line = axs[1].add_collection(lc)
  30. fig.colorbar(line, ax=axs[1])
  31. axs[0].set_xlim(x.min(), x.max())
  32. axs[0].set_ylim(-1.1, 1.1)
  33. plt.show()

下载这个示例