简体   繁体   English

Matplotlib:在指定的x轴范围内绘制两个图形

[英]Matplotlib: Plotting two graphs within a specified x-axis range

Basically I'm in a situation where I want to lock down the starting point of the graph depending on the first graph that's plotted. 基本上,我要根据绘制的第一个图来锁定图的起点。

eg If i do something like this. 例如,如果我做这样的事情。

import matplotlib.pyplot as plt
plt.plot([7,8,9,10], [1,4,9,16], 'yo')
plt.plot([1,9,11,12], [1,4,9,16], 'ro')
plt.show()

I would like a way to restrict the x-axis to start from 7 so (1,1) from the second plot will be removed. 我想要一种将x轴限制为从7开始的方法,因此将删除第二个绘图中的(1,1)。

Is there a way to do this? 有没有办法做到这一点? I could keep track of it myself but just curious if there's something built in to handle this. 我自己可以跟踪它,但是只是好奇是否有内置的东西可以处理这个问题。

Thanks. 谢谢。

Matplotlib offers you two ways: Matplotlib为您提供两种方法:

import matplotlib.pyplot as plt
plt.plot([7,8,9,10], [1,4,9,16], 'yo')
plt.plot([1,9,11,12], [1,4,9,16], 'ro')
plt.xlim(xmin=7)
plt.show()

or the more object-oriented way 或更面向对象的方式

import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([7,8,9,10], [1,4,9,16], 'yo')
ax.plot([1,9,11,12], [1,4,9,16], 'ro')
ax.set_xlim(xmin=7)
plt.show()

If you don't use IPython, I highly recommend it since you can create the axes object and then type ax.<Tab> and see all of your options. 如果您不使用IPython,则强烈建议您使用IPython,因为您可以创建axes对象,然后键入ax.<Tab>并查看所有选项。 Autocomplete can be a wonderful thing in this case. 在这种情况下,自动完成功能可能是一件很棒的事情。

In short: plt.xlim(). 简而言之:plt.xlim()。

In long: 总而言之:

import matplotlib.pyplot as plt
x1, y1 = ([7,8,9,10], [1,4,9,16])
plt.plot(x1, y1, 'yo')
plt.xlim(min(x1), max(x1))
plt.plot([1,9,11,12], [1,4,9,16], 'ro')
plt.show()

You can turn auto-scaling off after the first plot ( doc ): 您可以在第一个绘图( doc )之后关闭自动缩放功能:

ax = plt.gca()
ax.autoscale(enable=False)

which will lock down all of the scales (you can do x and y separately as well). 这将锁定所有比例尺(您也可以分别进行x和y操作)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM