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%\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 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.
>Solution :
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:
