deeenes deeenes - 6 days ago 8
Python Question

Seaborn barplot with x_order: AttributeError: 'bool' object has no attribute 'sum'

I am trying to plot simple barcharts with

seaborn.barplot()
. In the simplest case it works well,
x
can by a vector of strings, or numbers:

import numpy as np
import seaborn as sns
import matplotplib.pyplot as plt
fig, ax = plt.subplots()
ax = sns.barplot(np.array(['a','b','c']), y = np.array([1,2,3]))
fig.tight_layout()
fig.savefig('test.pdf')


To order the bars in a custom way, there is the
x_order
argument, which is a list-like object with indexes. If
x
itself is numeric, it also works well:

x = np.array([2, 0, 1])
y = np.array([3, 4, 2])
sns.barplot(x, y = y, x_order = list(x.argsort()))


However, if
x
is not numeric, it gives an error, even if I try to order by other numeric vector, or by ordering the string vector itself:

x = np.array(['b', 'c', 'a'])
y = np.array([3, 4, 2])
sns.barplot(x, y = y, x_order = list(x.argsort()))
sns.barplot(x, y = y, x_order = [2, 0, 1])


Then I get the error
AttributeError: 'bool' object has no attribute 'sum'
. I haven't found much about this, and I am wondering how to do this simple ordering properly.

Answer

x_order should be a list of the labels, not the list of indexes. In other words, in the latter case you would just want x_order=['a', 'b', 'c'].

Comments