Matplotlib传奇没有显示。 ax.arrow()的标签在for循环中定义。 Python 2.7

问题描述 投票:0回答:1

我无法使我的Matplotlib v.2.0.2图形的图例出现在Python 2.7中。我在下面有一个最小的例子,它在for循环中的轴上绘制箭头。

由于每次迭代分配标签关键字定义都无法使图例显示,因此我尝试使用条件来仅在第一次迭代期间设置标签。

在ax.legend()中尝试“bbox_to_anchor”和“loc”参数没有任何效果,所以我省略了任何图例参数。

任何人都有任何想法如何制作一个图例,分别在标签旁边显示带有红色和黑色箭头标记的“Arrow1”和“Arrow2”标签?

最小的例子:

import matplotlib.pyplot as plt

fig, ax = plt.subplots( )
ax.set_xlim( 0, 11 )
ax.set_ylim( 0, 2 )

kwargs1 ={'color':'r'}
kwargs2 ={'color':'black'}

for i in range(1, 11):

    ax.arrow( i-0.2, 0, 0, i/10., width=0.1, 
              label='Arrow1' if i == 1 else None, **kwargs1 )

    ax.arrow( i+0.2, 0, 0, i/10., width=0.1, 
              label='Arrow2' if i == 1 else None, **kwargs2 )

ax.legend( )

查看没有图例的输出图的链接:

arrow plot

编辑:

似乎每次迭代设置标签定义都可以。这是一个解决方案,在图例中显示具有正确颜色和标签的线标记:

import matplotlib.pyplot as plt

fig, ax = plt.subplots( )
ax.set_xlim( 0, 11 )
ax.set_ylim( 0, 2 )

kwargs1 ={'color':'r' }
kwargs2 ={'color':'black'}

for i in range(1, 11):

    Arrow1 = ax.arrow( i-0.2, 0, 0, i/10., width=0.1, 
              label='Arrow1', **kwargs1 )

    Arrow2 = ax.arrow( i+0.2, 0, 0, i/10., width=0.1, 
              label='Arrow2', **kwargs2 )

ax.legend( handles=[Arrow1, Arrow2] )

带图例的绘图输出图片:

arrow plot with legend

另一个编辑:

由于我认为我不会深究的原因,我的实际脚本(不是最小示例)的复杂性需要一个不可见的“代理艺术家”来为图例添加标签。在这些文档中为不受支持的艺术家here提出了这一点

import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle

fig, ax = plt.subplots( )
ax.set_xlim( 0, 11 )
ax.set_ylim( 0, 2 )

kwargs1 ={'color':'red' }
kwargs2 ={'color':'black'}

for i in range(1, 11):

    ax.arrow( i-0.2, 0, 0, i/10., width=0.1, **kwargs1 )
    Arrow1 = Rectangle((0, 0), 1, 1, label='Arrow1', fc='red')

    ax.arrow( i+0.2, 0, 0, i/10., width=0.1, **kwargs2 )
    Arrow2 = Rectangle((0, 0), 1, 1, label='Arrow2', fc='black')

ax.legend( handles=[Arrow1, Arrow2], loc='upper left' )
python python-2.7 matplotlib plot
1个回答
0
投票

我认为您需要指定legend()命令的'labels'和'handles'参数才能显示它

https://matplotlib.org/users/legend_guide.html

© www.soinside.com 2019 - 2024. All rights reserved.