如何制作只有文字的图例

How to make a legend with only text

我有两个地块想要制作传奇,现在它们看起来像这样:

我只希望 'C3H8' 和 'CO2' 在图例中,不包括蓝色框。现在我正在使用 matplotlib.patches 模块。还有什么我可以用的吗?

如@PaulH 所述,您只需要根据您的情况使用 plt.textplt.annotate

示例:

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0,10,100)
y = np.random.random(100)
y2 = np.random.random(100)

fig = plt.figure()
ax1 = fig.add_subplot(211)
ax1.scatter(x,y)
ax1.annotate("$C_{3}H_{8}$", xy=(0.9,0.9),xycoords='axes fraction',
             fontsize=14)

ax2 = fig.add_subplot(212)
ax2.scatter(x,y2)
ax2.annotate("$CO_{2}$", xy=(0.9,0.9),xycoords='axes fraction',
             fontsize=14)

fig.show()

此处注释中的xy参数指的是文本的x and y坐标。您可以相应地更改它们。

产生:

这是另一个看起来更像传说的解决方案。

import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid.anchored_artists import AnchoredText


def textonly(ax, txt, fontsize = 14, loc = 2, *args, **kwargs):
    at = AnchoredText(txt,
                      prop=dict(size=fontsize), 
                      frameon=True,
                      loc=loc)
    at.patch.set_boxstyle("round,pad=0.,rounding_size=0.2")
    ax.add_artist(at)
    return at

at = textonly(plt.gca(), "Line 1\nLine 2", loc = 2)
at = textonly(plt.gca(), "Line 1\nLine 2", loc = 4, fontsize = 55)
plt.gcf().show()
raw_input('pause')

您可以像这样在 pyplot 注释中使用 bbox 文本 属性:

import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111, autoscale_on=False, xlim=(-1, 5), ylim=(-5, 3))

ax.annotate("$C_{3}H_{8}$",
            xy=(0.86,0.9), xycoords='axes fraction',
            textcoords='offset points',
            size=14,
            bbox=dict(boxstyle="round", fc=(1.0, 0.7, 0.7), ec="none"))

plt.show()