Aiden3301
Aiden3301

Reputation: 41

Error in Python Seaborn Catplot: Object has no len()

Given some categorical data like:

import pandas as pd

data = pd.Series(["NY", "NY", "CL", "TX", "CL", "FL", "NY", "FL"])

In the original data, this is a column in a DataFrame. I want to plot it via sns.catplot() like so:

import seaborn as sns
import matplotlib.pyplot as plt

sns.catplot(x=data, kind="count")

But I get this error:

Traceback (most recent call last):
  File "C:\Users\%USERNAME%\PycharmProjects\Troubleshooting\temp.py", line 6, in <module>
    sns.catplot(x=my_data, kind="count")
  File "C:\Users\%USERNAME%\Troubleshooting\lib\site-packages\seaborn\categorical.py", line 3241, in catplot
    g = FacetGrid(**facet_kws)
  File "C:\Users\%USERNAME%\Troubleshooting\lib\site-packages\seaborn\axisgrid.py", line 403, in __init__
    none_na = np.zeros(len(data), bool)
TypeError: object of type 'NoneType' has no len()

The Series / Data Frame has a shape, length etc. so I don't understand where the error message comes from. What is wrong, and how do I fix it?

I know that sns.countplot() will work with this input, but I need to use catplot in order to create the countplot.

Upvotes: 0

Views: 438

Answers (3)

Aiden3301
Aiden3301

Reputation: 41

I figured it out. Thank you guys.

The issue is, that the catplot needs (at least for DataFrames) the explicitly needs parameter "data", given a DataFrame, and then a parameter for "x", but only the column name there. It isn't enough to use the argument "x=df["column_name"]".

import seaborn as sns
import pandas as pd

my_data #any dataframe you have

sns.countplot(data=my_data, x="Column 1", kind="count")

Upvotes: 0

mozway
mozway

Reputation: 262359

It doesn't really make sense to use a catplot with a Series, as this higher level function is relevant when multiple columns with categories are present to automatically generate a FacetGrid.

Anyway, if you really want to use catplot, you'll have to convert to DataFrame and pass the data to data, not x (that is for the column name in data):

sns.catplot(data=data.to_frame('x-label'), x='x-label', kind="count")

Output:

enter image description here

Upvotes: 1

imburningbabe
imburningbabe

Reputation: 792

You should use sns.countplot instead:

data = pd.Series(["NY", "NY", "CL", "TX", "CL", "FL", "NY", "FL"])

sns.countplot(x=data)

Upvotes: 1

Related Questions