2016-08-21 89 views
1

我遇到了我的代码问题。它只显示一个图形的数​​据,另一个图形是空白的。我不明白为什么它不起作用。
我正在使用subplot()函数,我的猜测是,原因可能是我的函数格式化的方式。图只显示1图中的数据,但不显示其他

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() 

my graph

回答

2

你需要你的第一次调用plt.plot之前招行plt.subplot(211)。这是因为要调用plt.subplot必须在该子图的实际绘图之前。

+0

这就像一个魅力,我不能相信我错过了。谢谢!! – Cesar

+0

如果有效,您应该接受答案。 – bpachev

相关问题