首页 > 解决方案 > 更改图例中椭圆手柄的形状

问题描述

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

我怎样才能改变这个?


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()

在此处输入图像描述

标签: pythonmatplotliblegend

解决方案


以下是基于答案的解决方案。这里的主要思想是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'])

在此处输入图像描述


推荐阅读