python - 更改图例中椭圆手柄的形状
问题描述
我正在尝试在单个图例中绘制一些轮廓和椭圆的标签。我快到了(下面的代码),但我希望与图例中的椭圆关联的形状是直线,而不是默认的矩形。
我怎样才能改变这个?
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()
解决方案
以下是基于此答案的解决方案。这里的主要思想是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'])
推荐阅读
- javascript - 为什么我在 Vue.js 上收到 npm 缺少服务器错误?
- php - 如何修复我的代码以使其正常工作?
- jboss - 如何在 Kie Piesistence 中实现 jboss 事务?
- android - 移动应用中的图片广告规范
- ios - ios - firebase 云混乱的混搭
- javascript - 有没有更好的方法来对对象数组进行排序以动态生成按值分隔的 HTML 元素?
- .net-core - 来自 .NET core 2.1 的 DB2 连接
- saml-2.0 - 尝试使用 OneLogin 实现多个 ACS 支持
- angular - 每次渲染组件时加载新数据或使用存储数据
- css - 是否可以按条件用css对div进行排序