Python3-使用matplotlib.pyplot.fill_between

时间:2018-09-27 09:27:24

标签: python python-3.x matplotlib

我正在根据样本数量在“测试统计信息”上编写代码。我正在计算不同数量的样本的置信度,依此类推。我已经编写了代码以将误差容限可视化为样本数的函数,现在我想在图形之间填充一个区域。不幸的是,当我调用该函数时,出现以下错误:

TypeError:输入类型不支持ufunc'isfinite',并且根据强制转换规则” safe“

,不能将输入安全地强制转换为任何受支持的类型

这是我的完整代码:

import matplotlib
#matplotlib.use('Qt4Agg')
import matplotlib.pyplot as plt
import numpy as np
import math as m
from scipy.stats import t
from scipy.stats import norm
from matplotlib.ticker import MaxNLocator

# Confidence Levels
confidence_level = 0.95
# Number of Tested Samples
samples = np.linspace(2.0,20.0,19.0) # test samples
# True Mean
test_true_mean = 20.0 # krad (GomSpace TID level requirement)
# Standard Deviations
n_bins = 21
test_sigma1 = np.std(np.linspace(10.0,30.0,n_bins),ddof=1) # krad [10.0,30.0] interval
test_sigma2 = np.std(np.linspace(15.0,25.0,n_bins),ddof=1) # krad [15.0,25.0] interval
test_sigma3 = np.std(np.linspace(17.5,22.5,n_bins),ddof=1) # krad [17.5,22.5] interval
test_sigma = np.array([test_sigma1,test_sigma2,test_sigma3])
# Statistical Loop
stat_loop = 100
# Arrays creation
sim_rand_var = np.zeros([test_sigma.size,samples.size,stat_loop],object)
test_samples = np.zeros([test_sigma.size,samples.size,stat_loop],object)
test_samples_mean = np.zeros([test_sigma.size,samples.size,stat_loop],object)
test_samples_stdev = np.zeros([test_sigma.size,samples.size,stat_loop],object)
delta = np.zeros([test_sigma.size,samples.size,stat_loop],object)
error = np.zeros([test_sigma.size,samples.size,stat_loop],object)
lower_limit  = np.zeros([test_sigma.size,samples.size,stat_loop],object)
higher_limit = np.zeros([test_sigma.size,samples.size,stat_loop],object)
Ct = np.zeros(samples.size,object)
test_samples_mean_mean = np.zeros([test_sigma.size,samples.size],object)
delta_mean = np.zeros([test_sigma.size,samples.size],object)
lower_limit_mean  = np.zeros([test_sigma.size,samples.size],object)
higher_limit_mean = np.zeros([test_sigma.size,samples.size],object)
error_mean = np.zeros([test_sigma.size,samples.size],object)

#print("Standard Deviation [krad]    Test Samples (2 to 20)    Set         Error (%)")
#print("-------------------------    ----------------------    --------    ---------")

for k in range(0,test_sigma.size):
    for l in range(0,samples.size):
        for m in range(0,stat_loop):
            # Random Gaussian Numbers Generation
            sim_rand_var[k][l][m] = np.random.normal(test_true_mean,test_sigma[k],int(samples[l]))
            # Samples Mean and Standard Deviation
            test_samples_mean[k][l][m]  = np.mean(sim_rand_var[k][l][m])
            test_samples_stdev[k][l][m] = np.std(sim_rand_var[k][l][m],ddof=1)
            # Student-t Critical Values
            Ct[l] = t.ppf(confidence_level,int(samples[l])-1)
            # Deviation from the Sample Mean
            delta[k][l][m] = Ct[l]*test_samples_stdev[k][l][m]/np.sqrt(samples[l])
            # Error Lower and Higher Margins
            lower_limit[k][l][m]  = test_samples_mean[k][l][m] - delta[k][l][m]
            if lower_limit[k][l][m] < 0.0:
                lower_limit[k][l][m] = 0.0
            higher_limit[k][l][m] = test_samples_mean[k][l][m] + delta[k][l][m]
            # Test Global Error
            error[k][l][m] = 100*delta[k][l][m]/test_samples_mean[k][l][m]
            #print(error[k][l][m])
            #input = "%.3f                         %s                        %s          %.3f" % (test_sigma[k],samples[l],int(m),error[k][l][m])
            #print(input)

#print("errors_mean:")
for k in range(0,test_sigma.size):
    for l in range(0,samples.size):
        test_samples_mean_mean[k][l] = np.mean(test_samples_mean[k][l][:])
        delta_mean[k][l]             = np.mean(delta[k][l][:])
        lower_limit_mean[k][l]       = np.mean(lower_limit[k][l][:])
        higher_limit_mean[k][l]      = np.mean(higher_limit[k][l][:])
        error_mean[k][l]             = np.mean(error[k][l][:])

print(type(lower_limit_mean[0,1]))

for k in range(0,test_sigma.size):
    ax = plt.figure().gca()
    #plt.figure(k+1)
    plt.errorbar(samples,test_samples_mean_mean[k,:],yerr=delta_mean[k,:],fmt='.k')#uplims=True,lolims=True
    plt.hlines(xmin=0, xmax=25,y=test_true_mean,linewidth=2.0,color='r')
    plt.xlim(1,21)
    plt.ylim(test_true_mean-3*test_sigma[0],test_true_mean+3*test_sigma[0])
    ax.set_xticks(np.arange(len(samples))+2)
    plt.grid(color='gray',linestyle='--',linewidth=0.5)
    plt.xlabel('Test Samples')
    plt.ylabel('Confidence Margin [krad]')
    plt.suptitle('Confidence Margins Distribution (%s%%)'%(100*confidence_level),fontsize=14)
    plt.title('Population $\\mu$ = %0.1f krad, $\\sigma$ = %0.1f krad'%(test_true_mean,test_sigma[k]),fontsize=14)

    ax = plt.figure().gca()
    plt.plot(samples,higher_limit_mean[k,:],'b',linewidth=3.0)
    plt.plot(samples,lower_limit_mean[k,:],'r',linewidth=3.0)
    plt.hlines(xmin=0, xmax=25,y=test_true_mean,linewidth=2.0,color='k')
    plt.fill_between(samples,higher_limit_mean[k,:],lower_limit_mean[k,:])#,color='g')#,alpha=.5)
    plt.xlim(1,21)
    plt.ylim(test_true_mean-3*test_sigma[0],test_true_mean+3*test_sigma[0])
    ax.set_xticks(np.arange(len(samples))+2)
    plt.grid(color='gray',linestyle='--',linewidth=0.5)
plt.show()

在代码末尾调用matplotlib.pyplot.fill_between函数。我已经检查了变量类型,它们都是相同的()。

对错误在哪里有任何好的想法?

1 个答案:

答案 0 :(得分:0)

您已初始化所有数组以具有dtype = object。我不确定为什么要这样做,但是fill_between函数不能处理它。

解决方案是删除dtype=object。对您最终在fill_between中使用的两个数组执行此操作就足够了(尽管我不确定您根本不需要对象数组...):

lower_limit_mean  = np.zeros([test_sigma.size, samples.size])
higher_limit_mean = np.zeros([test_sigma.size, samples.size])

# rest of code

plt.fill_between(samples, higher_limit_mean[k,:], lower_limit_mean[k,:])

其中一个结果图如下:

enter image description here