除了我对 OP 的评论之外,您还可以根据自然数 1 到 n 进行绘图,其中 n 是数据集中唯一横坐标值的数量。然后您可以将 x 刻度标签设置为这些唯一值。我在实现这一点时遇到的唯一麻烦是处理重复的横坐标值。为了保持这个一般性,我想出了以下内容
from collections import Counter # Requires Python > 2.7
# Test abscissa values
x = [3.0, 4.0, 5.0, 5.0, 6.0, 7.0, 9.0, 9.0, 9.0, 11.0]
# Count of the number of occurances of each unique `x` value
xcount = Counter(x)
# Generate a list of unique x values in the range [0..len(set(x))]
nonRepetitive_x = list(set(x)) #making a set eliminates duplicates
nonRepetitive_x.sort() #sets aren't ordered, so a sort must be made
x_normalised = [_ for i, xx in enumerate(set(nonRepetitive_x)) for _ in xcount[xx]*[i]]
在这一点上,我们print x_normalised
有
[0, 1, 2, 2, 3, 4, 5, 5, 5, 6]
所以密谋y
反对x_normalised
from matplotlib.figure import Figure
fig=Figure()
ax=fig.add_subplot(111)
y = [6.0, 5.0, 4.0, 2.5, 3.0, 2.0, 1.0, 2.0, 2.5, 2.5]
ax.plot(x_normalised, y, 'bo')
给
set_xticklabels
最后,我们可以使用using更改 x 轴刻度标签以反映原始 x 数据的实际值
ax.set_xticklabels(nonRepetitive_x)
编辑要使最终图看起来像 OP 中所需的输出,可以使用
x1,x2,y1,y2 = ax.axis()
x1 = min(x_normalised) - 1
x2 = max(x_normalised) + 1
ax.axis((x1,x2,(y1-1),(y2+1)))
#If the above is done, then before set_xticklabels,
#one has to add a first and last value. eg:
nonRepetitive_x.insert(0,x[0]-1) #for the first tick on the left of the graph
nonRepetitive_x.append(x[-1]+1) #for the last tick on the right of the graph