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

Question:

Given some categorical data like:

import pandas as pd

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

In the original data, it 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%PycharmProjectsTroubleshootingtemp.py", line 6, in <module>
    sns.catplot(x=my_data, kind="count")
  File "C:Users%USERNAME%Troubleshootinglibsite-packagesseaborncategorical.py", line 3241, in catplot
    g = FacetGrid(**facet_kws)
  File "C:Users%USERNAME%Troubleshootinglibsite-packagesseabornaxisgrid.py", line 403, in __init__
    none_na = np.zeros(len(data), bool)
TypeError: object of type 'NoneType' has no len()

The Series 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.

Asked By: Aiden3301

||

Answers:

Try using:

import seaborn as sns
import matplotlib.pyplot as plt

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

resource: https://pandas.pydata.org/docs/reference/api/pandas.Series.tolist.html

Answered By: kaliiiiiiiii

You should use sns.countplot instead:

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

sns.countplot(x=data)
Answered By: imburningbabe

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

Answered By: mozway

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

I haven’t found a solution for the series yet, but if I find one, I’ll update this post.

Answered By: Aiden3301
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.