使用matplotlib的scale函数对坐标轴进行缩放时,会导致拓扑断开的问题,即图形被切割或者图形内的点被移动。解决方法包括以下两种:
1.使用子图替代缩放:在代码中通过创建子图的方式来达到缩放的效果,在子图中绘制图形,而不是直接对主图进行缩放。例如:
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(10, 3))
ax1 = fig.add_subplot(1, 2, 1) ax1.plot([1, 2, 3], [4, 5, 6]) ax1.set_title("Original plot")
ax2 = fig.add_subplot(1, 2, 2) ax2.plot([1, 2, 3], [4, 5, 6]) ax2.set_xlim(0.5, 2.5) ax2.set_ylim(4.5, 5.5) ax2.set_title("Scaled plot")
plt.tight_layout() plt.show()
2.使用Transform进行缩放:使用Transform对象来进行坐标变换,而不是直接使用scale函数。例如:
import matplotlib.pyplot as plt import matplotlib.transforms as mtransforms
fig = plt.figure(figsize=(10, 3))
ax1 = fig.add_subplot(1, 2, 1) ax1.plot([1, 2, 3], [4, 5, 6]) ax1.set_title("Original plot")
ax2 = fig.add_subplot(1, 2, 2) ax2.plot([1, 2, 3], [4, 5, 6]) scale_x = 2.0 scale_y = 0.5 transform = mtransforms.Affine2D().scale(scale_x, scale_y) ax2.transData = transform + ax2.transData ax2.set_title("Scaled plot")
plt.tight_layout() plt.show()