2

I would like to make a scatter plot for the following DataFrame with x-axis topic and y-axis content.

In[18]: test=pd.read_excel('test.xlsx')
In[19]: test
Out[19]:    topic content
        0    A1       a
        1    A1       b
        2    A2       b
        3    A2       c
        4    A2       e
        5    A3       a
        6    A3       c
        7    A3       d
        8    A4       b
        9    A4       c

Below is my current plot:

My current plot

How can I sort y-axis in a different order? Such as ['b', 'c', 'a', 'd', 'e'] with 'b' in the bottom?

Ondra K.
  • 2,767
  • 4
  • 23
  • 39
Jinglebell
  • 55
  • 1
  • 1
  • 5

1 Answers1

2

If the order of the x-axis is not important, you could use pandas Categorial and sort_values():

df = pd.DataFrame([['A1','a'], ['A1','b'], ['A2','b'], ['A2','c'], ['A2','e'], ['A3','a'], ['A3','c'], ['A3','d'], ['A4','b'], ['A4','c']], columns=['topic','content'])

order = ['b', 'c', 'a', 'd', 'e']
df['content'] = pd.Categorical(df['content'], order)
df.sort_values(by=['content'], inplace=True)

plt.scatter(df['topic'], df['content'])

enter image description here

Edit Another solution could be replacing each value of content with an integener, df['content'] = [order.index(x) for x in df['content']] and set the yticks:

order = ['b', 'c', 'a', 'd', 'e']
df = pd.DataFrame([['A1','a'], ['A1','b'], ['A2','b'], ['A2','c'], ['A2','e'], ['A3','a'], ['A3','c'], ['A3','d'], ['A4','b'], ['A4','c']], columns=['topic','content'])

df['content'] = [order.index(x) for x in df['content']]

plt.yticks(range(len(order)), order)
plt.scatter(df['topic'], df['content'])

enter image description here

ilja
  • 2,592
  • 2
  • 16
  • 23
  • Thanks!! What if I also want x-axis in the order of A1, A2, A3, A4? – Jinglebell May 01 '19 at 12:37
  • There is no optimal solution (see. https://stackoverflow.com/questions/53191411/sorting-labels-in-matplotlib-scaterplot), but maybe you could use a workarourn with integers, see my edit. – ilja May 01 '19 at 12:55
  • Happy to help, and welcome to Stack Overflow. If this answer solved your issue, please mark it as accepted. :-) – ilja May 01 '19 at 13:10