【问题标题】:Colored label texts in a matplotlib stem plotmatplotlib 主干图中的彩色标签文本
【发布时间】:2018-01-24 12:56:17
【问题描述】:

我喜欢用 Pythons matplotlib 做一个茎裂,其中该图有一个图例框,其中标签的颜色与茎一样。目前我只得到一个图例,其中标签文本是正常的黑色,左侧有一个短的茎图。我希望它只是标签文本,但它的颜色与相应的词干相似(例如下面示例中的蓝色和绿色)。

请注意,实际的主干图是具有多个子图的图形的一部分,因此如果可能,我希望解决方案使用ax 处理程序而不是plt

import numpy as np
import matplotlib.pyplot as plt

n = np.arange(0, 10)

x1 = np.sin(n)
x2 = np.cos(n)

fig, ax = plt.subplots()

ax.stem(n, x1, 'b', markerfmt='bo', label="First")
ax.stem(n, x2, 'g', markerfmt='go', label="Second")
ax.legend()

plt.show()

简而言之,图例框应该只包含蓝色的“First”和绿色的“Second”,没有任何线条或点。

【问题讨论】:

    标签: python matplotlib colors


    【解决方案1】:

    您可以遍历图例条目以将文本颜色设置为图例句柄的颜色。

    leg = ax.legend()
    for h, t in zip(leg.legendHandles, leg.get_texts()):
        t.set_color(h.get_color()[0])
    

    现在不幸的是,在主图的情况下,图例句柄本身由几位艺术家组成,因此 t.set_visible(False) 之类的东西不能用于将句柄设置为不可见。相反,人们会在图例中挖掘得更深一些,以找到句柄的 DrawingArea 并将这个完整的区域设置为不可见。

    for l in leg._legend_handle_box.get_children()[0].get_children():
        l.get_children()[0].set_visible(False)
    

    完整示例:

    import numpy as np
    import matplotlib.pyplot as plt
    
    n = np.arange(0, 10)
    
    x1 = np.sin(n)
    x2 = np.cos(n)
    
    fig, ax = plt.subplots()
    
    ax.stem(n, x1, 'b', markerfmt='bo', label="First")
    ax.stem(n, x2, 'g', markerfmt='go', label="Second")
    
    leg = ax.legend()
    
    for h, t in zip(leg.legendHandles, leg.get_texts()):
        t.set_color(h.get_color()[0])
    
    for l in leg._legend_handle_box.get_children()[0].get_children():
        l.get_children()[0].set_visible(False)
    
    plt.show()
    

    【讨论】:

    • 谢谢,效果很好。我还用我的正常线图对其进行了测试,其中 ist 也适用。
    【解决方案2】:

    使用basefmt:

    import numpy as np
    import matplotlib.pyplot as plt
    
    n = np.arange(0, 10)
    
    x1 = np.sin(n)
    x2 = np.cos(n)
    
    fig, ax = plt.subplots()
    
    ax.stem(n, x1, 'b', markerfmt='bo', basefmt=" ", label="First")
    ax.stem(n, x2, 'g', markerfmt='go', basefmt=" ", label="Second")
    x = np.linspace(*ax.get_xlim())
    ax.plot(x, x*0, 'r-')
    ax.legend()
    
    plt.show()
    

    这导致

    我现在将基线以一种 hacky 的方式放入其中,但它确实有效。如果需要,您可以更改基线的部分,使其从 0 开始并在 9 结束。

    【讨论】:

      猜你喜欢
      • 2014-08-02
      • 2011-02-27
      • 2013-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-28
      • 2012-11-28
      • 2018-05-03
      相关资源
      最近更新 更多