簡體   English   中英

如何在python`matplotlib`中添加線條到等高線圖?

[英]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')

在此輸入圖像描述

...但是我不能讓線條顯示在我需要它們的情節上。 我只是需要將它們疊加在等高線圖的頂部。 做這個的最好方式是什么?

我知道在R中可能的 ,但是如何使用matplotlibPython執行此操作?

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM