![]() |
|
[Tut] How to Color a Scatter Plot by Category using Matplotlib in Python - Printable Version +- Sick Gaming (https://sickgaming.net) +-- Forum: Programming (https://sickgaming.net/forum-76.html) +--- Forum: Python (https://sickgaming.net/forum-83.html) +--- Thread: [Tut] How to Color a Scatter Plot by Category using Matplotlib in Python (/thread-99214.html) |
[Tut] How to Color a Scatter Plot by Category using Matplotlib in Python - xSicKxBot - 04-15-2022 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 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:
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: ![]() If you want to learn more about Matplotlib, feel free to check out our full blog tutorial series: |