Search code examples
pythonmatplotlibif-statementgoogle-maps-markersscatter-plot

Using different markers in a scatter plot


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.


Solution

  • 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