- If a column is set as categorical with
pd.Categorical, the categorical column is not correctly plotted with the associated value, when usingplt.plot, as shown below. - Anybody know how to avoid this sort of thing? Is this a bug, or am I the problem?
import pandas as pd
import matplotlib.pyplot as plt
labels = ["b", "b", "a", "b", "a"]
values = [10, 11, 1, 12, 2]
df = pd.DataFrame([{"label": label, "value": v} for label, v in zip(labels, values)])
df.label = pd.Categorical(df.label)
The dataframe looks like this:
>>> print(df)
label value
0 b 10
1 b 11
2 a 1
3 b 12
4 a 2
But when I plot the dataframe with matplotlib.pyplot.plot, the labels "a" and "b" are mixed up:
>>> plt.plot(df.label, df.value, "o")

Compare the (correct) output of plt.scatter(df.label, df.value):

The problem goes away when swapping the labels "a" and "b", so it looks like plt.plot sorts the labels before plotting. But why would it do that? It works fine when the labels are strings; the problem only arises because df.labels is categorical.

