我的代码出现问题。它仅显示一个图表的数据,另一个图表为空白。我无法理解为什么它不起作用
我使用subplot()
函数,我的猜测是原因可能是我的函数格式化。
import numpy as np
import matplotlib.pyplot as plt
import cvxopt as opt
from cvxopt import blas, solvers
import pandas as pd
import mpld3
from mpld3 import plugins
np.random.seed(123)
solvers.options['show_progress'] = False
n_assets = 4
n_obs = 1000 # original 1000
return_vec = np.random.randn(n_assets, n_obs)
def rand_weights(n):
k = np.random.rand(n)
return k / sum(k) print(rand_weights(n_assets)) print(rand_weights(n_assets))
def random_portfolio(returns):
p = np.asmatrix(np.mean(returns,axis=1))
w = np.asmatrix(rand_weights(returns.shape[0]))
C = np.asmatrix(np.cov(returns))
mu = w * p.T
sigma = np.sqrt(w * C * w.T)
#this recursion reduces outlier to keep the graph nice
if sigma > 2:
return random_portfolio(returns)
return mu, sigma
n_portfolios = 500
means, stds = np.column_stack([random_portfolio(return_vec) for _ in range(n_portfolios)])
plt.plot(return_vec.T, alpha=.4);
plt.xlabel('time')
plt.ylabel('returns')
plt.figure(1)
plt.subplot(212)
plt.plot(stds, means, 'o', markersize = 5)
plt.xlabel('std')
plt.ylabel('mean')
plt.title('Mean and standard deviation of returns of randomly generated portfolios')
plt.subplot(211)
plt.figure(1)
plt.show()
答案 0 :(得分:2)
您需要在第一次致电plt.subplot(211)
之前移动plt.plot
行。这是因为对plt.subplot
的调用必须先于该子图中的实际绘图。