繁体   English   中英

如何在 Python 中将等高线标签作为图例放置?

[英]How to put contour labels as legend in a plot in Python?

我正在绘制轮廓,使用此链接中的示例(下面的代码和输出图) https://www.geeksforgeeks.org/matplotlib-pyplot-contour-in-python/

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import matplotlib
   
delta = 0.15
x = np.arange(1.5, 2.5, delta)
y = np.arange(1.0, 3.0, delta)
X, Y = np.meshgrid(x, y)
Z = (np.exp(X - Y))
  
  
CS1 = plt.contour(X, Y, Z)
   
fmt = {}
strs = ['1', '2', '3', '4', '5', '6', '7']
for l, s in zip(CS1.levels, strs):
    fmt[l] = s
plt.clabel(CS1, CS1.levels, inline = True,
           fmt = fmt, fontsize = 10)
  
plt.title('matplotlib.pyplot.contour() Example')
plt.show()

输出是: 在此处输入图像描述

我希望每个轮廓的标签作为角落的图例,而不是沿着轮廓线。 有办法吗?

  1. 此处的这篇文章展示了几种为轮廓创建图例的方法。 具体来说,您可以使用
for i in range(len(cl)): 
  CS1.collections[i].set_label(cl[i].get_text())

为您的轮廓创建自定义图例。

  1. 要从图中的轮廓中删除标签,您可以使用此处发布的解决方案。 它包括使用label.remove()迭代地删除标签

下面是最终代码的样子:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import matplotlib
   
delta = 0.15
x = np.arange(1.5, 2.5, delta)
y = np.arange(1.0, 3.0, delta)
X, Y = np.meshgrid(x, y)
Z = (np.exp(X - Y))
  
  
CS1 = plt.contour(X, Y, Z)

fmt = {}

strs = ['1', '2', '3', '4', '5', '6', '7']
for l, s in zip(CS1.levels, strs):
    fmt[l] = s

cl=plt.clabel(CS1, CS1.levels,fmt=fmt, inline = False, fontsize = 10)

plt.title('matplotlib.pyplot.contour() Example')
for i in range(len(cl)): 
  CS1.collections[i].set_label(cl[i].get_text())


for label in cl:
  label.remove()

plt.legend()

输出给出:

在此处输入图像描述

尝试这个:

delta = 0.15
x = np.arange(1.5, 2.5, delta)
y = np.arange(1.0, 3.0, delta)
X, Y = np.meshgrid(x, y)
Z = (np.exp(X - Y))
  
CS1 = plt.contour(X, Y, Z)
   
nm, lbl = CS1.legend_elements()
lbl_ = [i for i in range(1, len(lbl))]
plt.legend(nm, lbl_) 

plt.title('matplotlib.pyplot.contour() Example')
plt.show()

在此处输入图像描述

暂无
暂无

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

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