x轴上的区间

3 投票
1 回答
3724 浏览
提问于 2025-04-18 08:20

我想改变数字之间的间隔大小。x轴的范围显然是从10到26。但是我希望每个整数都能显示出来:10、11、12、13等等……我还希望每个区间的宽度是0.5,这样我就可以有一个从10.5到11的区间,或者从24到24.5的区间等等……因为否则,Python输出的直方图的区间会是随机的,没法确定。以下是我现在的代码:

import random
import numpy
from matplotlib import pyplot
import numpy as np

data = np.genfromtxt('result.csv',delimiter=',',skip_header=1, dtype=float)

magg=[row[5] for row in data]
magr=[row[6] for row in data]

bins = numpy.linspace(10, 26)

pyplot.hist(magg, bins, alpha=0.5, color='g', label='mag of g')
pyplot.hist(magr, bins, alpha=0.5, color='r', label='mag of r')
pyplot.legend(loc='upper left')
pyplot.show()

1 个回答

2

使用一个坐标轴定位器,特别是 MultipleLocator。根据你的例子,代码可以写成这样:

import matplotlib.pyplot as plt
import numpy as np

x = np.random.random_integers(low=10, high=27, size=37)

bins = np.linspace(10, 26)

fig, ax = plt.subplots()
hist = ax.hist(x, bins, alpha=0.5, color='g', label='mag of g')
ax.xaxis.set_major_locator(plt.MultipleLocator(1))

enter image description here

撰写回答