Reputation: 143
I am trying to draw a circle with matplotlib, with a diameter, say, of 2 inches and a border of 10 pixels, and I want to save it in a file. This is my code:
import matplotlib.pyplot as plt
from matplotlib import patches
path = 'test.png'
fig1 = plt.figure()
fig1.dpi = 100
fig1.set_size_inches(2, 2)
ax1 = fig1.add_subplot(111, aspect='equal')
ax1.axes.get_xaxis().set_visible(False)
ax1.axes.get_yaxis().set_visible(False)
ax1.add_patch(patches.Circle((0.5, 0.5),
radius=0.5,
color='k', linewidth=10, fill=False))
fig1.tight_layout()
fig1.savefig(path, bbox_inches='tight', pad_inches=0)
and this is what I get:
As you can see, part of the border is out of the picture.
In fact, even doing something much simpler, I get similar results:
import matplotlib.pyplot as plt
from matplotlib import patches
fig1 = plt.figure()
ax1 = fig1.add_subplot(111, aspect='equal')
ax1.add_patch(patches.Circle((0.5, 0.5),
radius=0.5,
color='k', linewidth=10, fill=False))
plt.show()
so, I can't understand where is the problem.
What am I doing wrong?
Upvotes: 4
Views: 8204
Reputation: 12590
Adding a patch won't automatically adjust the axes limits. You have to call ax1.autoscale_view()
to adjust the limits to the content.
fig1 = plt.figure()
ax1 = fig1.add_subplot(111, aspect='equal')
ax1.add_patch(patches.Circle((0.5, 0.5),
radius=0.5,
color='k', linewidth=10, fill=False))
ax1.autoscale_view()
Upvotes: 4
Reputation: 243945
The limits are small, by default take the minimum position and maximum of all points without considering the thickness, I recommend that you set the limits a little bigger. You must be {axes}.set_xlim()
and {axes}.set_ylim()
import matplotlib.pyplot as plt
from matplotlib import patches
path = 'test.png'
fig1 = plt.figure()
fig1.dpi = 100
fig1.set_size_inches(2, 2)
ax1 = fig1.add_subplot(111, aspect='equal')
ax1.axes.get_xaxis().set_visible(False)
ax1.axes.get_yaxis().set_visible(False)
ax1.add_patch(patches.Circle((0.5, 0.5),
radius=0.5,
color='k', linewidth=10, fill=False))
ax1.set_xlim([-0.1, 1.1])
ax1.set_ylim([-0.1, 1.1])
fig1.tight_layout()
fig1.savefig(path, bbox_inches='tight', pad_inches=0)
Upvotes: 1