【发布时间】:2020-08-17 02:06:17
【问题描述】:
在我的情节中,我试图在每个点使用多个值进行注释。
weights = [np.array([w, 1-w]) for w in np.linspace(0, 1, 5)]
mu = [0.5, 0.25]
def portfolio_return(weights, returns):
return weights.T @ returns
rets = [portfolio_return(w, mu) for w in weights]
S = [[0.493, 0.11], [0.11, 0.16]]
def portfolio_vol(weights, cov):
return (weights.T @ cov @ weights)**0.5
vols = [portfolio_vol(w, S) for w in weights]
import matplotlib.pyplot as plt
%matplotlib inline
%config InlineBackend.figure_format = 'svg'
markers_on = [1, 3]
fig = plt.figure()
ax = fig.add_subplot(111)
plt.plot(vols, rets, 'g-')
for marker in markers_on:
plt.plot(vols[marker], rets[marker], 'bs')
w1, w2 = weights[marker][0], weights[marker][1]
ax.annotate(f'w = ({w1:.1f}, {w2:.1f})', (w1, w2), xy=(vols[marker]+.08, rets[marker]-.03))
plt.xlabel('Risk')
plt.ylabel('Return')
plt.show()
这会返回错误 -
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-8-0e29da296b76> in <module>
11 plt.plot(vols[marker], rets[marker], 'bs')
12 w1, w2 = weights[marker][0], weights[marker][1]
---> 13 ax.annotate(f'w = ({w1:.1f}, {w2:.1f})', (w1, w2), xy=(vols[marker]+.08, rets[marker]-.03))
TypeError: annotate() got multiple values for argument 'xy'
Python 绘图新手。我要做的就是在图上注释两个点,每个点都显示两个权重。
---------------------------------------------------------------------------
注意 - 在@ewong 的评论之后进行了以下更改。
for marker in markers_on:
plt.plot(vols[marker], rets[marker], 'bs')
w1, w2 = weights[marker][0], weights[marker][1]
ax.annotate(r'w = ({w1:%.2f}, {w2:%.2f})', (w1, w2))
没有错误,这很好。不幸的是,虽然它标记了两个位置,但没有显示权重。
在情节出现之前还有大量的空白。我必须在 jupyter notebook 中向下滚动。
----------------------------------------------------------------------------------
进行了进一步的更改。获得所有三个标记的情节。但不是重量。
for marker in markers_on:
plt.plot(vols[marker], rets[marker], 'bs')
w1, w2 = weights[marker][0], weights[marker][1]
text = f'w = ({w1:.2f}, {w2:.2f})', (w1, w2)
ax.annotate(s = text, xy=(vols[marker]+.08, rets[marker]-.03))
【问题讨论】:
-
aiui, from matplotlib.org/3.1.0/api/_as_gen/… ,
annotate()将(w1, w2)视为xy,因此再次指定xy是错误的。 -
谢谢@ewong 做出了你建议的改变。没有错误。不显示值。查看问题的编辑版本。
-
您可以将
f'w = ({w1:.1f}, {w2:.1f})', (w1, w2)分配给一个临时变量,并将该临时变量用作ax.annotate()中的文本。 -
@Ynjxsjmh 你能告诉我怎么做吗?代码会是什么样子?
-
text = f'w = ({w1:.1f}, {w2:.1f})', (w1, w2) \n ax.annotate(text=text, xy=(vols[marker]+.08, rets[marker]-.03))。您可以参考Axes.annotate() 了解text参数的含义。
标签: python matplotlib annotate