在图例中更改椭圆形手柄的形状

时间:2018-10-27 19:14:02

标签: python matplotlib legend

我试图在单个图例中绘制一些轮廓和椭圆的标签。我快到了(下面的代码),但是我希望与图例中的椭圆相关的形状是直线,而不是默认的矩形。

我该如何更改?


import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse

# Random data
ndim, nsamples = 2, 1000
samples = np.random.randn(ndim * nsamples).reshape([nsamples, ndim])

fig, ax = plt.subplots()
x, y = samples.T
H, X, Y = plt.hist2d(x, y, bins=20, cmap=plt.get_cmap('Greys'))[:-1]

# Plot two contours
contour = ax.contour(
    H.T, levels=(5, 10), extent=[x.min(), x.max(), y.min(), y.max()])

# Plot ellipse
ellipse = Ellipse(xy=(0., 0.), width=3., height=2, angle=45, edgecolor='r', fc='None', label='ellipse')
ax.add_patch(ellipse)

# Get ellipse's handle and label
ellip, ellip_lbl = ax.get_legend_handles_labels()

# Plot legend
plt.legend(ellip + list(reversed(contour.collections)), ellip_lbl + ['1s', '2s'])

plt.show()

enter image description here

1 个答案:

答案 0 :(得分:1)

以下是基于this答案的解决方案。这里的主要思想是通过绘制一个空列表并抓住其句柄来使用ls="-",。将椭圆的补丁存储在ax1中,并使用它来获取标签。

ellipse = Ellipse(xy=(0., 0.), width=3., height=2, angle=45, edgecolor='r', fc='None', label='ellipse')
ax1 = ax.add_patch(ellipse)

# Get ellipse's handle and label
ellip, ellip_lbl = ax.get_legend_handles_labels()

plt.legend(handles = [plt.plot([],ls="-", color='r')[0]] + list(reversed(contour.collections)),
           labels=[ax1.get_label()] + ['1s', '2s'])

enter image description here