简体   繁体   中英

How to sort values with strings on the axis in scatter plot

How to sort the values on x axis in an ascending order in a scatter plot?

fig, ax = plt.subplots()
fig.set_size_inches(18, 8)
ax.scatter(data=ipl,x='budget',y='player')

n = 4

for idx, label in enumerate(ax.xaxis.get_ticklabels()):
    if idx % n != 0:
        label.set_visible(False)

In the image,the values on x axis are randomly arranged.

和

you can use a small regex to extract the values, convert to int and sort by the integer values:

#dummy data
ipl = pd.DataFrame(
    {
        'budget': ['${}M'.format(a) for a in np.random.randint(0,200,10)],
        'player': np.random.randint(-10,10,10)
    }

)

ipl['values'] = ipl['budget'].str.extract('([0-9]+)').astype(int)
ipl.sort_values(by='values', inplace=True)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM