BramAdafruit
BramAdafruit

Reputation: 71

Set order of y axis in python with Matplotlib

I am trying to plot simple arrays with values a,b,c and d. I want to plot these arrays in alphabetical order. For example I added a plot of the fifth row in the dataframe given below, the y-value starts at 'a' (good) and then the next y-value is 'c' (wrong), I want to have 'b' at that place. In short; the y values should be in alphabetical order without losing the x value order.

enter image description here

The head of the dataset is given. It is very basic.

enter image description here

And the (very basic) code bins = ['a', 'b', 'c', 'd']; plt.plot((X_sax.iloc[4,:])); plt.yticks(bins);

Can Someone help me?

Thanks!

Upvotes: 1

Views: 5032

Answers (3)

Arty
Arty

Reputation: 16747

Next code uses NumPy-only functions for very fast processing of data:

import matplotlib.pyplot as plt, pandas as pd, numpy as np
# ----- Input -----
bins = ['a', 'b', 'c', 'd']
X_sax = pd.DataFrame(data = np.array([list('accbcbbbbcb')]))
print(X_sax)
# ----- Show ------
v = X_sax.values[0, :] # Choose which row to show
b = np.sort(bins)
v = np.searchsorted(b, v)
plt.plot(v)
plt.yticks(np.arange(b.size), b)
plt.show()

You may also try code above online!

Output:

   0  1  2  3  4  5  6  7  8  9 10
0  a  c  c  b  c  b  b  b  b  c  b

and

enter image description here

Upvotes: 1

B. Bogart
B. Bogart

Reputation: 1075

I would map the y axis to values and then name the axis as @Yogesh suggested.

from matplotlib import pyplot as plt  
X_sax = list('accbcbbbbcb')

datamap = {'a':1,'b':2,'c':3, 'd':4}
X_sax = list(map(lambda x: datamap[x], X_sax))
           
plt.plot((X_sax))
plt.yticks([1,3,2,4], bins)

gives:

chart

Upvotes: 1

Yogesh
Yogesh

Reputation: 801

Use this:

plt.yticks(np.arange(len_of_y_ticks), y_order)

Eg:

x = np.arange(0, 11)
y = 'a c c b c b b b b c b'.split()
y_order = sorted(set(y))
len_of_y_ticks = len(set(y))
y = list(map(lambda x: ord(x)-97, y))
plt.plot(x, y)
plt.yticks(np.arange(4), y_order)
plt.show()

Upvotes: 0

Related Questions