Repository navigation
Description
Adjacent patch objects which share an edge show a visible seam at the coincident edge for edgecolor=None. I've verified via reading the raw text in the pdf file that the points are precisely coincident and only polygons exist and there are no lines outlining the patches. The problem continues for rasterization via output to png.
To demonstrate this problem @akturner, @xylar, and myself have devised a test case script:
#!/usr/bin/python
import matplotlib as mpl
#mpl.use("tkagg")
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from matplotlib.transforms import Affine2D
import mpl_toolkits.axisartist.floating_axes as floating_axes
# define patches
def p1():
return patches.Rectangle(
(0.1, 0.1), # (x,y)
0.4, # width
0.8, # height
linewidth=0,
edgecolor='none'
)
def p2():
return patches.Rectangle(
(0.5, 0.1), # (x,y)
0.4, # width
0.8, # height
linewidth=0,
edgecolor='none'
)
# setup plots
fig1 = plt.figure()
# rectilinear patches in subplot 1
ax1 = fig1.add_subplot(121, aspect='equal')
ax1.add_patch(p1())
ax1.add_patch(p2())
plt.ylim([0,1])
plt.xlim([0,1])
# make rotated version of the above in subplot 2
tr = Affine2D().scale(0.5, 0.5).translate(0.6,0).rotate_deg(30)
grid_helper = floating_axes.GridHelperCurveLinear(tr, extremes=(0, 1, 0, 1))
ax2 = floating_axes.FloatingSubplot(fig1, 122, grid_helper=grid_helper)
fig1.add_subplot(ax2)
aux_ax = ax2.get_aux_axes(tr)
aux_ax.add_patch(p1())
aux_ax.add_patch(p2())
plt.ylim([0,1])
plt.xlim([0,1])
# save figures
plt.savefig('test.pdf')
plt.savefig('test.png')
plt.show()The output for pdf shows two seams:
The output for png only shows a seam for the rotated rectangular patches which is why this typically does not show up for colorbars output to png:
Output to screen also has both seams:

I can understand why the problem exists for pdf, e.g., http://www.mathworks.com/matlabcentral/answers/15388-artifacts-in-figures-exported-as-pdf-from-matlab. It is obviously not desirable that this happens, however, and a solution would be greatly appreciated.
Regardless, the rasterization process in the conversion to png should remove this problem.
The issue appears to be a graphical aliasing issue because the seam disappears in pdf when smoothing is turned off. However, this is not the default for most pdf viewers.
We have noticed that this problem can be slightly alleviated by two approaches
- edgecolor='face', linewidth=1 However, this distorts the shape of the polygons because colors can be mangled and make the cells appear to be different sizes, e.g., hexes are no longer hexagonal.
- Scale each polygon to be slightly bigger. This solves the problem but it is inelegant and resolution dependent and not a true solution for a vector graphic because the seam will show up at some plotted scale.
Is there an alternative approach we are missing that fixes this issue? We suspect that this may be at least a soft bug warranting a warning message in matplotlib if not a solid bug.

