Home > OS >  Matplotlib scatterplot with list of uneven lists and custom order y-axis
Matplotlib scatterplot with list of uneven lists and custom order y-axis

Time:10-22

can I do this and produce a scatter?

y-axis tick/label order → [0, 7, 2, 9, 4, 11, 6, 1, 8, 3, 10, 5]
            
x = ('a', 'b', 'c', 'd', 'e')

y = [[1,5,2], [10,5,11,7], [9], [], [ 7, 2, 9, 4, 11, 6, 1, 8, 3, 10, 5]]

The idea is to map the x-values against the y-values. e.g. the first in the list of data ('a') was, say, hitting 1, 5 and 2 on a target, the second ('b') hit scores 10, 5, 11, 7. I need to keep the Y-axis as labels in the order shown.

enter image description here

# Define the  y-ticks.
yticks = (0, 7, 2, 9, 4, 11, 6, 1, 8, 3, 10, 5)
ax.set_yticks(sorted(yticks))
ax.set_yticklabels(yticks)

enter image description here

# Define the x-ticks.
xticks = range(5)
ax.set_xticks(xticks)
ax.set_xticklabels(("a", "b", "c", "d", "e")) # `ax.set_xticklabels("abcde")` would work too.

enter image description here

# Put the values in the right spot.
y_lists = ([1, 5 , 2],
           [10, 5, 11, 7],
           [9],
           [],
           [7, 2, 9, 4, 11, 6, 1, 8, 3, 10, 5])

for x, y_list in zip(xticks, y_lists):
    x_list = [x]*len(y_list) # We have a single x value for each letter, but we need the x-list to be as long y-list in order to make a scatter.
    true_y_list = [yticks.index(y) for y in y_list] # Notice the use of `.index` here to accomodate the ticks not being ordered.
    ax.scatter(x_list, true_y_list)

enter image description here

We could also automate things a bit more by using a dict, and writing the labels of the x-axis directly from the keys of that dict... I don't know if you need that?

y_lists = {"a": [1, 5 , 2],
           "b": [10, 5, 11, 7],
           "c": [9],
           "d": [],
           "e": [7, 2, 9, 4, 11, 6, 1, 8, 3, 10, 5]}
...
  • Related