How to plot an image with non-linear y-axis with Matplotlib using imshow?

前端 未结 4 814
猫巷女王i
猫巷女王i 2020-12-09 19:58

How can I plot an 2D array as an image with Matplotlib having the y scale relative to the power of two of the y value?

For instance the first row of my array will ha

4条回答
  •  心在旅途
    2020-12-09 20:48

    Have you tried to transform the axis? For example:

    ax = subplot(111)
    ax.yaxis.set_ticks([0, 2, 4, 8])
    imshow(data)
    

    This means there must be gaps in the data for the non-existent coordinates, unless there is a way to provide a transform function instead of just lists (never tried).

    Edit:

    I admit it was just a lead, not a complete solution. Here is what I meant in more details.

    Let's assume you have your data in an array, a. You can use a transform like this one:

    class arr(object):
        @staticmethod
        def mylog2(x):
            lx = 0
            while x > 1:
                x >>= 1
                lx += 1
            return lx
        def __init__(self, array):
            self.array = array
        def __getitem__(self, index):
            return self.array[arr.mylog2(index+1)]
        def __len__(self):
            return 1 << len(self.array)
    

    Basically it will transform the first coordinate of an array or list with the mylog2 function (that you can transform as you wish - it's home-made as a simplification of log2). The advantage is, you can re-use that for another transform should you need it, and you can easily control it too.

    Then map your array to this one, which doesn't make a copy but a local reference in the instance:

    b = arr(a)
    

    Now you can display it, for example:

    ax = subplot(111)
    ax.yaxis.set_ticks([16, 8, 4, 2, 1, 0])
    axis([-0.5, 4.5, 31.5, 0.5])
    imshow(b, interpolation="nearest")
    

    Here is a sample (with an array containing random values):

    alt text http://img691.imageshack.us/img691/8883/clipboard01f.png

提交回复
热议问题