[英]How to add lines to contour plot in python `matplotlib`?
我有以下功能来说明一些轮廓线:
"""
Illustrate simple contour plotting, contours on an image with
a colorbar for the contours, and labelled contours.
See also contour_image.py.
"""
import matplotlib
import numpy as np
import matplotlib.cm as cm
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
matplotlib.rcParams['xtick.direction'] = 'out'
matplotlib.rcParams['ytick.direction'] = 'out'
X = np.arange(-1.2, 1.2, 0.005)
Y = np.arange(-1.2, 1.2, 0.005)
X, Y = np.meshgrid(X, Y)
Z = (np.ones([np.shape(X)[0],np.shape(X)[1]])-X)**2+100*(Y-(X)**2)**2
# Create a simple contour plot with labels using default colors. The
# inline argument to clabel will control whether the labels are draw
# over the line segments of the contour, removing the lines beneath
# the label
levels = np.arange(-100.0, 600, 1.0)
plt.figure()
CS = plt.contour(X,
Y,
Z,
levels=levels,
)
plt.clabel(CS,
np.array(filter(lambda lev: lev <5.0, levels)),
inline=0.5,
fontsize=10,
fmt='%1.1f'
)
plt.hold(True)
plt.plot(np.arange(-1.0, 1.0, 0.005),
np.arange(-1.0, 1.0, 0.005),
np.ones(len(np.arange(-1.0, 1.0, 0.005)))*100, '-k')
plt.title('Contour Lines and Constraint of Rosenbrock Optimiztion Problem')
plt.show()
如果你注释掉线条,等高线图看起来很棒....:
# plt.hold(True)
# plt.plot(np.arange(-1.0, 1.0, 0.005),
# np.arange(-1.0, 1.0, 0.005),
# np.ones(len(np.arange(-1.0, 1.0, 0.005)))*100, '-k')
...但是我不能让线条显示在我需要它们的情节上。 我只是需要将它们叠加在等高线图的顶部。 做这个的最好方式是什么?
plt.plot
从x和y坐标序列中绘制一条二维线。 没有与每个点关联的z坐标,因此不需要传入第三个数组参数。 目前, plt.plot
将这些数组解释为两条独立行的坐标,并且相当于:
plt.plot(np.arange(-1.0, 1.0, 0.005), np.arange(-1.0, 1.0, 0.005))
plt.plot(np.ones(len(np.arange(-1.0, 1.0, 0.005)))*100, '-k')
由于第二行包含最多100的x和y坐标,因此轴将自动重新调整,以使轮廓图不再清晰。
我想你可能会想到zorder=
参数(它应该只是一个标量而不是一个数组)。 在这种情况下没有必要 - 因为您在轮廓之后绘制线条,默认情况下它应该比轮廓线具有更高的zorder
。 你可以摆脱plt.plot
的第三个数组参数
此外,由于您只绘制了两个点的直线,因此您只需要传递起点和终点坐标:
plt.plot([-1, 1], [-1, 1], '-k')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.