扩展坐标轴以填充图形,x和y同尺度
我知道两件事,但它们是分开的。
figure.tight_layout
会扩展我当前的坐标轴
axes.aspect('equal')
会保持x轴和y轴的比例相同。
但是当我同时使用这两者时,我得到的是一个正方形的坐标轴视图,而我想要的是扩展的视图。保持相同的比例是指x轴和y轴从0到1的距离是一样的。
有没有办法做到这一点?保持相同的比例,同时扩展到整个图形(而不仅仅是一个正方形)。这个方法还应该适用于自动缩放。
2 个回答
1
1
可能有更简单的方法,但至少你可以手动来做。这里有一个非常简单的例子:
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot([0,1],[1,0])
ax.set_aspect(1)
ax.set_xlim(0, 1.5)
这个例子会生成一个图像
这个图像保持了宽高比。
如果你想要使用 tight_layout
提供的自动缩放功能,那么你需要自己做一些计算:
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot([0,1],[1,0])
fig.tight_layout()
# capture the axis positioning in pixels
bb = fig.transFigure.transform(ax.get_position())
x0, y0 = bb[0]
x1, y1 = bb[1]
width = x1 - x0
height = y1 - y0
# set the aspect ratio
ax.set_aspect(1)
# calculate the aspect ratio of the plot
plot_aspect = width / height
# get the axis limits in data coordinates
ax0, ax1 = ax.get_xlim()
ay0, ay1 = ax.get_ylim()
awidth = ax1 - ax0
aheight = ay1 - ay0
# calculate the plot aspect
data_aspect = awidth / aheight
# check which one needs to be corrected
if data_aspect < plot_aspect:
ax.set_xlim(ax0, ax0 + plot_aspect * aheight)
else:
ax.set_ylim(ay0, ay0 + awidth / plot_aspect)
当然,你可以随意设置 xlim
和 ylim
,比如说,你可能想在刻度的两端添加相同的空间。