Reputation: 584
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
Upvotes: 3
Views: 147
Reputation: 339560
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()
Upvotes: 2
Reputation: 2135
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)
Upvotes: 1