如何用x和y分类轴绘制折线图?

时间:2017-11-13 11:00:51

标签: python pandas matplotlib

我试图绘制一个比较2个分类变量的折线图。但是我一直遇到错误。我已将代码放在下面:

import matplotlib.pyplot as plt

cat = ["bored", "happy", "bored", "bored", "happy", "bored"]
dog = ["happy", "happy", "happy", "happy", "bored", "bored"]
activity = ["combing", "drinking", "feeding", "napping", "playing", 
"washing"]

fig, ax = plt.subplots()
ax.plot(activity, dog, label="dog")
ax.plot(activity, cat, label="cat")
ax.legend()

plt.show()

1 个答案:

答案 0 :(得分:2)

在这里提供一个答案:当使用matplotlib> = 2.1运行时,来自问题的代码

import matplotlib.pyplot as plt

cat = ["bored", "happy", "bored", "bored", "happy", "bored"]
dog = ["happy", "happy", "happy", "happy", "bored", "bored"]
activity = ["combing", "drinking", "feeding", "napping", "playing", 
"washing"]

fig, ax = plt.subplots()
ax.plot(activity, dog, label="dog")
ax.plot(activity, cat, label="cat")
ax.legend()

plt.show()

运行良好并生成

enter image description here

<小时/> 对于早期版本的matplotlib,轴应为数字。因此,您需要将类别转换为数字,绘制它们,然后相应地设置ticklabel。

import numpy as np
import matplotlib.pyplot as plt

cat = ["bored", "happy", "bored", "bored", "happy", "bored"]
dog = ["happy", "happy", "happy", "happy", "bored", "bored"]
activity = ["combing", "drinking", "feeding", "napping", "playing", 
"washing"]

catu, cati = np.unique(cat, return_inverse=True)
dogu, dogi = np.unique(dog, return_inverse=True)

fig, ax = plt.subplots()
ax.plot(range(len(dog)), dogi, label="dog")
ax.plot(range(len(cat)), cati, label="cat")

ax.set_xticks(range(len(activity)))
ax.set_xticklabels(activity)

ax.set_yticks(range(len(catu)))
ax.set_yticklabels(catu)

ax.legend()
plt.show()