绘制分类变量

如何在Matplotlib中使用分类变量。

很多时候你想创建一个在Matplotlib中使用分类变量的图。Matplotlib允许你将分类变量直接传递给许多绘图函数,我们将在下面演示。

  1. import matplotlib.pyplot as plt
  2. data = {'apples': 10, 'oranges': 15, 'lemons': 5, 'limes': 20}
  3. names = list(data.keys())
  4. values = list(data.values())
  5. fig, axs = plt.subplots(1, 3, figsize=(9, 3), sharey=True)
  6. axs[0].bar(names, values)
  7. axs[1].scatter(names, values)
  8. axs[2].plot(names, values)
  9. fig.suptitle('Categorical Plotting')

分类变量图示1;

这在两个轴上都起作用:

  1. cat = ["bored", "happy", "bored", "bored", "happy", "bored"]
  2. dog = ["happy", "happy", "happy", "happy", "bored", "bored"]
  3. activity = ["combing", "drinking", "feeding", "napping", "playing", "washing"]
  4. fig, ax = plt.subplots()
  5. ax.plot(activity, dog, label="dog")
  6. ax.plot(activity, cat, label="cat")
  7. ax.legend()
  8. plt.show()

分类变量图示2;

下载这个示例