问题描述
在我的绘图中,我试图在每个点使用多个值进行注释。
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],'bs')
12 w1,weights[marker][1]
---> 13 ax.annotate(f'w = ({w1:.1f},rets[marker]-.03))
TypeError: annotate() got multiple values for argument 'xy'
Python情节的新手。我想做的就是在图中标注两个点,每个点都显示两个权重。
---------------------------------------------------------------------------
注意-在@ewong的评论之后进行了以下更改。
for marker in markers_on:
plt.plot(vols[marker],weights[marker][1]
ax.annotate(r'w = ({w1:%.2f},{w2:%.2f})',w2))
没有错误,这很好。不幸的是,尽管它标记了两个位置,但没有显示权重。
在剧情出现之前,还有大量的空白。我必须在jupyter笔记本中向下滚动。
----------------------------------------------------------------------------------
for marker in markers_on:
plt.plot(vols[marker],weights[marker][1]
text = f'w = ({w1:.2f},{w2:.2f})',w2)
ax.annotate(s = text,rets[marker]-.03))
解决方法
之所以看不到粗细,是因为您使用xy=(vols[marker]+.08,rets[marker]-.03)
调整了文字位置。从您的图片中,我注意到x max为0.0225
。 0.08
大于0.0225
,因此文本超出范围。
import numpy as np
import matplotlib.pyplot as plt
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]
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]
text = f'w = ({w1:.1f},{w2:.1f})'
ax.annotate(text,xy=(vols[marker]+.005,rets[marker]-0.005))
plt.xlabel('Risk')
plt.ylabel('Return')
plt.show()