3

I want to plot the values of two matrices in a scatter plot. For each of the points of the scatterplot, I want to see in which column and which row they are. For the different rows, I use different colours. For the different columns, I use different markers. In the legend I want the colours to indicate a number (corresponding to the row) and the markers to indicate a letter (corresponding to the column). I managed to get the column in the legend, but not the row. Simplified my code looks something like this:

x = np.array([[np.nan, 5, 6], [3, 4, 8], [0, 0, 9]])
y = np.array([[np.nan, 4, 7], [7, 8, 2], [1, 2, 7]])
color = np.array([['b','g','r'],]*3).transpose()  # Can be other colours than b,g,r
marker = ['o', 'v', '^']
label = ['A','B','C']
for j in range(3):
    plt.scatter(x[:,j], y[:,j], c=color[:,j], marker=marker[j], label=label[j])
plt.xlabel("xlabel")
plt.ylabel("ylabel")
plt.legend(loc=2)
plt.show()
plt.ylabel("ylabel")
plt.legend(loc=2)

How can I also add the marker? And now in my legend, the first marker is green, while the other two are blue. Is there a way to fix this?

Jorre Goossens
  • 139
  • 1
  • 2
  • 10

1 Answers1

4

The idea to make the legend is to create proxy artists (i.e. used only for the legend): plt.legend(list_of_proxy_artists, list_of_labels).

The column markers can be obtained by plotting empty lines with:

proxy = plt.plot([], [], 'o', markerfacecolor='w', markeredgecolor='k')[0]

And the colored rectangles for the rows can be created with patches:

patch = mpatches.Patch(color='r')

Putting everything together:

import numpy as np
from matplotlib import pyplot as plt
import matplotlib.patches as mpatches

x = np.array([[np.nan, 5, 6], [3, 4, 8], [0, 0, 9]])
y = np.array([[np.nan, 4, 7], [7, 8, 2], [1, 2, 7]])
color = np.array([['b','g','r'],]*3).transpose()  # Can be other colours than b,g,r
marker = ['o', 'v', '^']

for j in range(3):
    plt.scatter(x[:,j], y[:,j], c=color[:,j], marker=marker[j])
plt.xlabel("xlabel")
plt.ylabel("ylabel")

# legend
label_column = ['A','B','C']
label_row = ['1', '2', '3']
rows = [mpatches.Patch(color=color[i, 0]) for i in range(3)]
columns = [plt.plot([], [], marker[i], markerfacecolor='w',
                    markeredgecolor='k')[0] for i in range(3)]

plt.legend(rows + columns, label_row + label_column, loc=2)

plt.show()

enter image description here

j_4321
  • 15,431
  • 3
  • 34
  • 61