J CENA
J CENA

Reputation: 51

How to plot line graph with x and y categorical axis?

I'm trying to plot a line graph that compares 2 categorical variables. However I keep running into errors. I've put my code below:

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()

Upvotes: 0

Views: 143

Answers (1)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339200

To provide an answer here: When being run with matplotlib >=2.1, the code from the question

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()

runs fine and produces

enter image description here


For earlier versions of matplotlib, axes should be numeric. Hence you need to convert the categories into numbers, plot them, then set the ticklabels accordingly.

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()

Upvotes: 2

Related Questions