简体   繁体   English

Matplotlib:在等高线图上将散点图绘制到前景

[英]Matplotlib: Scatter Plot to Foreground on top of a Contour Plot

Does anyone know a way to bring a scatter plot to the foreground in matplotlib?有谁知道在 matplotlib 中将散点图带到前台的方法吗? I have to display the scatter plotting on top of the contour, but by default it is plotted underneath...我必须在轮廓顶部显示散点图,但默认情况下它绘制在下面......

Thanks in advance!提前致谢!

You can manually choose in which order the different plots are to be displayed with the zorder parameter of eg the scatter method.您可以使用scatter方法的zorder参数手动选择不同图的显示顺序。

To demonstrate, see the code below, where the scatter plot in the left subplot has zorder=1 and in the right subplot it has zorder=-1 .为了演示,请参阅下面的代码,其中左侧子图中的散点图具有zorder=1 ,右侧子图中的zorder=-1具有zorder=-1 The object with the highest zorder is placed on top.具有最高zorder的对象放置在顶部。 This means that the scatter will be placed on top of the contour in the first subplot, while it is placed underneath in the second subplot.这意味着散点将被放置在第一个子图中的等高线顶部,而它被放置在第二个子图中的下方。

import numpy as np
import matplotlib.cm as cm
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt

delta = 0.025
x = np.arange(-3.0, 3.0, delta)
y = np.arange(-2.0, 2.0, delta)
X, Y = np.meshgrid(x, y)
Z1 = mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0)
Z2 = mlab.bivariate_normal(X, Y, 1.5, 0.5, 1, 1)
Z = 10.0 * (Z2 - Z1)

norm = cm.colors.Normalize(vmax=abs(Z).max(), vmin=-abs(Z).max())
cmap = cm.PRGn

levels = np.arange(-2.0, 1.601, 0.4)

fig, axes = plt.subplots(1,2, sharey=True)

for ax, zord in zip(axes, [1, -1]):
    ax.contourf(X, Y, Z, levels,
                cmap=cm.get_cmap(cmap, len(levels)-1),
                norm=norm)
    ax.autoscale(False) # To avoid that the scatter changes limits
    ax.scatter(np.random.uniform(-3,3,10),
               np.random.uniform(-2,2,10),
               zorder=zord)
    ax.set_title('Scatter with zorder={0}'.format(zord))

在此处输入图片说明

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

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