python - 当折线图不从第一个 x 轴刻度开始时,如何使 x 轴刻度之间的间距保持一致

标签 python matplotlib

最初我在一个图上有一张图:

x1 = [0,1,2,3,10,11]
y1 = [1,2,3,4,5,6]
ax.plot(x1,y1)

但这导致 x 轴标签之间的间距不一致,如下所示:

enter image description here

为了解决这个问题,我做了

ax.plot(y1)
ax.set_xticklabels(x1)

然后将图表更改为这样(这就是我想要的):

enter image description here

但是现在假设我有另一个线图,它是 y2 = [2,3,4,5,6,7] 我想将此图添加到同一个图中,但我想要例如,对其进行偏移,使其从 x = 2 开始。

当我说 ax.plot(y2) 时,它将从默认的第一个刻度 (x=1) 开始,如果我说 ax.plot(x2,y2) > 第二条线图将出现与 Graph1 相同的问题。

基本上,我希望最终结果看起来像两条平行线,但其中一条从 x = 2 开始。任何建议将不胜感激,谢谢!

最佳答案

如果,正如您在问题中所说,您实际上想要绘制从 x=2 开始的 y2,那么两条线将重叠。

fig,ax = plt.subplots()

ticks = [0,1,2,3,10,11]

y1 = [1,2,3,4,5,6]
y2 = [2,3,4,5,6,7]

x1 = np.arange(1,len(y1)+1,1)
x2 = np.arange(2,len(y2)+2,1)

ax.plot(x1,y1)
ax.plot(x2,y2)

ax.set_xticklabels(ticks)

plt.show()

产品:

enter image description here

您最后说您想要两条平行线,但其中一条从 x = 2 开始。如果是这样,那么您可以执行与上面相同的操作,但使用 y1 代替:

ax.plot(x2,y1)

给出:

enter image description here

关于python - 当折线图不从第一个 x 轴刻度开始时,如何使 x 轴刻度之间的间距保持一致,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45169270/

相关文章:

python - Django 2.0 - 使用 allauth 登录 Facebook - 无法加载 URL : The domain of this URL isn't included in the app's domains

python - 绘制单个 XGBoost 决策树

python - 在 matplotlib 中绘制预测点和 ground_truth 点之间的线

python - 绘制一维数据的 KMeans 聚类和分类

python - Linux 下小型 Python 程序(非模块)的正确安装脚本

python - pandas - 数据框列值的线性回归

python - 使用 xml.etree 的基本 Python 解析 XML - 问题

python - 是否有相当于 MATLAB 的 datacursormode 的 matplotlib?

python - 我的 matplotlib ArtistAnimation 做错了什么?

python - Django 更新 Celery 异步任务中的设置