I plotted a step plot and the order of the y ticks are not what I want. How can I reorder them?
Here are the codes:
import numpy as np
import matplotlib.pyplot as plt
df = {'col1': [1, 2, 3, 4,5,6], 'col2': ['a', 'a', 'b', 'c', 'a','b']}
dat = pd.DataFrame(data = df)
plt.step(dat['col1'], dat['col2'])
plt.show()
This is the plot I got:

But What I want is the order of the y tick to be [b, c, a] not [a,b,c]. How can I do this?
Thank you,
LT
Unfortunately, matplotlib currently does not allow to predetermine the order of categories on an axis. One option though, is to first plot something in the correct order to the axes, and then remove it. This will fix the order for the subsequent real plotting.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
order = list("bca")
dic = {'col1': [1, 2, 3, 4,5,6], 'col2': ['a', 'a', 'b', 'c', 'a','b']}
df = pd.DataFrame(dic)
sentinel, = plt.plot(np.repeat(df.col1.values[0], len(order)), order)
sentinel.remove()
plt.step(df['col1'], df['col2'])
plt.show()

You can use a mixture of pd.Series as mapper and ax.set_yticks:
import numpy as np
import matplotlib.pyplot as plt
df = {'col1': [1, 2, 3, 4,5,6], 'col2': ['a', 'a', 'b', 'c', 'a','b']}
dat = pd.DataFrame(data = df)
# Create a mapper from character to rank with the desired order:
order = ['b', 'c', 'a']
rank = pd.Series(range(len(order)), index=order)
fig, ax = plt.subplots()
ax.step(dat['col1'], rank.loc[dat['col2']])
ax.set_yticks(rank.values);
ax.set_yticklabels(rank.index)

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With