Ailurophile
Ailurophile

Reputation: 3005

How to invert the order in Matplotlib diverging plot?

I have a dataframe with ordered values with ordered index

     PERFORMER_ID   Number_of_Activities    colors
0        535    24  darkgreen
1        1FD    20  darkgreen
2        4F8    14  darkgreen
3        A8D    14  darkgreen
4        57D    11  darkgreen
5        D8B    10  darkgreen
6        064    9   darkgreen
7        D9F    9   darkgreen
8        684    9   darkgreen
9        F87    9   darkgreen
10       5A8    -1  red
11       5A6    -1  red
12       5A1    -1  red
13       59B    -1  red
14       59A    -1  red
15       587    -1  red
16       581    -1  red
17       578    -1  red
18       574    -1  red
19       7C3    -1  red

I'm trying to diverging plot with the above data

# Draw plot
import matplotlib.patches as patches

plt.figure(figsize=(10,12), dpi= 80)
plt.hlines(y=data.index, xmin=0, xmax=data.Number_of_Activities, color=data.colors, alpha=0.4, linewidth=1)
plt.scatter(data.Number_of_Activities, data.index, color=data.colors, s=600, alpha=0.6)

for x, y, tex in zip(data.Number_of_Activities, data.index, data.Number_of_Activities):
    t = plt.text(x, y, abs(tex), horizontalalignment='center', 
                 verticalalignment='center', fontdict={'color':'white'})
    
plt.yticks(data.index, data.PERFORMER_ID)
plt.xticks(fontsize=12)



# # Add Patches
# p1 = patches.Rectangle((-2.0, -1), width=.3, height=3, alpha=.2, facecolor='red')
# p2 = patches.Rectangle((1.5, 27), width=.8, height=5, alpha=.2, facecolor='green')
# plt.gca().add_patch(p1)
# plt.gca().add_patch(p2)

# Decorate
plt.title('Performers with Most & Less Activities', fontdict={'size':12})
plt.grid(linestyle='--', alpha=0.5)
plt.show()

enter image description here

I got the plot in reverse order. How do I make it plot with the given order or how can I reverse the values in the above plot (The bottom 10 to up and top 10 to bottom)?

Upvotes: 3

Views: 308

Answers (1)

r-beginners
r-beginners

Reputation: 35205

The easiest way to deal with this is to reorder and re-index the data.

data.sort_index(ascending=False, ignore_index=True, inplace=True)

enter image description here

Upvotes: 1

Related Questions