Ana*_*ake 46 python textbox matplotlib
有没有办法告诉pyplot.text()像pyplot.legend()一样的位置?
像传奇论点这样的东西会很棒:
plt.legend(loc="upper left")
Run Code Online (Sandbox Code Playgroud)
我试图用字母标记不同轴的子图(例如"A","B").我认为必须有一种比手动估算位置更好的方法.
谢谢
Joe*_*ton 50
只需使用annotate并指定轴坐标即可.例如,"左上角"将是:
plt.annotate('Something', xy=(0.05, 0.95), xycoords='axes fraction')
Run Code Online (Sandbox Code Playgroud)
你也可以变得更漂亮,并指定一个点的常量偏移:
plt.annotate('Something', xy=(0, 1), xytext=(12, -12), va='top'
xycoords='axes fraction', textcoords='offset points')
Run Code Online (Sandbox Code Playgroud)
Ana*_*ake 31
我最初发布问题时不确定这是否可用,但现在可以使用loc参数.以下是一个例子:
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()
Run Code Online (Sandbox Code Playgroud)
这个问题已经很老了,但由于根据Add loc=best kwarg to pyplot.text()直到现在(2019 年)还没有通用的解决方案,我正在使用legend()以下解决方法来获得简单文本的自动放置盒子:
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()
Run Code Online (Sandbox Code Playgroud)
一般的想法是创建一个带有空行符号的图例,然后删除由此产生的空白空间。如何调整matplotlib图例框的大小?帮助我处理图例格式。
| 归档时间: |
|
| 查看次数: |
38310 次 |
| 最近记录: |