'Undesired space between Rectangle patches in matplotlib

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');

All is OK in the python plot: enter image description here

But there is white space in the pdf:enter image description here



Solution 1:[1]

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

Solution 2:[2]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 rvd