对于目前为止我见过的所有类型的图,matplotlib
会在没有给定 xlim()、ylim()
值时自动将它们居中。示例:
import matplotlib.pyplot as plt
A_pts = [(162.5, 137.5), (211.0, 158.3), (89.6, 133.7)]
ax = plt.subplot(111)
ax.scatter(*A_pts)
plt.show()
但是当我绘制一个Polygon
ax = plt.subplot(111)
triangle = plt.Polygon(A_pts, fill=None, edgecolor='r')
ax.add_patch(triangle)
plt.show()
绘图窗口显示的两个轴都具有限制 [0, 1]
,这导致多边形不可见。我必须明确传递适当的限制,以便它显示在绘图窗口中
ax.set_xlim(80, 250)
ax.set_ylim(120, 170)
这是设计使然还是我遗漏了什么?
最佳答案
添加补丁时,坐标轴的数据限制会发生变化,您可以通过打印ax.dataLim.bounds
来查看。但是,add_patch
不会调用 automlimits 函数,而大多数其他绘图命令会调用。
这意味着您可以手动设置绘图的限制(如问题中所述),也可以只调用 ax.autoscale_view()
来调整限制。后者的优势当然是您无需事先确定限制,并且可以保留边距。
import matplotlib.pyplot as plt
pts = [(162, 137), (211, 158), (89, 133)]
ax = plt.subplot(111)
triangle = plt.Polygon(pts, fill=None, edgecolor='r')
ax.add_patch(triangle)
print ax.dataLim.bounds
ax.autoscale_view()
plt.show()
一旦您添加了一些其他自动缩放限制的绘图,就无需再调用 autoscale_view()
。
import matplotlib.pyplot as plt
pts = [(162, 137), (211, 158), (89, 133)]
ax = plt.subplot(111)
triangle = plt.Polygon(pts, fill=None, edgecolor='r')
ax.add_patch(triangle)
ax.plot([100,151,200,100], [124,135,128,124])
plt.show()
关于python - Matplotlib 默认不会显示居中的多边形图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43187677/