问题
I'm to Python and learning it by doing. I want to make two plots with matplotlib in Python. The second plot keeps the limits of first one. Wonder how I can change the limits of each next plot from previous. Any help, please. What is the recommended method?
X1 = [80, 100, 120, 140, 160, 180, 200, 220, 240, 260]
Y1 = [70, 65, 90, 95, 110, 115, 120, 140, 155, 150]
from matplotlib import pyplot as plt
plt.plot(
X1
, Y1
, color = "green"
, marker = "o"
, linestyle = "solid"
)
plt.show()
X2 = [80, 100, 120, 140, 160, 180, 200]
Y2 = [70, 65, 90, 95, 110, 115, 120]
plt.plot(
X2
, Y2
, color = "green"
, marker = "o"
, linestyle = "solid"
)
plt.show()
回答1:
There are two ways:
The quick and easy way; set the x and y limits in each plot to what you want.
plt.xlim(60,200)
plt.ylim(60,200)
(for example). Just paste those two lines just before both plt.show() and they'll be the same.
The harder, but better way and this is using subplots.
# create a figure object
fig = plt.figure()
# create two axes within the figure and arrange them on the grid 1x2
ax1 = fig.add_Subplot(121)
# ax2 is the second set of axes so it is 1x2, 2nd plot (hence 122)
# they won't have the same limits this way because they are set up as separate objects, whereas in your example they are the same object that is being re-purposed each time!
ax2 = fig.add_Subplot(122)
ax1.plot(X1,Y1)
ax2.plot(X2,Y2)
回答2:
Here is one way for you using subplot
where plt.subplot(1, 2, 1)
means a figure with 1 row (first value) and 2 columns (second value) and 1st subfigure (third value in the bracket, meaning left column in this case). plt.subplot(1, 2, 2)
means subplot in the 2nd column (right column in this case).
This way, each figure will adjust the x- and y-limits according to the data. There are another ways to do the same thing. Here is a SO link for you.
from matplotlib import pyplot as plt
fig = plt.figure(figsize=(10, 4))
plt.subplot(1, 2, 1)
X1 = [80, 100, 120, 140, 160, 180, 200, 220, 240, 260]
Y1 = [70, 65, 90, 95, 110, 115, 120, 140, 155, 150]
plt.plot(X1, Y1, color = "green", marker = "o", linestyle = "solid")
# plt.plot(X1, Y1, '-go') Another alternative to plot in the same style
plt.subplot(1, 2, 2)
X2 = [80, 100, 120, 140, 160, 180, 200]
Y2 = [70, 65, 90, 95, 110, 115, 120]
plt.plot(X2, Y2, color = "green", marker = "o", linestyle = "solid")
# plt.plot(X2, Y2, '-go') Another alternative to plot in the same style
Output
来源:https://stackoverflow.com/questions/52423697/multiple-plots-with-matplotlib-in-python