04-15-2022, 02:58 AM
How to Color a Scatter Plot by Category using Matplotlib in Python
Problem Formulation
Given three arrays:
Question: How to plot the data so that and with the same category have the same color?
Solution: Use Pandas groupby() and Call plt.plot() Separately for Each Group
To plot data by category, you iterate over all groups separately by using the operation. For each group, you execute the operation to plot only the data in the group.
In particular, you perform the following steps:
Here’s what that looks like in code:
Before I show you how the resulting plot looks, allow me to show you the data output from the function. Here’s the output of the categorical data:
Now, how does the colored category plot look like? Here’s how:
![[Image: image-61.png]](https://blog.finxter.com/wp-content/uploads/2022/04/image-61.png)
If you want to learn more about Matplotlib, feel free to check out our full blog tutorial series:
Problem Formulation
Given three arrays:
- The first two arrays andCode:
xof lengthCode:ycontain theCode:ndata of a 2D coordinate system.Code:(x_i, y_i)
- The third array provides categorical label information so we essentially getCode:
cdata bundlesCode:nfor an arbitrary number of categoriesCode:(x_i, y_i, c_i).Code:c_i
Question: How to plot the data so that Code:
(x_i, y_i)Code:
(x_j, y_j)Code:
c_i == c_jSolution: Use Pandas groupby() and Call plt.plot() Separately for Each Group
To plot data by category, you iterate over all groups separately by using the
Code:
data.groupby()Code:
plt.plot()In particular, you perform the following steps:
- Use the function assuming that data is a Pandas DataFrame containing theCode:
data.groupby("Category"),Code:x, andCode:ycolumns for n data points (rows).Code:category
- Iterate over all tuples in the grouping operation result obtained from step one.Code:
(name, group)
- Use to plot each group separately using theCode:
plt.plot(group["X"], group["Y"], marker="o", linestyle="", label=name),Code:xdata andCode:yas a label.Code:name
Here’s what that looks like in code:
Code:
import pandas as pd
import matplotlib.pyplot as plt # Generate the categorical data
x = [1, 2, 3, 4, 5, 6]
y = [42, 41, 40, 39, 38, 37]
c = ['a', 'b', 'a', 'b', 'b', 'a'] data = pd.DataFrame({"X": x, "Y": y, "Category": c})
print(data) # Plot data by category
groups = data.groupby("Category")
for name, group in groups: plt.plot(group["X"], group["Y"], marker="o", linestyle="", label=name) plt.legend()
plt.show()Before I show you how the resulting plot looks, allow me to show you the data output from the
Code:
print()Code:
X Y Category
0 1 42 a
1 2 41 b
2 3 40 a
3 4 39 b
4 5 38 b
5 6 37 aNow, how does the colored category plot look like? Here’s how:
![[Image: image-61.png]](https://blog.finxter.com/wp-content/uploads/2022/04/image-61.png)
If you want to learn more about Matplotlib, feel free to check out our full blog tutorial series:

