带有自定义刻度的散点图 [英] Scatter plot with custom ticks
问题描述
我想在 y 轴上绘制波长(浮点数)的散点图,在 x 轴上绘制光谱类(字符/字符串列表),labels = ['B','A','F','G'、'K'、'M'].数据保存在 pandas dataframe, df 中.
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
无法将字符串转换为浮点数:'G'
could not convert string to float: 'G'
解决此问题后,我想按如下方式制作自定义 xticks.但是,我怎么能
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)
推荐答案
首先,我认为您必须将这些字符串映射到整数,然后 matplotlib 可以决定放置这些点的位置.
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})
然后绘制散点图,
fig, ax = plt.subplots()
ax.scatter(df['Spec Type Index'], df['Disk Major Axis "'])
最后,
ax.set_xticklabels(labels)
这篇关于带有自定义刻度的散点图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!