python - python中用户定义的图例

标签 python matplotlib legend-properties

我有这个图,其中曲线之间的一些区域被定义填充。有什么方法可以将它们包含在图例中吗?特别是那些填充区域重叠的地方,以及出现新的不同颜色的地方。

或者无论曲线数据如何,都可以定义任意图例? enter image description here

最佳答案

使用 fill_bettween 绘制数据将自动在图例中包含填充区域。

要包含两个数据集重叠的区域,您可以将两个数据集的图例句柄合并为一个图例句柄。

正如评论中所指出的,您还可以使用代理定义任意图例句柄。

最后,您可以准确定义要在图例中显示的句柄和标签,而不管图表中绘制的数据是什么。

请参阅下面说明上述要点的 MWE:

import matplotlib.pyplot as plt
import numpy as np

plt.close('all')

# Gererate some datas:
x = np.random.rand(50)
y = np.arange(len(x))

# Plot data:
fig, ax = plt.subplots(figsize=(11, 4))
fillA = ax.fill_between(y, x-0.25, 0.5, color='darkolivegreen', alpha=0.65, lw=0)
fillB = ax.fill_between(y, x, 0.5, color='indianred', alpha=0.75, lw=0)

linec, = ax.plot(y, np.zeros(len(y))+0.5, color='blue', lw=1.5)
linea, = ax.plot(y, x, color='orange', lw=1.5)
lineb, = ax.plot(y, x-0.25, color='black', lw=1.5)

# Define an arbitrary legend handle with a proxy:
rec1 = plt.Rectangle((0, 0), 1, 1, fc='blue', lw=0, alpha=0.25)

# Generate the legend:
handles = [linea, lineb, linec, fillA, fillB, (fillA, fillB),
           rec1, (fillA, fillB, rec1)]
labels = ['a', 'b', 'c', 'A', 'B', 'A+B', 'C', 'A+B+C']
ax.legend(handles, labels, loc=2, ncol=4)

ax.axis(ymin=-1, ymax=2)

plt.show()

enter image description here

关于python - python中用户定义的图例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40042223/

相关文章:

python - 如何在 opencv 中更改鼠标光标图像?

python - 如何对数据框中的列进行分组,其中包含包含元组列表的列

python - Pyside 中的 Matplotlib 与 Qt 设计器 (PySide)

R 传单图例 : specify order instead of alphabetical

java - Jfreechart - 如何添加带有破折号的图例项?

r - ggplot + geom_point + 基于大小和颜色的图例

python - 如何实例化具有已知系数的 Scikit-Learn 线性模型而不进行拟合

python - 当鼠标悬停在某个区域(矩形)上时,显示标签/注释

python - 如何用matplotlib绘制小比例地形图?

python - 如何将 hist2d 图的无数据区域设置为零值颜色?