Jerome Pitogo de Leon Jerome Pitogo de Leon - 1 year ago 96
Python Question

Scatter plot with custom ticks

I want to do a scatter plot of a wavelength (float) in y-axis and spectral class (list of character/string) in x-axis, labels = ['B','A','F','G','K','M']. Data are saved in pandas dataframe, df.

df['Spec Type Index']
0 NaN
1 A
2 G
. .
. .
167 K
168 Nan
169 G


df['Disk Major Axis "']
0 4.30
1 4.50
2 22.00
. .
. .
167 1.32
168 0.28
169 25.00

Thus, I thought this should be done simply with

plt.scatter(df['Spec Type Index'], df['Disk Major Axis "'])

But I get this annoying error

could not convert string to float: 'G'

After fixing this, I want to make custom xticks as follows. However, how can I

labels = ['B','A','F','G','K','M']
ticks = np.arange(len(labels))
plt.xticks(ticks, labels)

Answer Source

First, I think you have to map those strings to integers then matplotlib can decide where to place those points.

labels = ['B','A','F','G','K','M']
mapping = {'B': 0,'A': 1,'F': 2,'G': 3,'K': 4,'M': 5}
df = df.replace({'Spec Type Index': mapping})

Then plot the scatter,

fig, ax = plt.subplots()
ax.scatter(df['Spec Type Index'], df['Disk Major Axis "'])