Artefacts in contour plot?

I notice some spurious zigzagging lines towards the top

    > of the plot. Any idea where those might be coming from?

I don't get zigzag lines either. Try using replacing
matplotlib.axes.Axes.contour with the function included below (from
CVS) and let me know if it works.

    > Also, the figure produced by the above script is
    > flipped horizontally. The corresponding Matlab script
    > produces the correct plot.

matplotlib supports two image / contour orientation styles, and this
is controlled by an rc parameter. Try (note the origin kwarg)

from matplotlib.pylab import *

def rosenbrock(x,y):
     return 10.0 * (y-x**2)**2 + (x-1)**2

x = arange( -1.5, 1.5, 0.01 )
y = arange( -0.5, 1.5, 0.01 )
[X,Y] = meshgrid( x, y )
Z = rosenbrock( X, Y )
contour( Z, x=X, y=Y, levels = 50, origin='lower' )
show()

Amended contour function

    def contour(self, z,
                x = None,
                y = None,
                levels = None,
                colors = None,
                linewidths = None,
                alpha = 1.0,
                fmt='%1.3f',
                origin=None):
        """\
CONTOUR(z, x = None, y = None, levels = None, colors = None)

plots contour lines of an image z

z is a 2D array of image values
x and y are 2D arrays with coordinates of z values in the
two directions. x and y do not need to be evenly spaced but must
be of the same shape as z

levels can be a list of level values or the number of levels to be
  plotted. If levels == None, a default number of 7 evenly spaced
  levels is plotted.

colors is one of these:

  - a tuple of matplotlib color args (string, float, rgb, etc),
    different levels will be plotted in different colors in the order
    specified

  - one string color, e.g. colors = 'r' or colors = 'red', all levels
    will be plotted in this color

  - if colors == None, the default color for lines.color in
    .matplotlibrc is used.

linewidths is one of:

   - a number - all levels will be plotted with this linewidth,
     e.g. linewidths = 0.6

   - a tuple of numbers, e.g. linewidths = (0.4, 0.8, 1.2) different
     levels will be plotted with different linewidths in the order
     specified

   - if linewidths == None, the default width in lines.linewidth in
     .matplotlibrc is used

reg is a 2D region number array with the same dimensions as x and
  y. The values of reg should be positive region numbers, and zero fro
  zones wich do not exist.

triangle - triangulation array - must be the same shape as reg

alpha : the default transparency of contour lines

fmt is a format string for adding a label to each collection.
  Currently this is useful for auto-legending and may be useful down
  the road for legend labeling

origin = 'upper'|'lower'|None. If None, the rc value for image.origin
will be used

More information on reg and triangle arrays is in _contour.c

Return value is levels, collections where levels is a list of contour
levels used and collections is a list of
matplotlib.collections.LineCollection instances
"""

        if origin is None: origin = rcParams['image.origin']
        
        if origin == 'upper':
            if x is not None: x = x[::-1]
            if y is not None: y = y[::-1]
            z = z[::-1]

        if not self._hold: self.cla()
        if which[0] == "numeric":
            z = array(z.tolist(),typecode = z.typecode())
        if len(shape(z)) != 2:
            raise TypeError("Input must be a 2D array.")
        else:
            jmax, imax = shape(z)

        region = 0
        reg = ones((jmax,imax), Int32)
        reg[:,0]=0
        triangle = zeros((jmax,imax), Int32)

        if x == None and y == None:
            y, x = indices((jmax,imax), 'd')

        rz = ravel(z)
        zmax = nxmax(rz)
        zmin = nxmin(rz)

        def autolev(N):
            return mlab.linspace(zmin, zmax, N+2)[1:-1]
        
        if levels is None: lev = autolev(7)
        else:
            try: Nlev = int(levels)
            except TypeError:
                lev = list(levels)
            else: lev = autolev(Nlev)

        Nlev = len(lev)
        if colors == None:
            colors = rcParams['lines.color']

        if is_string_like(colors):
            colors = [colors] * Nlev
        elif iterable(colors) and len(colors) < Nlev:
            colors = list(colors) * Nlev
        else:
            try: gray = float(colors)
            except TypeError: pass
            else: colors = [gray] * Nlev

        tcolors =
        for c in colors:
            tcolors.append((colorConverter.to_rgba(c, alpha),))

        if linewidths == None:
            tlinewidths = [linewidths] *Nlev
        else:
            if iterable(linewidths) and len(linewidths) < Nlev:
                linewidths = list(linewidths) * int(ceil(Nlev/len(linewidths)))
            elif not iterable(linewidths) and type(linewidths) in [int, float]:
                linewidths = [linewidths] * Nlev
            tlinewidths = [(w,) for w in linewidths]

        args = zip(lev, tcolors, tlinewidths)

        levels =
        collections =

        for level, color, width in args:
            ntotal, nparts = _contour.GcInit1(x, y, reg, triangle, region, z, level)
            np = zeros((nparts,), Int32)
            xp = zeros((ntotal, ), Float64)
            yp = zeros((ntotal,), Float64)
            nlist = _contour.GcTrace(np, xp, yp)
            col = LineCollection(nlist, colors=color, linewidths = width)
            col.set_label(fmt%level)
            self.add_collection(col)
            levels.append(level)
            #col.set_linestyle('dashdot') # dashed|dotted|solid|dashdot
            #dashes = 0, (4,2,8,1)
            #col.set_linestyle( (dashes,) ) # offset, onoffseq
            collections.append(col)

        if x is not None:
            rx = ravel(x)
            self.set_xlim((min(rx), max(rx)))
        else:
            self.set_xlim([0,imax])

        if y is not None:
            ry = ravel(y)
            self.set_ylim((min(ry), max(ry)))
        else:
            self.set_ylim([0,jmax])

        return levels, collections

John Hunter wrote:

"Dominique" == Dominique Orban <Dominique.Orban@...92...> writes:

    > I notice some spurious zigzagging lines towards the top
    > of the plot. Any idea where those might be coming from?

I don't get zigzag lines either. Try using replacing
matplotlib.axes.Axes.contour with the function included below (from
CVS) and let me know if it works.

    > Also, the figure produced by the above script is
    > flipped horizontally. The corresponding Matlab script
    > produces the correct plot.

matplotlib supports two image / contour orientation styles, and this
is controlled by an rc parameter. Try (note the origin kwarg)

from matplotlib.pylab import *

def rosenbrock(x,y):
     return 10.0 * (y-x**2)**2 + (x-1)**2

x = arange( -1.5, 1.5, 0.01 )
y = arange( -0.5, 1.5, 0.01 )
[X,Y] = meshgrid( x, y )
Z = rosenbrock( X, Y )
contour( Z, x=X, y=Y, levels = 50, origin='lower' )
show()

Amended contour function

> [snip]

John,

Many thanks for the update. That solves some of the issues. The 'origin' keyword argument restores the orientation of the plot. To account for the 'x' and 'y' keyword arguments, I would suggest changing the lines

  if x == None and y == None:
             y, x = indices((jmax,imax), 'd')

to

  if x is None:
             x = indices((jmax,imax), 'd')
         if y is None:
             y = indices((jmax,imax), 'd')

to account for the situation where only one of x or y is specified (I admit that might be unlikely but hey).

Regarding the zigzags, I notice they appear for relatively small values of the increment in arange() (the 3rd argument). When I decrease it to, say, 0.1, zigzags start to appear. For higher values, they don't. It makes me think they might be part of the line collections. Is anyone else able to reproduce this behavior?

Thanks much.
Dominique

I have made several experiments; I have installed the latest matplotlib (with the 'contour' update) in both Win XP and SuSE Linux Pro 9.1. I made sure to uninstall everything pertaining to matplotlib before installing the latest version. In Windows, I use the pre-built distribution, and in Linux I compile it myself. The situation is this:

- In Linux, some zigzagging lines appear when there are few points to interpolate. Eg, if i generate my grid from
  x = y = arange( -1, 1, delta ),
zigzags would appear for small values of delta. However, it seems that those zigzags are a normal consequence of a small value of delta. For larger deltas, the contours are beautiful.

- In XP, the same as above happens. But I see additional lines that don't seem to represent anything meaningful. I made sure I was performing a clean install. Are there updates to other packages I should consider? Pygtk? This happened with both the TkAgg and GTKAgg backends. Perhaps I should try compiling matplotlib myself?

If anyone is able to reproduce the problem, then it might indeed be a problem. If not, perhaps something is funny with my box.

Thanks,
Dominique

(Sorry, sending this again to correct a typo -- i inverted small and large below)

I have made several experiments; I have installed the latest matplotlib
(with the 'contour' update) in both Win XP and SuSE Linux Pro 9.1. I
made sure to uninstall everything pertaining to matplotlib before
installing the latest version. In Windows, I use the pre-built
distribution, and in Linux I compile it myself. The situation is this:

- In Linux, some zigzagging lines appear when there are few points to
interpolate. Eg, if i generate my grid from
  x = y = arange( -1, 1, delta ),
zigzags would appear for LARGE values of delta (eg, delta = 0.2; ie too few values of x and/or y). However, it seems that those zigzags are a normal consequence of a large value of delta. For SMALLER deltas, the contours are beautiful.

- In XP, the same as above happens. But I see additional lines that
don't seem to represent anything meaningful. I made sure I was
performing a clean install. Are there updates to other packages I should
consider? Pygtk? This happened with both the TkAgg and GTKAgg backends.
Perhaps I should try compiling matplotlib myself?

If anyone is able to reproduce the problem, then it might indeed be a
problem. If not, perhaps something is funny with my box.

Thanks,
Dominique

I've been able to reproduce the problem on MacOSX (after the correction), although I don't have
an answer to what's causing it now.

Nadia Dencheva

···

On Jan 18, 2005, at 2:38 PM, Dominique Orban wrote:

(Sorry, sending this again to correct a typo -- i inverted small and large below)

I have made several experiments; I have installed the latest matplotlib
(with the 'contour' update) in both Win XP and SuSE Linux Pro 9.1. I
made sure to uninstall everything pertaining to matplotlib before
installing the latest version. In Windows, I use the pre-built
distribution, and in Linux I compile it myself. The situation is this:

- In Linux, some zigzagging lines appear when there are few points to
interpolate. Eg, if i generate my grid from
  x = y = arange( -1, 1, delta ),
zigzags would appear for LARGE values of delta (eg, delta = 0.2; ie too few values of x and/or y). However, it seems that those zigzags are a normal consequence of a large value of delta. For SMALLER deltas, the contours are beautiful.

- In XP, the same as above happens. But I see additional lines that
don't seem to represent anything meaningful. I made sure I was
performing a clean install. Are there updates to other packages I should
consider? Pygtk? This happened with both the TkAgg and GTKAgg backends.
Perhaps I should try compiling matplotlib myself?

If anyone is able to reproduce the problem, then it might indeed be a
problem. If not, perhaps something is funny with my box.

Thanks,
Dominique

-------------------------------------------------------
The SF.Net email is sponsored by: Beat the post-holiday blues
Get a FREE limited edition SourceForge.net t-shirt from ThinkGeek.
It's fun and FREE -- well, almost....http://www.thinkgeek.com/sfshirt
_______________________________________________
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
matplotlib-users List Signup and Options

Nadia Dencheva wrote:

I've been able to reproduce the problem on MacOSX (after the correction), although I don't have an answer to what's causing it now.

Results seem inconsistent; if i replace the 'rosenbrock' function in my previous script with

   def saddle(x,y): return y**2 - x**2

and use

   x = y = arange( -2, 2, 0.1 )

then

   contour( Z, x = X, y = Y, levels = 30, origin = 'lower' )

produces the zigzags, but

   contour( Z, x = X, y = Y, levels = 30, origin = 'upper' )

doesn't. The same isn't true of the rosenbrock function. I wonder if the zigzags might be coming from the C function which computes the levels. Is there a C interface to that function somewhere that we could try?

Dominique