python - pyplot 中所有子图的一个图例

标签 python matplotlib legend

我目前正在绘制相同的数据,但在两个子图中以不同的方式对其进行可视化(见图): Scatter and horizontal bar plot

用于生成上图的代码片段:

# Figure
plt.figure(figsize=(14,8), dpi=72)
plt.gcf().suptitle(r'Difference between TI and $\lambda$D', size=16)
# Subplot 1
ax1 = plt.subplot2grid((1,3),(0,0),colspan=2)

# Plot scattered data in first subplot
plt.scatter(LE_x, LE_y, s=40, lw=0, color='gold', marker='o', label=r'$\lambda$D')
plt.scatter(MD_x, MD_y, s=40, lw=0, color='blue', marker='^', label=r'TI')

# Subplot 2
ax2 = plt.subplot2grid((1,3),(0,2))

plt.barh(vpos1, LE_hist, height=4, color='gold', label=r'$\lambda$D')
plt.barh(vpos2, MD_hist, height=4, color='blue', label=r'TI')

# Legend
legend = plt.legend()

有没有办法让图例同时显示散点和条形?这是否也会按照描述的那样进行每个假人here ?有人可以为此发布一个最小的工作示例吗,因为我无法理解这一点。

最佳答案

这对我有用,您基本上捕获绘制的每个图形的补丁句柄,并在最后手动创建图例。

import pylab as plt
import numpy as NP

plt.figure(figsize=(14,8), dpi=72)
plt.gcf().suptitle(r'Difference between TI and $\lambda$D', size=16)
# Subplot 1
ax1 = plt.subplot2grid((1,3),(0,0),colspan=2)
N = 100
LE_x = NP.random.rand(N)
LE_y = NP.random.rand(N)
MD_x = NP.random.rand(N)
MD_y = NP.random.rand(N)

# Plot scattered data in first subplot
s1 = plt.scatter(LE_x, LE_y, s=40, lw=0, color='gold', marker='o', label=r'$\lambda$D')
s2 = plt.scatter(MD_x, MD_y, s=40, lw=0, color='blue', marker='^', label=r'TI')

data = NP.random.randn(1000)
LE_hist, bins2 = NP.histogram(data, 50)

data = NP.random.randn(1000)
MD_hist, bins2 = NP.histogram(data, 50)
# Subplot 2
ax2 = plt.subplot2grid((1,3),(0,2))
vpos1 = NP.arange(0, len(LE_hist))
vpos2 = NP.arange(0, len(MD_hist)) + 0.5
h1 = plt.barh(vpos1, LE_hist, height=0.5, color='gold', label=r'$\lambda$D')
h2 = plt.barh(vpos2, MD_hist, height=0.5, color='blue', label=r'TI')

# Legend
#legend = plt.legend()
lgd = plt.legend((s1, s2, h1, h2), (r'$\lambda$D', r'TI', r'$\lambda$D', r'TI'), loc='upper center')
plt.show()

Result

关于python - pyplot 中所有子图的一个图例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22001756/

相关文章:

python - 将平面投影到新坐标系上

java - 如何在列中显示饼图的图例?

r - ggplot : how to get legend linetype group-dependent while errorbar linetype solid

python - 排序 Swagger 标签

python-3.x - 是否可以将 Python matplotlib.pyplot.hist 中的 X 轴从 bin 边缘切换为精确值?

python - 如何将 sns.facetgrid 保存为 pdf

r - 等号更改生存对象自动绘图中图例标签的呈现

python - 如何从 Python 2.7 中以空格分隔的字符串中提取整数?

python - 如何从元素不断变化的 JSONL 文件中提取元素?

python - 是否有用于处理和验证用户输入的 Python 库?