Reputation: 121
The following code draws two red rectangles. The red rectangles should be next to each other, with no space between. In the python plot, this is OK. In the exported pdf, there is a thin but noticeable white space between the rectangles. Is there some way of fixing this?
import matplotlib.pyplot as plt
import matplotlib
import matplotlib.patches as patches
fig1 = plt.figure();
ax = fig1.add_subplot(111, aspect='equal');
ax.set_xticks([]);
ax.set_yticks([]);
#add first patch
dx=1.0;
loc=(0.0,0.0);
ax.add_patch(patches.Rectangle((loc[0]-dx/2.0,loc[1]-dx/2.0),dx,dx,facecolor='red',edgecolor='none',linewidth=0));
#add second patch
dx=1.0;
loc=(1.0,0.0);
ax.add_patch(patches.Rectangle((loc[0]-dx/2.0,loc[1]-dx/2.0),dx,dx,facecolor='red',edgecolor='none',linewidth=0));
ax.set_xlim([-1,3]);
ax.set_ylim([-1,2]);
fig1.show();
plt.savefig('spaceTest.pdf');
But there is white space in the pdf:
Upvotes: 2
Views: 533
Reputation: 404
The problem here is the edgecolor="none"
.
Force the edgecolor
and the facecolor
to be the same, and don't set linewidth=0
.
This should produce a line-free PDF:
import matplotlib.pyplot as plt
import matplotlib
import matplotlib.patches as patches
fig1 = plt.figure();
ax = fig1.add_subplot(111, aspect='equal');
ax.set_xticks([]);
ax.set_yticks([]);
#add first patch
dx=1.0;
loc=(0.0,0.0);
ax.add_patch(patches.Rectangle((loc[0]-dx/2.0,loc[1]-dx/2.0),float(dx),float(dx),facecolor='red',edgecolor='red')); # <---
#add second patch
dx=1.0;
loc=(1.0,0.0);
ax.add_patch(patches.Rectangle((loc[0]-dx/2.0,loc[1]-dx/2.0),float(dx),float(dx),facecolor='red',edgecolor='red')); # <---
ax.set_xlim([-1,3]);
ax.set_ylim([-1,2]);
fig1.show();
plt.savefig('spaceTest.pdf');
See this answer for a solution with a PatchCollection.
Upvotes: 0
Reputation: 17721
The thin line comes from inexact arithmetic. You calculate the points of the rectangle with integer arithmetic, but you should force float arithmetic.
For instance: Instead of
ax.add_patch(patches.Rectangle((float(loc[0]-dx/2),float(loc[1]-dx/2)),float(dx),float(dx),facecolor='red',edgecolor='none',linewidth=0));
use
ax.add_patch(patches.Rectangle((loc[0]-dx/2.0,loc[1]-dx/2.0),float(dx),float(dx),facecolor='red',edgecolor='none',linewidth=0));
Using 2.0
instead of 2
gives 0.5
instead of 0
as division result.
If this doesn't help, you should also turn Antialiasing off:
ax.add_patch(patches.Rectangle((loc[0]-dx/2.0,loc[1]-dx/2.0),float(dx),float(dx),facecolor='red',edgecolor='none',linewidth=0, antialiased = False));
Upvotes: 2