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

标签 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)

这是设计使然还是我遗漏了什么?

最佳答案

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

关于python - Matplotlib 默认不会显示居中的多边形图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43187677/

相关文章:

google-maps - 如何从 Google map MVCArray 中获取内容?

python - PyQt5 中的 Matplotlib : How to remove the small space along the edge

python - 在 Pandas 图上标记事件点

python - Matplotlib 动画要么在几帧后卡住,要么就是不工作

algorithm - 从切割多边形 (2D) 生成新多边形

python - 过滤 Action 装饰器 - Django Rest Framework

python - 如何动态地将多个数据帧附加在一起?

python - Julia 中的任意精度算术

python:函数正好接受 1 个参数(给定 2 个)

math - 如何检测两个多边形是否具有相同的形状?