Scatter Plots In Pandas/pyplot: How To Plot By Category With Different Markers
Building on this earlier question: Scatter plots in Pandas/Pyplot: How to plot by category. The code below is the solution to that post and plots each group as a different color.
Solution 1:
While you iterate over your groups, you can iterate over a list of markers using zip
. The code below will iterate over the markers
list and assign each element, in turn, using marker=marker
in the ax.plot
line.
I've also added itertools.cycle
which will cause the iteration to go to the beginning once the end is reached, this means that if you have more than 3 groups then it won't fail. If you had 4 groups then the markers would be 'x', 'o', '^', 'x'
, for example.
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
np.random.seed(1974)
from itertools import cycle
# 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')
markers = ['x', 'o', '^']
# Plot
fig, ax = plt.subplots()
ax.margins(0.05) # Optional, just adds 5% padding to the autoscalingfor (name, group), marker inzip(groups, cycle(markers)):
ax.plot(group.x, group.y, marker=marker, linestyle='', ms=12, label=name)
ax.legend()
plt.show()
Post a Comment for "Scatter Plots In Pandas/pyplot: How To Plot By Category With Different Markers"