matplotlib,如何压缩 x 轴的部分 [英] matplotlib, how to compress parts of x axis

查看:78
本文介绍了matplotlib,如何压缩 x 轴的部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,这是我第一次在这里发布信息,希望这个问题不会太琐碎.我试图寻找解决方案,但找不到我想要的.

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

  x = [1,2,3,10,11]y = [1,2,3,4,5]plt.plot(x,y)plt.xticks(x)

图形如下所示:

编辑:

如果您想看到轴不连续,可以在此答案中找到帮助.

>

EDIT2:

在我的示例中,我仅将 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在范围(len(y2))中的i + 1]xticks = list(set(x1+x2)) #或更明确:[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()

Hey guys this is my first time posting here and hopefully this question isn't too trivial. I tried looking for a solution to this but couldn't find what I wanted.

I have this very simple code here which plots xy line graph

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

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

The graph then looks like this: Graph

What I want to do is compress the x axis such that the spacing between each point is the same. E.g have the space between 3 to 10 be the same as the space between 1 to 2.

Is there a way to do this? Thanks!

解决方案

This should do it:

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

I added the markers to visualise the data points better. The result looks like this:

EDIT:

If you want to visualise that the axis is not continuous, you can find help in this answer.

EDIT2:

In my example, I only passed the y-values to the plot function, which means that the x-values are implicitly calculated to be [1,2,3,4,5]. You can of course also pass the x-values for each plot command explicitly and thereby variate at which x-value which plot starts. For the example in your comment, this would be:

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

这篇关于matplotlib,如何压缩 x 轴的部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