Skip to main content
 首页 » 编程设计

python之matplotlib 茎图中的彩色标签文本

2025年01月19日9jillzhang

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

请注意,实际的主干图是具有多个子图的图形的一部分,因此我希望解决方案尽可能使用 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”,没有任何线条或点。

请您参考如下方法:

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

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

不幸的是,在主干图的情况下,图例句柄本身由几位艺术家组成,因此像 t.set_visible(False) 这样的东西无法将句柄设置为不可见。相反,人们会在图例中更深入地挖掘以找到 handle 的 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()