Skip to content

Adjacent patch objects show "seam" for show, pdf, or png output #5694

Closed

Description

@pwolfram

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:

test.pdf

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:

test

Output to screen also has both seams:
screenshot 2015-12-17 16 38 49

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

  1. 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.
  2. 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

  1. tacaswell commented on Dec 18, 2015

    @tacaswell
    Member

    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

  2. WeatherGod commented on Dec 18, 2015

    @WeatherGod
    Member

    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]

    wrote:

    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 https://github.com/mdboom

    —
    Reply to this email directly or view it on GitHub
    #5694 (comment)
    .

  3. pwolfram commented on Dec 18, 2015

    @pwolfram
    Author

    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 Triangulation which 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).

    advection_2

  4. pwolfram commented on Dec 18, 2015

    @pwolfram
    Author

    @ianthomas23, you may be interested in this thread too because it has to do with plotting unstructured data.

  5. tacaswell commented on Dec 18, 2015

    @tacaswell
    Member

    Simply using the face color as the edge color solves the problem in your test code above:

    # define patches 
    def p1():
    
        p = patches.Rectangle(
                (0.1, 0.1),   # (x,y)
                0.4,          # width
                0.8,          # height
                linewidth=1,
                )
        p.set_edgecolor(p.get_facecolor())
        return p
    
    def p2():
        p = patches.Rectangle(
                (0.5, 0.1),   # (x,y)
                0.4,          # width
                0.8,          # height
                linewidth=1,
                )
        p.set_edgecolor(p.get_facecolor())
        return p

    One of the default changes coming in 2.0 is to default edge color of patches to the face color unless specified otherwise.

  6. pwolfram commented on Dec 18, 2015

    @pwolfram
    Author

    @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.,

    screenshot 2015-12-18 10 53 21

    looks strange and is misleading even compared to the less-troubling aesthetic issues with

    screenshot 2015-12-18 10 54 09

    Presumably a zorder approach could work here, but it would not be a general solution that is resolution or patch collection independent.

  7. tacaswell commented on Dec 18, 2015

    @tacaswell
    Member

    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?

  8. mdboom commented on Dec 18, 2015

    @mdboom
    Member

    One of the default changes coming in 2.0 is to default edge color of patches to the face color unless specified otherwise.

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

  9. pwolfram commented on Dec 18, 2015

    @pwolfram
    Author

    @tacaswell, here is a prototype script as you requested (https://gist.github.com/2745eaccaf33f222fed6), the kernel of the code (minus geometry) is below:

    def gradient(xt,yt):
        return np.mean(np.sqrt(xt*xt + yt*yt))
    
    patches = []
    colors = []
    for ac,nv in zip(cells,nvertices):
        ac = np.asarray(ac[:nv], dtype='int')
        xp = x[ac]
        yp = y[ac]
        patches.append(Polygon(zip(xp,yp)))
        colors.append(gradient(xp,yp))
    
    colors = np.asarray(colors)
    colors /= colors.max()
    
    pc = PatchCollection(patches, cmap='viridis', alpha=1.0)
    pc.set_array(colors)
    
    # option 1 (demonstrates problem)
    option = int(sys.argv[1])
    if option == 1:
        pc.set_edgecolor('face')
        pc.set_lw(0)
    
    # option 2 (demonstrates problem with 'fix')
    if option == 2:
        pc.set_edgecolor('face')
        pc.set_lw(10.0)
    
    # option 3 (possible solution)
    if option == 3:
        pc.set_edgecolor('face')
        pc.set_lw(0.1)
    
    plt.figure()
    ax = plt.gca()
    ax.add_collection(pc)
    ax.set_aspect('equal')
    ax.autoscale_view()
    plt.colorbar(pc)
    
    plt.savefig('test_hex_'+str(option)+'.pdf')
    plt.savefig('test_hex_'+str(option)+'.png')
    plt.show()

    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

    1. problem with no edges
      test_hex_1
    2. problem when line widths are too wide
      test_hex_2
    3. problem where line width may be about right
      test_hex_3

    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:

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

    @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.

    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.

    @mdboom, this seems like the best approach although lack of generality would be suboptimal.

  10. pelson commented on Jan 3, 2016

    @pelson
    Member

    @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.

    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

  11. dabana commented on Sep 12, 2018

    @dabana
    Contributor

    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.

    test_hex_ss3

    I did it by changing line 87 in backend_agg.py from:

    self._renderer = _RendererAgg(int(width), int(height), dpi)
    

    to:

    self._renderer = _RendererAgg(int(width), int(height), dpi * supersampling_factor)
    

    Of course there are side effects introduced by this rather crude implementation like

    1. linewidths being wider.
    2. some tick labels disappearing

    Any idea how to fix this?

  12. jklymak commented on Sep 12, 2018

    @jklymak
    Member

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

  13. dabana commented on Sep 12, 2018

    @dabana
    Contributor

    They seem to disappear above a certain threshold. Here is an image with supersampling_fator = 8.

    test_hex_ss3

  14. WeatherGod commented on Sep 12, 2018

    @WeatherGod
    Member
  15. jklymak commented on Sep 12, 2018

    @jklymak
    Member

    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.

  16. dabana commented on Sep 12, 2018

    @dabana
    Contributor

    @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:

    I think we agree there is a tradeoff here.

    on compound rendering ...

    On the one hand, there is a mathematically perfect solution that requires some rather pervasive refactoring of the code and permanent care in how plots are constructed to ensure it's running optimally, and an exponentially growing performance curve as the complexity of the plot increases.

    and talking about supersampling ...

    On the other, is a suboptimal end result that requires minimal changes, and a well-defined and upper bound performance penalty.

  17. anntzer commented on Sep 13, 2018

    @anntzer
    Contributor

    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:

    AFAIK the only way to solve this is to emit your polygons as mesh objects, so that the renderer actually "knows" that the two edges are supposed to be the same (and even then you need a renderer that actually knows how to use that information). See also #7841.

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

  18. QuLogic commented on Mar 4, 2023

    @QuLogic
    Member

    Closing as a duplicate of #1188.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions