Matplotlib-Contourf-如何使刻度线间距不均匀?

时间:2019-11-18 22:43:59

标签: python matplotlib

我想用(纬度,深度,温度)绘制轮廓线f,然后具有与下图相似的间距(温度在地表附近变化更大,然后在深度处变化,所以我想强调该区域)。

我的深度数组不均匀(即,深度= [5,15,...,4975,5185,...]。我想具有这样的不均匀垂直间距。

我想显示yticks = [10,100,500,1000,1500,2000,3000,4000,5000],并且深度数组没有这些确切值。

function getZodiac(day, month){

    // store the start/end ranges for the zodiacs
    let zodiacs = {
        'crab':{
            'start':[1,1],
            'end':[25,7]
        },
        'dog':{
            'start':[25,7],
            'end':[31,12]
        }
    }

    // loop through each property of 'zodiacs' in this case the property name is the zodiac_name
    for(let zodiac_name in zodiacs){

        // the object contains two properties 'start' and 'end'. Each of which is an array of two numbers. The first is the day, the second is the month.
        // so start[0] indicates this is the starting day, and end[1] indcates the ending day
        if(
            (month >= zodiacs[ zodiac_name ].start[1] && month < zodiacs[ zodiac_name ].end[1]) && // is the passed-in month in between the start and end for this?
            (day >= zodiacs[ zodiac_name ].start[0] && day < zodiacs[ zodiac_name ].end[0]) // is the passed-in day in between the start and end for this?
        ){
            console.log(`You're a ${zodiac_name}!`); // print out the name of this property!
        }
    }
}

getZodiac(1, 1); // you're a crab!
getZodiac(27, 7); // you're a dog!

大西洋的潜在温度: Potential Temperature of the Atlantic Ocean

1 个答案:

答案 0 :(得分:0)

根据yticks上的matplotlib文档,您可以指定要使用的标签。在您的情况下,如果要显示标签[10,100,500,1000,1500,2000,3000,4000,5000],只需将列表作为plt.yticks()中的第二个参数传递,就像这样

plt.yticks(z[pos], [10,100,500,1000,1500,2000,3000,4000,5000])

,它将相应显示yticks。问题出现在位置说明中-由于depth数组没有与所需ytick值完全对应的点,因此您需要进行插值才能找到放置位置的确切位置标签。除非在pos中指定的大概位置已经足够,否则在上述情况下就足够了。

如果depth数据的间距不均匀,则可以使用numpy.interp进行插值,如下所示

import matplotlib.pyplot as plt
import numpy as np

# Create some depth data that is not uniformly spaced over [0, 5500]
depth = [(np.random.random() - 0.5)*25 + ii for ii in np.linspace(0, 5500, 50)]

lat = np.linspace(-75, 75, 50)
z   = np.linspace(0,50, 50)
yticks = [10,100,500,1000,1500,2000,3000,4000,5000]

# Interpolate depths to get z-positions
pos = np.interp(yticks, depth, z)

temp = np.outer(lat, z)        # Arbitrarily populate temp for demonstration
ax  = plt.contourf(lat,z,temp)
plt.colorbar()

plt.gca().yaxis.set_ticks(pos)
plt.yticks(pos,yticks)         # Place yticks at interpolated z-positions

plt.gca().invert_yaxis()
plt.grid(linestyle=':')
plt.gca().set(ylabel='Depth (m)',xlabel='Latitude')
plt.show()

如果yticks数组在这些位置上有数据,则会找到depth 会落在的 exact 位置,并将它们相应地放置为如下所示。

Output with interpolated ytick positions