2

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. How would one also plot each group as different marker?

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()
Community
  • 1
  • 1
srmulcahy
  • 359
  • 1
  • 3
  • 18

1 Answers1

4

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 autoscaling
for (name, group), marker in zip(groups, cycle(markers)):
    ax.plot(group.x, group.y, marker=marker, linestyle='', ms=12, label=name)
ax.legend()

plt.show()

Example plot

Ffisegydd
  • 51,807
  • 15
  • 147
  • 125