Python reordering levels in data frames used for step diagrams

Python reordering levels in data frames used for step diagrams … here is a solution to the problem.

Python reordering levels in data frames used for step diagrams

I

drew a step chart and the order of the y scale is not what I want. How can I reorder them?

The code is as follows:

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

Here’s the plot I got:

enter image description here

But what I want is that the order of the y scale is [b, c, a] instead of [a,b,c]. What should I do?

Thanks,

LT

Solution

Unfortunately, matplotlib currently does not allow predetermining the order of categories on the axis. One option, though, is to first draw something on the axis in the correct order and then remove it. This will fix the order of subsequent real drawings.

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

Related Problems and Solutions