简体   繁体   中英

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.

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:

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. Autocomplete can be a wonderful thing in this case.

In short: 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 ):

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

which will lock down all of the scales (you can do x and y separately as well).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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