gpt4 book ai didi

python - matplotlib,如何压缩x轴的部分

转载 作者:行者123 更新时间:2023-12-01 02:47:46 25 4
gpt4 key购买 nike

嘿伙计们,这是我第一次在这里发帖,希望这个问题不是太微不足道。我尝试寻找解决方案,但找不到我想要的。

我这里有一个非常简单的代码,它绘制 xy 线图

x = [1,2,3,10,11]
y = [1,2,3,4,5]

plt.plot(x,y)
plt.xticks(x)

图表如下所示: Graph

我想要做的是压缩x轴,使得每个点之间的间距相同。例如,3 到 10 之间的间距与 1 到 2 之间的间距相同。

有办法做到这一点吗?谢谢!

最佳答案

这应该可以做到:

from matplotlib import pyplot as plt

fig,ax = plt.subplots()

x = [1,2,3,10,11]
y = [1,2,3,4,5]

ax.plot(y,marker='o')
ax.set_xticks([i for i in range(len(y))])
ax.set_xticklabels(x)
plt.show()

我添加了标记以更好地可视化数据点。结果如下: result of the posted code

编辑:

如果您想可视化轴不连续,您可以在 this answer 中找到帮助。 .

编辑2:

在我的示例中,我仅将 y 值传递给 plot 函数,这意味着 x 值是隐式计算的为 [1,2,3,4,5]。当然,您也可以显式传递每个绘图命令的 x 值,从而改变绘图开始的 x 值。对于您评论中的示例,这将是:

fig,ax = plt.subplots()

y1 = [1,2,3,4,5]
x1 = [i for i in range(len(y1))]
y2 = [2,3,4,5,6]
x2 = [i+1 for i in range(len(y2))]

xticks = list(set(x1+x2)) #or more explicit: [i for i in range(6)]
xtick_labels = [1,2,3,10,11,12]

ax.plot(x1,y1,marker='o')
ax.plot(x2,y2,marker='x')
ax.set_xticks(xticks)
ax.set_xticklabels(xtick_labels)
plt.show()

关于python - matplotlib,如何压缩x轴的部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45107207/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com