Search code examples
pythonmatplotlibplotcategorical-data

reordering relabeled data on y axis


I have a dataset that x is a tuple integer:

[1,2,3,4,5,6,7,8,9,10,...40]

and y is a string tuple

['5', '2', '5', '2', '5', '2', '5', '2', '5', '2', '5', '2', '5', '2', '4', '2', '4', '2', '5', '1', '5', '2', '5', '2', '1', '3', '5', '0', '5', '3', '5', '3', '5', '3', '5', '3', '5', '3', '4', '0'].

The y axis data need to be translated to categorical data ('5'->W,'4'->R,'3'->'N1','2'->'N2','1'->'N1'). Zero does not need a label. I chose to plot them as is and just change the label on the y axis:

import matplotlib.ticker as ticker
conv_tup=np.array(x)
fig, ax = plt.subplots()
ax.scatter(conv_tup/2,y)
y_labels={1:'W',2:'N1',3:'N2',4:'N3',5:'R'}
plt.yticks(list(y_labels.keys()), y_labels.values())
plt.show()

However, I want to change the order the data is shown on the y axis (not just relabel them) and have this order (from top to bottom y axis): W,R,N1,N2,N3 and plot them both as a scatter plot but as a line plot as well.Thank you.


Solution

  • IIUC, convert the y data to numeric first, which should plot the points in the correct order, and change the yticklabels at the end:

    fig, ax = plt.subplots()
    ax.plot(conv_tup/2, np.array(y).astype(int), '-o')
    ax.set_yticks(range(6), ['', 'N3', 'N2', 'N1', 'R', 'W'])
    plt.show()
    

    Output:

    enter image description here

    Swapping the 1 and 3:

    y_star = np.array(y).astype(int)
    is_1 = (y_star == 1)
    is_3 = (y_star == 3)
    y_star[is_1] = 3
    y_star[is_3] = 1
    
    fig, ax = plt.subplots()
    ax.plot(conv_tup/2, y_star, '-o')
    ax.set_yticks(range(6), ['', 'N3', 'N2', 'N1', 'R', 'W'])
    plt.show()
    

    Output:

    enter image description here