简体   繁体   English

matplotlib 具有极值的轮廓

[英]matplotlib contourf with extreme values

I have data I want to plot with extreme edge values, given below is a generic example:我有我想要的数据 plot 具有极端边缘值,下面给出的是一个通用示例:

import matplotlib.pyplot as plt
plt.style.use('seaborn-white')
import numpy as np

Z = np.random.rand(100,100)

plt.contourf(Z, 100, cmap='RdGy', vmin=0, vmax=1)
plt.colorbar()
plt.show()

Using the above code I get this plot:使用上面的代码,我得到了这个 plot:
在此处输入图像描述

But if I change only one row of Z to contain extreme values it "dominates" the whole plot:但是,如果我只更改 Z 的一行以包含极值,它会“支配”整个 plot:

import matplotlib.pyplot as plt
plt.style.use('seaborn-white')
import numpy as np

Z = np.random.rand(100,100)
Z[:1] *= 100

plt.contourf(Z, 100, cmap='RdGy', vmin=0, vmax=1)
plt.colorbar()
plt.show()

在此处输入图像描述

My question is so: In the second example, although I have extreme values, all the interesting things obviously happen in the range of 0 and 1, which is totally dominated by the multiplication I entered in the 1st row, even though I set vmin and vmax accordingly.我的问题是这样的:在第二个例子中,虽然我有极值,但所有有趣的事情显然都发生在 0 和 1 的范围内,这完全由我在第一行输入的乘法支配,即使我设置了 vmin 和vmax 相应地。 How do I keep the data as is, while "focusing" on the 0-1 range?如何在“关注”0-1 范围的同时保持数据原样? I don't really care what goes on in the first row, for all I care there can be a single color for the values 1-100.我真的不在乎第一行发生了什么,因为我只关心值 1-100 可以有一种颜色。

Many Thanks.非常感谢。

This seems to be a known behavior, as reported in this GH issue .这似乎是一种已知行为,如本期GH 问题中所述。

A workaround (given in the issue comments) is to use an iterable for the levels arguments instead of relying on vmin and vmax .一种解决方法(在问题评论中给出)是使用可迭代的levels arguments 而不是依赖vminvmax

Here is a code snippet to exhibit how vmin and vmax can be used with pcolormesh (as you said in the comment) but how to achieve a similar result with contourf .这是一个代码片段,展示了如何将vminvmaxpcolormesh一起使用(正如您在评论中所说),但如何使用contourf获得类似的结果。

import matplotlib.pyplot as plt
plt.style.use('seaborn-white')
import numpy as np


def main():
    fig, axs = plt.subplots(2)
    Z = np.random.rand(100,100)
    Z[:1] *= 100

    cmap = plt.get_cmap("viridis")

    p1 = axs[0].pcolormesh(Z, vmin=0., vmax=1, cmap=cmap)
    fig.colorbar(p1, ax=axs[0])
    p2 = axs[1].contourf(Z, levels=np.linspace(0, 1, 100), cmap=cmap)
    fig.colorbar(p2, ax=axs[1], ticks=np.linspace(0, 1, 5))
    plt.show()

if __name__ == '__main__':
    main()

pcolormesh 与 contourf

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM