Imports and Sample DataFrame

import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns  # for sample data
from matplotlib.lines import Line2D  # for legend handle

# DataFrame used for all options
df = sns.load_dataset('diamonds')

   carat      cut color clarity  depth  table  price     x     y     z
0   0.23    Ideal     E     SI2   61.5   55.0    326  3.95  3.98  2.43
1   0.21  Premium     E     SI1   59.8   61.0    326  3.89  3.84  2.31
2   0.23     Good     E     VS1   56.9   65.0    327  4.05  4.07  2.31

With matplotlib

You can pass plt.scatter a c argument, which allows you to select the colors. The following code defines a colors dictionary to map the diamond colors to the plotting colors.

fig, ax = plt.subplots(figsize=(6, 6))

colors = {'D':'tab:blue', 'E':'tab:orange', 'F':'tab:green', 'G':'tab:red', 'H':'tab:purple', 'I':'tab:brown', 'J':'tab:pink'}

ax.scatter(df['carat'], df['price'], c=df['color'].map(colors))

# add a legend
handles = [Line2D([0], [0], marker='o', color='w', markerfacecolor=v, label=k, markersize=8) for k, v in colors.items()]
ax.legend(title='color', handles=handles, bbox_to_anchor=(1.05, 1), loc='upper left')

plt.show()

df['color'].map(colors) effectively maps the colors from "diamond" to "plotting".

(Forgive me for not putting another example image up, I think 2 is enough :P)

With seaborn

You can use seaborn which is a wrapper around matplotlib that makes it look prettier by default (rather opinion-based, I know :P) but also adds some plotting functions.

For this you could use seaborn.lmplot with fit_reg=False (which prevents it from automatically doing some regression).

  • sns.scatterplot(x='carat', y='price', data=df, hue='color', ec=None) also does the same thing.

Selecting hue='color' tells seaborn to split and plot the data based on the unique values in the 'color' column.

sns.lmplot(x='carat', y='price', data=df, hue='color', fit_reg=False)

With pandas.DataFrame.groupby & pandas.DataFrame.plot

If you don't want to use seaborn, use pandas.groupby to get the colors alone, and then plot them using just matplotlib, but you'll have to manually assign colors as you go, I've added an example below:

fig, ax = plt.subplots(figsize=(6, 6))

grouped = df.groupby('color')
for key, group in grouped:
    group.plot(ax=ax, kind='scatter', x='carat', y='price', label=key, color=colors[key])
plt.show()

This code assumes the same DataFrame as above, and then groups it based on color. It then iterates over these groups, plotting for each one. To select a color, I've created a colors dictionary, which can map the diamond color (for instance D) to a real color (for instance tab:blue).

Answer from Ffisegydd on Stack Overflow
🌐
Kanoki
kanoki.org › 2020 › 08 › 30 › matplotlib-scatter-plot-color-by-category-in-python
Matplotlib Scatter Plot Color by Category in Python | kanoki
August 30, 2020 - import matplotlib.pyplot as plt ...opulation, Area=Area, continent = continent)) fig, ax = plt.subplots() colors = {'North America':'red', 'Europe':'green', 'Asia':'blue', 'Australia':'yellow'} ax.scatter(df['population'], df['Area'], c=df['continent'].map(colors)) ...
🌐
GitHub
rasbt.github.io › mlxtend › user_guide › plotting › category_scatter
Scategory_scatter: Create a scatterplot with categories in different colors - mlxtend
A function to quickly produce a scatter plot colored by categories from a pandas DataFrame or NumPy ndarray object.
Top answer
1 of 8
227

Imports and Sample DataFrame

import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns  # for sample data
from matplotlib.lines import Line2D  # for legend handle

# DataFrame used for all options
df = sns.load_dataset('diamonds')

   carat      cut color clarity  depth  table  price     x     y     z
0   0.23    Ideal     E     SI2   61.5   55.0    326  3.95  3.98  2.43
1   0.21  Premium     E     SI1   59.8   61.0    326  3.89  3.84  2.31
2   0.23     Good     E     VS1   56.9   65.0    327  4.05  4.07  2.31

With matplotlib

You can pass plt.scatter a c argument, which allows you to select the colors. The following code defines a colors dictionary to map the diamond colors to the plotting colors.

fig, ax = plt.subplots(figsize=(6, 6))

colors = {'D':'tab:blue', 'E':'tab:orange', 'F':'tab:green', 'G':'tab:red', 'H':'tab:purple', 'I':'tab:brown', 'J':'tab:pink'}

ax.scatter(df['carat'], df['price'], c=df['color'].map(colors))

# add a legend
handles = [Line2D([0], [0], marker='o', color='w', markerfacecolor=v, label=k, markersize=8) for k, v in colors.items()]
ax.legend(title='color', handles=handles, bbox_to_anchor=(1.05, 1), loc='upper left')

plt.show()

df['color'].map(colors) effectively maps the colors from "diamond" to "plotting".

(Forgive me for not putting another example image up, I think 2 is enough :P)

With seaborn

You can use seaborn which is a wrapper around matplotlib that makes it look prettier by default (rather opinion-based, I know :P) but also adds some plotting functions.

For this you could use seaborn.lmplot with fit_reg=False (which prevents it from automatically doing some regression).

  • sns.scatterplot(x='carat', y='price', data=df, hue='color', ec=None) also does the same thing.

Selecting hue='color' tells seaborn to split and plot the data based on the unique values in the 'color' column.

sns.lmplot(x='carat', y='price', data=df, hue='color', fit_reg=False)

With pandas.DataFrame.groupby & pandas.DataFrame.plot

If you don't want to use seaborn, use pandas.groupby to get the colors alone, and then plot them using just matplotlib, but you'll have to manually assign colors as you go, I've added an example below:

fig, ax = plt.subplots(figsize=(6, 6))

grouped = df.groupby('color')
for key, group in grouped:
    group.plot(ax=ax, kind='scatter', x='carat', y='price', label=key, color=colors[key])
plt.show()

This code assumes the same DataFrame as above, and then groups it based on color. It then iterates over these groups, plotting for each one. To select a color, I've created a colors dictionary, which can map the diamond color (for instance D) to a real color (for instance tab:blue).

2 of 8
63

Here's a succinct and generic solution to use a seaborn color palette.

First find a color palette you like and optionally visualize it:

sns.palplot(sns.color_palette("Set2", 8))

Then you can use it with matplotlib doing this:

# Unique category labels: 'D', 'F', 'G', ...
color_labels = df['color'].unique()

# List of RGB triplets
rgb_values = sns.color_palette("Set2", 8)

# Map label to RGB
color_map = dict(zip(color_labels, rgb_values))

# Finally use the mapped values
plt.scatter(df['carat'], df['price'], c=df['color'].map(color_map))
🌐
Finxter
blog.finxter.com › home › learn python blog › how to color a scatter plot by category using matplotlib in python
How to Color a Scatter Plot by Category using Matplotlib in Python - Be on the Right Side of Change
April 8, 2022 - 💬 Question: How to plot the data so that (x_i, y_i) and (x_j, y_j) with the same category c_i == c_j have the same color? To plot data by category, you iterate over all groups separately by using the data.groupby() operation.
Top answer
1 of 8
145

You can use scatter for this, but that requires having numerical values for your key1, and you won't have a legend, as you noticed.

It's better to just use plot for discrete categories like this. For example:

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
np.random.seed(1974)

# Generate Data
num = 20
x, y = np.random.random((2, num))
labels = np.random.choice(['a', 'b', 'c'], num)
df = pd.DataFrame(dict(x=x, y=y, label=labels))

groups = df.groupby('label')

# Plot
fig, ax = plt.subplots()
ax.margins(0.05) # Optional, just adds 5% padding to the autoscaling
for name, group in groups:
    ax.plot(group.x, group.y, marker='o', linestyle='', ms=12, label=name)
ax.legend()

plt.show()

If you'd like things to look like the default pandas style, then just update the rcParams with the pandas stylesheet and use its color generator. (I'm also tweaking the legend slightly):

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
np.random.seed(1974)

# Generate Data
num = 20
x, y = np.random.random((2, num))
labels = np.random.choice(['a', 'b', 'c'], num)
df = pd.DataFrame(dict(x=x, y=y, label=labels))

groups = df.groupby('label')

# Plot
plt.rcParams.update(pd.tools.plotting.mpl_stylesheet)
colors = pd.tools.plotting._get_standard_colors(len(groups), color_type='random')

fig, ax = plt.subplots()
ax.set_color_cycle(colors)
ax.margins(0.05)
for name, group in groups:
    ax.plot(group.x, group.y, marker='o', linestyle='', ms=12, label=name)
ax.legend(numpoints=1, loc='upper left')

plt.show()

2 of 8
73

This is simple to do with Seaborn (pip install seaborn) as a oneliner

sns.scatterplot(x_vars="one", y_vars="two", data=df, hue="key1") :

import seaborn as sns
import pandas as pd
import numpy as np
np.random.seed(1974)

df = pd.DataFrame(
    np.random.normal(10, 1, 30).reshape(10, 3),
    index=pd.date_range('2010-01-01', freq='M', periods=10),
    columns=('one', 'two', 'three'))
df['key1'] = (4, 4, 4, 6, 6, 6, 8, 8, 8, 8)

sns.scatterplot(x="one", y="two", data=df, hue="key1")

Here is the dataframe for reference:

Since you have three variable columns in your data, you may want to plot all pairwise dimensions with:

sns.pairplot(vars=["one","two","three"], data=df, hue="key1")

https://rasbt.github.io/mlxtend/user_guide/plotting/category_scatter/ is another option.

🌐
Datavizpyr
datavizpyr.com › home › how to color scatterplot by a variable in matplotlib?
How To Color Scatterplot by a variable in Matplotlib? - Data Viz with Python and R
May 9, 2021 - Coloring Scatterplot with Variable using Matplotlib · Here is the complete code chunk to color data points on scatterplot by a variable with x and y-ax labels and save the plot as PNG file. plt.figure(figsize=(8,8)) plt.scatter(x=df.culmen_length_mm, y=df.culmen_depth_mm, c=df.species.astype('category').cat.codes) plt.xlabel("Culmen Length (mm)", fontweight ='bold', size=14) plt.ylabel("Culmen Depth (mm)", fontweight ='bold', size=14) plt.savefig("Coloring_Scatterplot_with_Variable_matplotlib.png", format='png',dpi=150)
🌐
Medium
medium.com › @monayo › creating-a-scatter-plot-where-points-are-colored-according-to-a-categorical-variable-in-python-c9624be2f39c
Creating a scatter plot by category in python | by Rodgers Monayo | Medium
November 19, 2024 - The dataset used in this code snippet can be found in vincentarelbundock.github.io/Rdatasets/datasets.html by scrolling down to datasets category(datasets/iris.csv) import pandas as pd import matplotlib.pyplot as plt from matplotlib.patches import Patch iris= pd.read_csv('iris.csv') #assiging each category of species a color Dict_colors = {'setosa':'blue','versicolor':'green','virginica':'red'} #map species to their respective colors colors = iris['Species'].map(Dict_colors) #creating a scatter plot plt.scatter(iris['Petal.Length'],iris['Sepal.Length'],c=colors) #showing the grid plt.grid(True
🌐
Matplotlib
matplotlib.org › stable › users › explain › colors › colormaps.html
Choosing Colormaps in Matplotlib — Matplotlib 3.11.2 documentation
In CIELAB, color space is represented by lightness, \(L^*\); red-green, \(a^*\); and yellow-blue, \(b^*\). The lightness parameter \(L^*\) can then be used to learn more about how the matplotlib colormaps will be perceived by viewers. An excellent starting resource for learning about human perception of colormaps is from [IBM]. Colormaps are often split into several categories based on their function (see, e.g., [Moreland]):
Find elsewhere
🌐
Python Guides
pythonguides.com › matplotlib-scatter-plot-color
Matplotlib Scatter Marker: Shape, Size, Color
July 16, 2025 - Pass the numeric array as c and set cmap, then add plt.colorbar() so the colours can be read. Call plt.scatter once per category with its own c and label.
🌐
Python Graph Gallery
python-graph-gallery.com › the python graph gallery › scatterplot › use categorical variable to color scatterplot in seaborn
Use categorical variable to color scatterplot in seaborn
2 weeks ago - # library & dataset import seaborn as sns import matplotlib.pyplot as plt plt.rcParams["figure.dpi"] = 300 df = sns.load_dataset('iris') # Use the 'hue' argument to provide a factor variable sns.scatterplot( x="sepal_length", y="sepal_width", data=df, hue='species', ) plt.show() Edit code✨Still copy-pasting code? Let AI write it for you · It is also possible to define categories with different forms of marker.
🌐
Statology
statology.org › home › matplotlib: how to color a scatterplot by value
Matplotlib: How to Color a Scatterplot by Value
September 3, 2020 - The following code shows how to create a scatterplot using the variable z to color the markers based on category: import matplotlib.pyplot as plt groups = df.groupby('z') for name, group in groups: plt.plot(group.x, group.y, marker='o', linestyle='', markersize=12, label=name) plt.legend() You can find more Python tutorials here.
🌐
GitHub
github.com › matplotlib › matplotlib › issues › 6214
allow using categorical data for color, marker, size, … · Issue #6214 · matplotlib/matplotlib
March 23, 2016 - the color palette for categorical data would be plt.rcParams['axes.prop_cycle'].by_key()['color'], the marker palette a new rcParam (maybe?) those palettes would be cycled if there are too many categories. ... are integers treated as quantitiative + discrete (legend containing all separate values) or continuous (bar) how to specify if a legend/colorbar/sizebar should created? it makes sense to automatically do it if we use the data= interface ... Difficulty: Hardhttps://matplotlib.org/devdocs/devel/contribute.html#good-first-issueshttps://matplotlib.org/devdocs/devel/contribute.html#good-first-issuesNew featurekeepItems to be ignored by the “Stale” Github ActionItems to be ignored by the “Stale” Github Actiontopic: categorical
Author: matplotlib
🌐
GitHub
gist.github.com › jakevdp › 8a992f606899ac24b711
Example of a categorical color map in matplotlib · GitHub
Never understood why mpl does not have the ability of mapping categorical variables to colors automatically.
🌐
GeeksforGeeks
geeksforgeeks.org › how-to-create-a-scatter-plot-with-several-colors-in-matplotlib
How to create a Scatter Plot with several colors in Matplotlib? - GeeksforGeeks
January 10, 2024 - In this example, we are using Matplotlib to generate a scatter plot with specific data points and color-coded categories. Initially, essential modules such as Matplotlib and NumPy are imported.
🌐
Python Graph Gallery
python-graph-gallery.com › the python graph gallery › scatterplot › scatter plot with a grouping variable with pandas
Scatter plot with a grouping variable with Pandas
2 weeks ago - From a list comprehension, we create a list of colors according to the group of in the variable categorical_variable. Once this list is created, we just have to add the c=colors argument when calling the scatter() function.
🌐
Moonbooks
moonbooks.org › Articles › How-to-create-a-scatter-plot-with-several-colors-in-matplotlib-
How to create a scatter plot with several colors in matplotlib ?
April 5, 2019 - How to create a scatter plot with several colors in matplotlib ? import matplotlib.pyplot as plt import numpy as np a = np.array([[ 1, 2, 3, 4, 5, 6, 7, 8 ], [ 1, 4, 8, 14, 12, 7, 3, 2 ]]) categories = np.array([0, 2, 1, 1, 1, 2, 0, 0]) colormap = np.array(['r', 'g', 'b']) plt.scatter(a[0], a[1], s=100, c=colormap[categories]) plt.savefig('ScatterClassPlot.png') plt.show() Another example ·
🌐
Python Graph Gallery
python-graph-gallery.com › categorical-color-palette
Use, customize and create categoric palettes in Matplotlib
Matplotlib has built-in tools that make it easy to use categoric palettes by having a set of predefined palettes and functions to create custom ones. ... Font ColorwhiteFont Opacity100%Font Size100%Font FamilyArialText ShadownoneBackground ColorblackBackground Opacity50%Window ColorblackWindow Opacity0%
🌐
Stack Overflow
stackoverflow.com › questions › 71554518 › color-by-category-using-matplotlib
python - color by category using matplotlib - Stack Overflow
Matplotlib.colors.ListedColormap in python · 0 · Colouring by category in a pandas plot · 3 · How to color objects in an image with different color each · 1 · Plotting Categorical by Color · 4 · Color by category in matplotlib using np.where · 0 · plot multiple images from classification categories ·
🌐
Kanaries
docs.kanaries.net › topics › Matplotlib › matplotlib-colormap
Matplotlib Colormap: Complete Guide to Color Maps in Python – Kanaries
February 12, 2026 - Each color is maximally different from its neighbors, making them ideal for categorical labels. When to use: Cluster labels, categorical scatter plots, bar charts with unordered groups. Key examples: tab10, tab20, Set1, Set2, Set3, Paired, Accent · import matplotlib.pyplot as plt import numpy as np np.random.seed(7) categories = 6 x = np.concatenate([np.random.randn(30) + i * 3 for i in range(categories)]) y = np.concatenate([np.random.randn(30) + i * 1.5 for i in range(categories)]) labels = np.concatenate([np.full(30, i) for i in range(categories)]) plt.figure(figsize=(9, 6)) scatter = plt.scatter(x, y, c=labels, cmap='tab10', s=50, alpha=0.8, edgecolors='white') plt.colorbar(scatter, label='Category') plt.title('Qualitative Colormap: tab10') plt.xlabel('X') plt.ylabel('Y') plt.show()