我使用matplotib的AxesAPI绘制了一些数字。我画的线之一代表理论上的预期线。它没有原始y和x限制的含义。我想要的是让matlplotlib在自动缩放限制时忽略它。我以前要做的是检查当前极限,然后绘制并重置极限。问题在于,当我绘制第三张图时,将与理论线一起重新计算极限值,这实际上扩展了图。
# Boilerplate from matplotlib.figure import Figure from matplotlib.backends.backend_pdf import FigureCanvasPdf from numpy import sin, linspace fig = Figure() ax = fig.add_subplot(1,1,1) x1 = linspace(-1,1,100) ax.plot(x1, sin(x1)) ax.plot(x1, 3*sin(x1)) # I wish matplotlib would not consider the second plot when rescaling ax.plot(x1, sin(x1/2.0)) # But would consider the first and last canvas_pdf = FigureCanvasPdf(fig) canvas_pdf.print_figure("test.pdf")
显而易见的方法是手动将限制设置为所需的值。(例如ax.axis([xmin, xmax, ymin, ymax]))
ax.axis([xmin, xmax, ymin, ymax])
如果您不想手动查找限制,则有两种选择…
正如几个人(耕作,Yann和Vorticity)提到的那样,如果您可以绘制最后要忽略的函数,则可以在绘制前禁用自动缩放或将scaley=Falsekwarg传递给plot
scaley=False
plot
import numpy as np import matplotlib.pyplot as plt fig, ax = plt.subplots() x1 = np.linspace(-1,1,100) ax.plot(x1, np.sin(x1)) ax.plot(x1, np.sin(x1 / 2.0)) ax.autoscale(False) #You could skip this line and use scalex=False on ax.plot(x1, 3 * np.sin(x1)) #the "theoretical" plot. It has to be last either way fig.savefig('test.pdf')
请注意zorder,如果您想控制最后一个绘图,可以调整它的绘制,使其绘制在“中间”。
zorder
如果您不想依赖顺序,而只想指定要自动缩放的行列表,则可以执行以下操作:(注意:这是一个简化的版本,假设您要处理Line2D对象,而不是一般的matplotlib艺术家。)
Line2D
import numpy as np import matplotlib.pyplot as plt import matplotlib.transforms as mtransforms def main(): fig, ax = plt.subplots() x1 = np.linspace(-1,1,100) line1, = ax.plot(x1, np.sin(x1)) line2, = ax.plot(x1, 3 * np.sin(x1)) line3, = ax.plot(x1, np.sin(x1 / 2.0)) autoscale_based_on(ax, [line1, line3]) plt.show() def autoscale_based_on(ax, lines): ax.dataLim = mtransforms.Bbox.unit() for line in lines: xy = np.vstack(line.get_data()).T ax.dataLim.update_from_data_xy(xy, ignore=False) ax.autoscale_view() if __name__ == '__main__': main()