Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib will not show a polygon plot centered by default?

For all types plots I've seen so far, matplotlib will automatically center them when no xlim(), ylim() values are given. Example:

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

But when I plot a Polygon

ax = plt.subplot(111)
triangle = plt.Polygon(A_pts, fill=None, edgecolor='r')
ax.add_patch(triangle)
plt.show()

the plot window is shown with limits [0, 1] for both axis, which results in the polygon not being visible. I have to explicitly pass proper limits so that it will show in the plot window

ax.set_xlim(80, 250)
ax.set_ylim(120, 170)

Is this by design or am I missing something?

like image 322
Gabriel Avatar asked Dec 04 '22 22:12

Gabriel


2 Answers

When adding a patch, the data limits of the axes are changed, which you can see by printing ax.dataLim.bounds. However, add_patch does not call the automlimits function, while most other plotting commands do.

This means you can either set the limits of the plot manually (as in the question) or you can just call ax.autoscale_view() to adjust the limits. The latter has of course the advantage that you don't need to determine the limits beforehands and that the margins are preserved.

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() 

Once you would add some other plot which does automatically scale the limits, there is no need to call autoscale_view() any more.

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

like image 178
ImportanceOfBeingErnest Avatar answered Dec 11 '22 17:12

ImportanceOfBeingErnest


It is by design. Things like plot and scatter are plotting functions that take in data, create the artists and form the plot/adjust the axes. add_patch on the other hand, is more of an artist control method (it does not create the artist, the artist itself gets passed in). As mentioned in a comment by Paul H, it is at the lowest level of the public API and at that level it is assumed that you have full control of the figure.

like image 22
Ajean Avatar answered Dec 11 '22 16:12

Ajean