Pandas scatter plot not coloring by column value

Viewed 742

I have a simple pandas DataFrame as shown below. I want to create a scatter plot of value on the y-axis, date on the x-axis, and color the points by category. However, coloring the points isn't working.

# Create dataframe
df = pd.DataFrame({
    'date': ['2016-01-01', '2016-02-01', '2016-03-01', '2016-01-01', '2016-02-01', '2016-03-01'],
    'category': ['Wholesale', 'Wholesale', 'Wholesale', 'Retail', 'Retail', 'Retail'],
    'value': [50, 60, 65, 55, 62, 70]
})
df['date'] = pd.to_datetime(df['date'])

# Try to plot
df.plot.scatter(x='date', y='value', c='category')

ValueError: 'c' argument must be a mpl color, a sequence of mpl colors or a sequence of numbers, not ['Wholesale' 'Wholesale' 'Wholesale' 'Retail' 'Retail' 'Retail'].

Why am a I getting the error? Pandas scatter plot documentation says the argument c can be "A column name or position whose values will be used to color the marker points according to a colormap."

2 Answers
df.plot.scatter(x='date', y='value', c=df['category'].map({'Wholesale':'red','Retail':'blue'}))

I think you are looking at seaborn:

import seaborn as sns
sns.scatterplot(data=df, x='date', y='value', hue='category')

Output:

enter image description here

Or you can loop through df.groupby:

fig, ax = plt.subplots()
for cat, d in df.groupby('category'):
    ax.scatter(x=d['date'],y=d['value'], label=cat)

Output:

enter image description here

Related