You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Matplotlib茎状图:如何设置仅含彩色文本的Axes版图例

Fix Stem Plot Legend to Show Only Colored Text Labels

Got it, let's sort out this legend customization for your matplotlib stem plots! The default legend entries come with that tiny stem marker next to the text, but we can tweak things to display just colored text labels using Axes methods (since you prefer working with ax over plt).

Modified Code with Custom Legend

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.text import Text

n = np.arange(0, 10)
x1 = np.sin(n)
x2 = np.cos(n)

fig, ax = plt.subplots()
# Plot your stem lines as usual
ax.stem(n, x1, 'b', markerfmt='bo', label="First")
ax.stem(n, x2, 'g', markerfmt='go', label="Second")

# Create custom legend handles: Text objects matching your stem colors
handles = [
    Text(0, 0, "First", color='b'),
    Text(0, 0, "Second", color='g')
]

# Pass the custom handles and labels to the legend
ax.legend(handles=handles, labels=["First", "Second"])

plt.show()

How This Works

  • We import Text from matplotlib.text to build text-only legend entries. The dummy coordinates (0,0) don't matter here—they're just required for initializing the Text object.
  • Each Text object uses the exact color of its corresponding stem plot, so the legend text matches perfectly.
  • Instead of using the default auto-generated handles from stem(), we feed our custom Text handles to ax.legend() for a clean, color-matched legend.

Alternative Approach (Using Stem Plot Objects)

If you'd rather work with the existing stem plot outputs instead of creating Text objects manually, this method works too:

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()
# Capture the stem container objects when plotting
stem1 = ax.stem(n, x1, 'b', markerfmt='bo', label="First")
stem2 = ax.stem(n, x2, 'g', markerfmt='go', label="Second")

# Grab the default legend handles and labels
handles, labels = ax.get_legend_handles_labels()

# Modify handles to remove unwanted markers/stems and set text color
for idx, (handle, color) in enumerate(zip(handles, ['b', 'g'])):
    # Hide the stem line and marker in the legend entry
    handle[0].set_visible(False)
    handle[1].set_visible(False)
    # Replace the handle with a colored Text object
    handles[idx] = Text(0, 0, labels[idx], color=color)

# Update the legend with our modified handles
ax.legend(handles=handles, labels=labels)

plt.show()

This approach takes the default legend handles, hides the unnecessary stem/marker elements, and swaps them out for colored text labels.

Either method will give you the clean, color-matched legend you want—no extra markers, just text that matches your stem plot colors.

内容的提问来源于stack exchange,提问作者Martin Scharrer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:17:04