import numpy as np
import matplotlib.pyplot as plt
from matplotlib.offsetbox import AnchoredText
# make some data
x = np.arange(10)
y = x
# set up figure and axes
f, ax = plt.subplots(1,1)
# loc works the same as it does with figures (though best doesn't work)
# pad=5 will increase the size of padding between the border and text
# borderpad=5 will increase the distance between the border and the axes
# frameon=False will remove the box around the text
anchored_text = AnchoredText("Test", loc=2)
ax.plot(x,y)
ax.add_artist(anchored_text)
plt.show()
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as mpl_patches
x = np.linspace(-1,1)
fig, ax = plt.subplots()
ax.plot(x, x*x)
# create a list with two empty handles (or more if needed)
handles = [mpl_patches.Rectangle((0, 0), 1, 1, fc="white", ec="white",
lw=0, alpha=0)] * 2
# create the corresponding number of labels (= the text you want to display)
labels = []
labels.append("pi = {0:.4g}".format(np.pi))
labels.append("root(2) = {0:.4g}".format(np.sqrt(2)))
# create the legend, supressing the blank space of the empty line symbol and the
# padding between symbol and label by setting handlelenght and handletextpad
ax.legend(handles, labels, loc='best', fontsize='small',
fancybox=True, framealpha=0.7,
handlelength=0, handletextpad=0)
plt.show()
3条答案
按热度按时间roejwanj1#
只需使用
annotate
并指定轴坐标。例如,“左上角”将是:你也可以更漂亮,并指定一个恒定的点偏移:
更多说明请参见示例here和更详细的示例。
tv6aics12#
我不确定当我最初发布问题时是否可用,但现在实际上可以使用loc参数了。下面是一个例子:
egmofgnx3#
这个问题已经很老了,但是根据Add loc=best kwarg to pyplot.text(),到目前为止(2019年)还没有通用的解决方案,我使用
legend()
和以下解决方案来获得简单文本框的自动放置:一般的想法是创建一个带有空行符号的图例,然后删除产生的空白。How to adjust the size of matplotlib legend box?帮助我格式化图例。