使用python制作非数字x轴的直方图

时间:2018-07-23 00:54:40

标签: python matplotlib astronomy

我有一个快速/肮脏的脚本,可以将质量分类为光谱类型,并制作出像这样的恒星质量直方图

import matplotlib.pyplot as plt
import numpy as np
% matplotlib inline

star_masses = np.array([0.359, 0.325,0.842, 0.359, 0.245, 0.445, 0.558, 0.117, 0.245, 0.177, 0.558, 0.058, 0.637, 0.222, 0.245, 0.039, 0.177])
M2 = []
M12 = []
K7 = []
M6 = []
M1 = []
M0 = []
M5 = []
M35 = []
M42 = []
M625 = []
M37 = []
T6 = []
M8 = []

for i in star_masses:
    if i == 0.359:
        M2.append(i)
    if i == 0.325:
        M12.append(i)
    if i == 0.842:
        K7.append(i)
    if i == 0.245:
        M6.append(i)
    if i == 0.445:
        M1.append(i)
    if i == 0.558 or 0.637:
        M0.append(i)
    if i == 0.117:
        M5.append(i)
    if i == 0.245:
        M35.append(i)
    if i == 0.058:
        M625.append(i)
    if i == 0.222:
        M37.append(i)
    if i == 0.039:
        T6.append(i)
    if i == 0.177:
        M8.append(i)

plt.hist(star_masses, bins = 15)
plt.xlabel('Stellar Mass')
plt.ylabel('# of Stars')
plt.title ('Stellar Mass')

我正在尝试绘制光谱类型的直方图,以便每个bin是x轴上光谱类型的名称,y轴是恒星数量,但是我不知道如何获得非光谱值x轴上的数字

1 个答案:

答案 0 :(得分:0)

您可以使用set_xticklabels

import matplotlib.pyplot as plt
import numpy as np

star_masses = np.array([0.359, 0.325,0.842, 0.359, 0.245, 0.445, 0.558, 0.117, 0.245, 0.177, 0.558, 0.058, 0.637, 0.222, 0.245, 0.039, 0.177])
star_names= ['star%i'%ii for ii in range(13)]
M2 = []
M12 = []
K7 = []
M6 = []
M1 = []
M0 = []
M5 = []
M35 = []
M42 = []
M625 = []
M37 = []
T6 = []
M8 = []

for i in star_masses:
    if i == 0.359:
        M2.append(i)
    if i == 0.325:
        M12.append(i)
    if i == 0.842:
        K7.append(i)
    if i == 0.245:
        M6.append(i)
    if i == 0.445:
        M1.append(i)
    if i == 0.558 or 0.637:
        M0.append(i)
    if i == 0.117:
        M5.append(i)
    if i == 0.245:
        M35.append(i)
    if i == 0.058:
        M625.append(i)
    if i == 0.222:
        M37.append(i)
    if i == 0.039:
        T6.append(i)
    if i == 0.177:
        M8.append(i)

f, ax = plt.subplots()
ax.hist(star_masses, bins = 15)
ax.set_xlabel('Stellar Mass')
ax.set_xticklabels(star_names)
ax.set_ylabel('# of Stars')
ax.set_title ('Stellar Mass')
plt.show()