堆栈图示例

如何使用Matplotlib创建堆栈图。

通过将不同的数据集垂直地绘制在彼此之上而不是彼此重叠来生成堆积图。下面我们展示一些使用Matplotlib实现此目的的示例。

  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. x = [1, 2, 3, 4, 5]
  4. y1 = [1, 1, 2, 3, 5]
  5. y2 = [0, 4, 2, 6, 8]
  6. y3 = [1, 3, 5, 7, 9]
  7. y = np.vstack([y1, y2, y3])
  8. labels = ["Fibonacci ", "Evens", "Odds"]
  9. fig, ax = plt.subplots()
  10. ax.stackplot(x, y1, y2, y3, labels=labels)
  11. ax.legend(loc='upper left')
  12. plt.show()
  13. fig, ax = plt.subplots()
  14. ax.stackplot(x, y)
  15. plt.show()

堆栈图示例图例

堆栈图示例图例2

这里我们展示了使用stackplot制作流图的示例。

  1. def layers(n, m):
  2. """
  3. Return *n* random Gaussian mixtures, each of length *m*.
  4. """
  5. def bump(a):
  6. x = 1 / (.1 + np.random.random())
  7. y = 2 * np.random.random() - .5
  8. z = 10 / (.1 + np.random.random())
  9. for i in range(m):
  10. w = (i / m - y) * z
  11. a[i] += x * np.exp(-w * w)
  12. a = np.zeros((m, n))
  13. for i in range(n):
  14. for j in range(5):
  15. bump(a[:, i])
  16. return a
  17. d = layers(3, 100)
  18. fig, ax = plt.subplots()
  19. ax.stackplot(range(100), d.T, baseline='wiggle')
  20. plt.show()

堆栈图示例图例3

下载这个示例