0

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.

with

warped
  • 8,947
  • 3
  • 22
  • 49
Kishan
  • 334
  • 2
  • 16

1 Answers1

1

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)
warped
  • 8,947
  • 3
  • 22
  • 49
  • The `()` is something that pandas needs, to form an extraction group. See [here](https://stackoverflow.com/questions/54343378/pandas-valueerror-pattern-contains-no-capture-groups), for example. This is not specific to the regex. The regex itselt says: any of the following: [0-9], one or more times: +. – warped Jun 02 '20 at 07:22