0

I have three arrays to use in a scatter plot: x, y, and z. x and y make up the data points, and z is an identifier for labeling. z ranges between 1 and 24.

I want to give my scatter plot different makers based on the z value. If z is less than or equal to 12, marker = '1'. Else, marker = 'o'. Here is a snippet of the code I'm trying to use.

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(1, 13)
if z == x:
    scatter = plt.scatter(x, y, c=z, cmap='jet', marker = '1')
else:
    scatter = plt.scatter(x, y, c=z, cmap='jet', marker = 'o')

Unfortunately this code gives me a plot with only one marker type, regardless of the value of z for each x-y pair. I've also tried using a for loop to iterate through the z array, but that just gives me errors.

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
cat_herder
  • 51
  • 6
  • If your condition of `z` is less than or equal to 12, why is your `if` statement comparing `z` to an interval? – MrSoLoDoLo Mar 08 '23 at 17:34
  • This other answer may help you find what you are looking for. https://stackoverflow.com/questions/41099887/conditional-marker-matplotlib – jagord24 Mar 08 '23 at 17:56
  • MrSoloDoLo, I know, I'm obviously doing something wrong. That's why I'm asking for help. – cat_herder Mar 08 '23 at 18:27

1 Answers1

2

There are a few ways to do this, but here is one that is very readable:

import numpy as np
import matplotlib.pyplot as plt

x = np.random.uniform(low=0, high=50, size=10) 
y = np.random.uniform(low=0, high=50, size=10)
z = np.random.randint(low=1, high=25, size=10)

fig, ax = plt.subplots()
ax.scatter(x[z < 12], y[z < 12], marker='s', color='b', label='z < 12')
ax.scatter(x[z >= 12], y[z >= 12], marker='o', facecolors='none', edgecolors='r', label='z >= 12')
ax.set(xlabel='x', ylabel='y')
ax.legend()
plt.show()

enter image description here

Or here is a version that uses a colormap, like you had in your OP:

fig, ax = plt.subplots()
ax.scatter(x[z < 12], y[z < 12], marker='s', c=z[z < 12], cmap='jet', label='z < 12')
ax.scatter(x[z >= 12], y[z >= 12], marker='o', c=z[z >= 12], cmap='jet', label='z >= 12')
ax.set(xlabel='x', ylabel='y')
ax.legend()
sc = ax.scatter([],[], c=[], cmap='jet')
plt.show()

enter image description here

a11
  • 3,122
  • 4
  • 27
  • 66