Activity
tacaswell commentedon Dec 18, 2015
This is a long standing and (to my knowledge) unsolved problem inherent to the rasterization process.
One way to solve this is to always snap patches one pixel out when rendering (I think that is doable in Agg, but could be very wrong) which would cause the seem to be rendered to by both patches. However, if you have any alpha in your colors you get bright lines on the seams.
attn @mdboom
WeatherGod commentedon Dec 18, 2015
It is a bit more subtle than that, I think. It has to do with how to round
a floating point pixel coordinate to an integer pixel coordinate. If you
have them round to the same pixel, then you get an "overlap", which is
noticeable when alpha blending is used. Ideally, you want the polygons to
abut each other. Sometimes, the rasterizer gets this right, but sometimes
the rounding is such that it gets it wrong. This is why the unrotated
figure looked ok to PNG, but not ok on the screen. Those two output
"formats" have different resolutions, so the pixel rounding was slightly
different.
As for the rotated situation, you get antialiasing coming into play, which
is going to mix in the white background, which will almost always cause a
visible seam.
Excellent test cases, by the way!
On Fri, Dec 18, 2015 at 10:17 AM, Thomas A Caswell <[email protected]
pwolfram commentedon Dec 18, 2015
Thanks @tacaswell and @WeatherGod , this is very helpful. I'm suspicious that our typical use cases won't require alpha in patch colors, but @akturner, @xylar should comment if they disagree. I think solving the non-alpha case first is a much higher priority than solving the general case, unless there is a clever way to solve both cases in a single fix.
I understand this is an aliasing problem which from my limited experience with computer graphics / spectral methods is a challenging problem in general. Is the consensus that this is something that can be readily fixed (e.g., not requiring substantial modifications to a renderer or addition of a new renderer)? Secondly, does anyone with the expertise have interest in solving this problem?
The bottom line for our use case is that we want a clean way to plot cellular data on unstructured meshes without using
Triangulationwhich has interpolation between nodes on the triangulation. Instead, we want to plot values in each cell, e.g., see below with seams due to the afforementioned issue (you may have to open the full image).pwolfram commentedon Dec 18, 2015
@ianthomas23, you may be interested in this thread too because it has to do with plotting unstructured data.
tacaswell commentedon Dec 18, 2015
Simply using the face color as the edge color solves the problem in your test code above:
One of the default changes coming in 2.0 is to default edge color of patches to the face color unless specified otherwise.
pwolfram commentedon Dec 18, 2015
@tacaswell, thank you and agreed on it solving the problem above.
We considered this approach initially. It works for certain cases but not in general. For instance, using the hex grid above as the example, you'll notice it distorts the plotted cell values, e.g.,
looks strange and is misleading even compared to the less-troubling aesthetic issues with
Presumably a zorder approach could work here, but it would not be a general solution that is resolution or patch collection independent.
tacaswell commentedon Dec 18, 2015
Turn the edge width way down?
The other option is to overlay the plot with a line collection of just the edges.
Can you post code that is closer to your actual use case?
mdboom commentedon Dec 18, 2015
I haven't really updated everyone on this, but I've come around to rejecting that approach for exactly the same reasons as @pwolfram.
@pelson years ago did some experimentation with doing "simultaneous rendering", where the renderer is actually aware of all the patches at once and can stitch the pieces together appropriately. It worked quite well, but IIRC it wasn't very general. Maybe I shouldn't have let the perfect be the enemy of the good there, because at least it would make things better for the cases where it does work.
I've also experimented with outputting at double the dpi desired and then scaling down. That has fairly good results, and should probably be made into a convenient option (though not default).
pwolfram commentedon Dec 18, 2015
@tacaswell, here is a prototype script as you requested (https://gist.github.com/2745eaccaf33f222fed6), the kernel of the code (minus geometry) is below:
It can be run with the following options
i=1; python hex_poly.py -o $i; open *_hex_$i*for i=1,2,3.Essentially it considers the different line options where
The line width solution can create problems which are worse when one wants a scale-invarient plot.
Another approach as @tacaswell alludes may be to automatically place an edge between the polygons that has an edgecolor that is the average of the adjacent polygons, but again this seems like a hack and not a true solution.
Responding to @mdboom:
@mdboom, I'm wondering how the downscaling approach you mention would work. Perhaps that is the best solution, although of course it would restrict the utility of the file to rasters.
@mdboom, this seems like the best approach although lack of generality would be suboptimal.
pelson commentedon Jan 3, 2016
Sadly I never got around to finishing it. Doing so would make a superb GSOC project, though I'm unlikely to be able to mentor it.
Relevant mailing list discussion for this issue: http://matplotlib.1069221.n5.nabble.com/quot-Flash-quot-rendering-in-the-Agg-backend-td40550.html
dabana commentedon Sep 12, 2018
I think supersampling would do the job for most users and should not be to hard to implement. It would be nice to have it implemented as an optional supersampling_fator argument so that "compromise between performance vs "good enough" rendering" (quoted from @mdboom) can be tailored by the user.
Below is our running example with supersampling_fator = 4.
I did it by changing line 87 in backend_agg.py from:
to:
Of course there are side effects introduced by this rather crude implementation like
Any idea how to fix this?
jklymak commentedon Sep 12, 2018
Just for cross reference, this is a more pervasive problem than just hex. See https://github.com/jklymak/contourfIssues
The fundamental issue is that you are anti-aliasing the edge of each patch. Doing higher-res helps a lot because the anti-aliasing pixels become harder to see (though they are still clearly visible in your picture above, particularly for the dark patches).
dabana commentedon Sep 12, 2018
They seem to disappear above a certain threshold. Here is an image with supersampling_fator = 8.
WeatherGod commentedon Sep 12, 2018
jklymak commentedon Sep 12, 2018
ping @anntzer. I'm not sure if mplcairo "fixes" this.
@dabana sure you can oversample until the problem becomes less and less perceptible, depending on the DPI you want to view at. I don't think this is a very elegant solution.
I think the correct solution, at least for a single "object" like a QuadContourSet, is to rasterize the whole thing at once, rather than patch-by-patch, and then the anti-aliasing will be correct.
dabana commentedon Sep 12, 2018
@jklymak, the solution you are referring to is called "compound rendering" and is the subject of this mailing list discussion referenced by @pelson.
As @mdboom phrased it perfectly in one of the last emails of the above discussion:
on compound rendering ...
and talking about supersampling ...
anntzer commentedon Sep 13, 2018
No, in this specific case mplcairo suffers from the same issue, because it only sees one polygon at a time: matplotlib sends them one after another as independent objects, so mplcairo has no way to know it should arrange for stitching them.
Repeating the point I made in #9574:
In #7841 I suggested for example to represent hexbins as a quadmesh where each hexagon is the union of two quadrilaterals (upper and lower).
Supersampling is a reasonable workaround (except for the problem related to elements that scale with the dpi), but you do get a quadratic hit in performance (number of rendered pixels)...
QuLogic commentedon Mar 4, 2023
Closing as a duplicate of #1188.