【问题标题】:One legend for all subplots in pyplotpyplot 中所有子图的一个图例
【发布时间】:2014-02-24 23:55:42
【问题描述】:

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

生成上图的代码sn-p:

# 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 所述,这也会像每个假人一样吗?那么有人可以为此发布一个最小的工作示例,因为我无法解决这个问题。

【问题讨论】:

    标签: python matplotlib legend


    【解决方案1】:

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

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

    【讨论】:

    • 如此美丽,如此优雅!我想可能没有一种简单的方法可以在一行中只显示两次标签和两个符号?
    • @tschoppi:你可以通过让图例有两列、将两个标签留空并减小列间距来作弊:lgd = plt.legend((s1, s2, h1, h2), (r'', r'', r'$\lambda$D', r'TI'), ncol = 2, loc='upper center', columnspacing=0)
    猜你喜欢
    • 1970-01-01
    • 2017-01-03
    • 2017-06-16
    • 2011-10-27
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    • 1970-01-01
    相关资源
    最近更新 更多