python - 如何在 Matplotlib 中的 x 轴上分配相等的比例?

标签 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]

生成如下图:

enter image description here

我想要的是在我的轴上有相同的缩放比例。因此,与其在 7 和 9 以及 9 和 11 之间有这么大的差距,不如像其他所有空间一样是一个平等的空间。它看起来像这样:

enter image description here

为了消除图表中的 8 和 10,我使用了刻度线。相关代码如下:

ax=fig.add_subplot(111, ylabel="speed")
ax.plot(x, y, 'bo')
ax.set_xticks(x) 

matplotlib page 上没有任何示例有我想要的任何东西。我一直在浏览文档,但与“缩放”相关的所有内容都没有按照我的意愿进行。

这能做到吗?

最佳答案

根据我对 OP 的评论,您可以针对 1 到 n 的自然数进行绘图,其中 n 是数据集中未确定的横坐标值的数量。然后您可以将 x ticklabels 设置为这些唯一值。我在实现这个过程中遇到的唯一麻烦是处理重复的横坐标值。为了尽量保持这个一般性,我想出了以下内容

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]

所以根据 x_normalised 绘制 y

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')

给予

Result of solution presented as plotted using matplotlib

最后,我们可以使用 set_xticklabels 更改 x 轴刻度标签以反射(reflect)我们原始 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 

关于python - 如何在 Matplotlib 中的 x 轴上分配相等的比例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12045392/

相关文章:

python main函数不返回数据框

python - 如何使用 secondary_y 调整 pandas 图的刻度和标签大小

python-2.7 - 如何在matplotlib中控制科学计数法?

pandas - Matplotlib:如何使用 pandas plot api 在散点图中绘制一个空圆?

python - 如何在 Bokeh 中绘制水平条形图(Python)

python - 如何将轴标签绘制为时间(以小时、分钟等为单位)

python - Django 查询单下划线表现得像双下划线?

python - 使用 Beautiful Soup 和 Python 抓取 Asp.NET 网站

python 使用 cookie 请求登录

python - Matplotlib 在所有子图上显示 x-ticks 和唯一的 y 标签