Matplotlib不会显示默认居中的多边形图?

时间:2017-04-03 14:45:50

标签: python matplotlib polygon

对于我目前看到的所有类型的地块,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()

enter image description here

但是当我绘制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)

这是设计还是我错过了什么?

2 个答案:

答案 0 :(得分:7)

添加补丁时,轴的数据限制会发生变化,您可以通过打印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()

enter image description here

答案 1 :(得分:5)

这是设计的。像plotscatter之类的东西是绘制数据,创建艺术家和形成绘图/调整轴的函数。另一方面,add_patch更像是一种艺术家控制方法(它不会创造艺术家,艺术家本身也会被传入)。正如Paul H的评论中所提到的,它处于公共API的最低级别,在该级别,假设您完全控制了该数字。