如何在Matplotlib的x轴上分配相等的缩放比例?

Sai*_*irl 6 python matplotlib

我现在拥有的是:

x = [3.0, 4.0, 5.0, 5.0, 6.0, 7.0, 9.0, 9.0, 9.0, 11.0]
y = [6.0, 5.0, 4.0, 2.5, 3.0, 2.0, 1.0, 2.0, 2.5, 2.5]
Run Code Online (Sandbox Code Playgroud)

其中生成以下图表:

在此输入图像描述

我想要的是在我的轴上有相同的比例.因此,它不是在7和9以及9和11之间具有如此大的间隙,而是与所有其他空间相同的空间.它看起来像这样:

在此输入图像描述

为了消除图中的8和10,我使用了刻度线.这是相关代码:

ax=fig.add_subplot(111, ylabel="speed")
ax.plot(x, y, 'bo')
ax.set_xticks(x) 
Run Code Online (Sandbox Code Playgroud)

matplotlib页面上的所有示例都没有我想要的任何内容.我一直在查看文档,但所有"缩放"相关并不能达到我想要的目的.

可以这样做吗?

Chr*_*ris 4

根据我对 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]]    
Run Code Online (Sandbox Code Playgroud)

此时我们得到print x_normalised了

[0, 1, 2, 2, 3, 4, 5, 5, 5, 6]
Run Code Online (Sandbox Code Playgroud)

所以密谋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')
Run Code Online (Sandbox Code Playgroud)

给予

使用 matplotlib 绘制的解决方案结果

set_xticklabels最后,我们可以使用以下命令更改 x 轴刻度标签以反映原始 x 数据的实际值

ax.set_xticklabels(nonRepetitive_x)
Run Code Online (Sandbox Code Playgroud)

编辑要使最终图看起来像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 
Run Code Online (Sandbox Code Playgroud)

  • 查看 [matplotlib.axes API](http://matplotlib.sourceforge.net/api/axes_api.html),特别是方法 [`set_xticks`](http://matplotlib.sourceforge.net/api/ axes_api.html#matplotlib.axes.Axes.set_xticks) 和 [`set_xticklabels`](http://matplotlib.sourceforge.net/api/axes_api.html#matplotlib.axes.Axes.set_xticklabels)。 (2认同)