Undesired space between Rectangle patches in matplotlib

时间:2017-12-18 06:03:19

标签: python 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

1 个答案:

答案 0 :(得分:2)

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