Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python reorder level in data frame for step plot

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:

enter image description here

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

like image 591
user1480478 Avatar asked Dec 05 '25 16:12

user1480478


2 Answers

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()

enter image description here

like image 75
ImportanceOfBeingErnest Avatar answered Dec 08 '25 05:12

ImportanceOfBeingErnest


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)

enter image description here

like image 32
mrzo Avatar answered Dec 08 '25 04:12

mrzo



Donate For Us

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