def gluco_plot(time,
               gluco,
               hypo=70,
               hyper=126,
               title="Patiend ID glucose level"):
    """Plot the glucose level on a time span.
    
    Parameters
    -------------------
    time : array of datetimes, the horizontal axis
    gluco : array of float, the correspondent glucose level on the vertical axis
    hypo : number, hypoglicaemia threshold in mg/dl (default is 70, i.e. 3.9 mmol/l)
    hyper : number, hyperglicaemia threshold in mg/dl (default is 126, i.e. 7 mmol/l)
    title : string, the title of the plot (optional)
    """
    plt.figure(figsize=(10, 6))
    plt.hlines(hypo,
               time[0],
               time[-1],
               linestyles='dashed',
               label='hypoglicaemia')
    plt.hlines(hyper,
               time[0],
               time[-1],
               linestyles='dotted',
               label='hyperglicaemia')
    plt.ylim([10, 410])
    plt.plot_date(time, gluco, '-', label='glucose level')
    plt.title(title)
    plt.ylabel('mg/dL')
    plt.xticks(rotation='vertical')
    plt.legend()
def plot_aucs(test_name, train_aucs, test_aucs):
    fig = plt.figure(figsize=(8, 8))
    axes = fig.gca()
    axes.plot(
        np.arange(N_EPOCHS), train_aucs)
    axes.plot(
        np.arange(N_EPOCHS), test_aucs)
    plt.xlabel("epoch")
    plt.ylabel("AUC")
    plt.xlim(0, 15)
    plt.ylim(0.5, 1.0)
    plt.legend(["train", "test (%s)" % test_name])
    fig.savefig("auc_%s.png" % test_name)
示例#3
0
def cgm(df,
        gluco_fit=None,
        hypo=70,
        hyper=126,
        title="Patiend ID CGM",
        savefig=False):
    """Plot the CGM signal on an input time span.

    Parameters
    -------------------
    df : DataFrame, the output returned by gluco_extract(..., return_df=True)
    gluco_fit : array of float, the results of a fitted model (optional)
    hypo : number, hypoglicaemia threshold in
           mg/dl (default is 70, i.e. 3.9 mmol/l)
    hyper : number, hyperglicaemia threshold
            in mg/dl (default is 126, i.e. 7 mmol/l)
    title : string, the title of the plot (optional)
    savefig : bool, if True save title.png
    """
    plt.figure(figsize=(10, 6), dpi=300)
    plt.hlines(hypo,
               df.index[0],
               df.index[-1],
               linestyles='dashed',
               label='hypoglicaemia')
    plt.hlines(hyper,
               df.index[0],
               df.index[-1],
               linestyles='dotted',
               label='hyperglicaemia')
    plt.ylim([10, 410])
    plt.plot_date(df.index, df.as_matrix(), '-', label='real CGM')
    if gluco_fit is not None:
        plt.plot(df.index, gluco_fit, '--', label='predicted CGM')
    plt.title(title)
    plt.ylabel('mg/dL')
    plt.xticks(rotation='vertical')
    plt.legend(bbox_to_anchor=(1.1, 1.0))
    if savefig: plt.savefig(title + '_fit.png')
示例#4
0
obs_errors = [100, 1.0, 1.0, 1.0, 0.001]
levels = [0.95, 0.835, 0.685, 0.51, 0.34, 0.2, 0.095, 0.025]

plt.rc('lines', linewidth=1.0)

plt.figure(figsize=(9, 3), facecolor='white')

dirs = ['double']
labels = ['64 bits']

handles = []

for d, l in zip(dirs, labels):
    print(f'Plotting {d}')

    handles += plot(d, l)

plt.ylim([0, 3.5])
plt.xlabel('Time')
plt.ylabel(f'Total analysis RMSE')
plt.title('')

# Add legend
leg = plt.legend(handles=handles, frameon=True, ncol=2)
rect = leg.get_frame()
rect.set_linewidth(0.0)
rect.set_alpha(0.7)

plt.savefig(f'total_error_compare.pdf', bbox_inches='tight')
plt.show()
示例#5
0
    plot_fields(d, c)

# Get axis limits and equalise
xlim = plt.gca().get_xlim()
ylim = plt.gca().get_ylim()
xlim = ylim = [min(xlim[0], ylim[0]), max(xlim[1], ylim[1])]
plt.xlim(xlim)
plt.ylim(ylim)

# Plot diagonal line
plt.plot(xlim, ylim, ls="--", c=".3")

plt.title('')
plt.xlabel('RMSE')
plt.ylabel('Spread')

# Legend for symbol
for field in fields:
    plt.scatter(-1, -1, s=90, marker=field[2], color='.3', label=field[1])

# Legend for color
plot_lines = [plt.plot([-1,-1.5], [-1,-1.5], color=colors[0])[0]]
plot_lines.append(plt.plot([-1,-1.5], [-1,-1.5], color=colors[1])[0])
col_leg = plt.legend(plot_lines, labels, loc=6, fontsize=12)

# Add both legends
plt.gca().add_artist(col_leg)
plt.legend(loc=2, fontsize=12)

plt.savefig(f'scatter_all_fields.pdf', bbox_inches='tight')
示例#6
0
                  first_guess[:, var + 1],
                  '--',
                  label="first guess",
                  alpha=1.0)
    axarr[i].plot(final_guess[:, 0],
                  final_guess[:, var + 1],
                  ':',
                  label="final guess")

plt.tight_layout()
leg = plt.figlegend(axarr[len(display_vars) - 1].get_lines(),
                    ['truth', 'observations', 'first guess', 'final guess'],
                    loc='lower center',
                    ncol=2)
plt.xlabel('Time (nondimensional units)')
f.subplots_adjust(bottom=0.17)
plt.savefig('vars.pdf', bbox_extra_artists=(leg, ), bbox_inches='tight')

# Plot diagnostics
plt.figure(figsize=(6, 3))
diagn = loadtxt('diagnostics.txt')
length = where(diagn <= 0)[0]
length = diagn.shape[0] if len(length) == 0 else length[0]
plt.semilogy(diagn[:length - 1, 0], diagn[:length - 1, 1])
plt.xlabel('Iterations')
plt.ylabel('Cost function')

plt.tight_layout()
plt.savefig('cost_function.pdf', bbox_inches='tight')
plt.show()
示例#7
0
}

plt.rc('lines', linewidth=1.0)
plt.style.use('ggplot')

plt.figure(figsize=(9, 3), facecolor='white')

dirs = ['double']
labels = ['64 bits']

handles = []

for d, l in zip(dirs, labels):
    print(f'Plotting {d}')

    handles += plot(d, fields[argv[2]][0], l)

plt.ylim([0, 3.5])
plt.xlabel('Time')
plt.ylabel(f'{fields[argv[2]][1]}')
plt.title('')

# Add legend
leg = plt.legend(handles=handles, frameon=True, ncol=2)
rect = leg.get_frame()
rect.set_linewidth(0.0)
rect.set_alpha(0.7)

plt.savefig(f'error_compare_{argv[2]}.pdf', bbox_inches='tight')
plt.show()
示例#8
0
lexicon = ['faster', 'Harry', 'home']
vector1 = Counter(tok for tok in tokenize(
    "The faster Harry got to the store, the faster and faster Harry would get home."
) if tok in lexicon)
vector2 = Counter(tok for tok in tokenize("Jill is faster than Harry.")
                  if tok in lexicon)
vector3 = Counter(tok for tok in tokenize("Jill and Harry fast.")
                  if tok in lexicon)
corpus = [vector1, vector2, vector3]

corpus
# [Counter({'Harry': 2, 'faster': 3, 'home': 1}),
#  Counter({'Harry': 1, 'faster': 1}),
#  Counter()]

df = pd.DataFrame.from_records(corpus)
df = df.fillna(0)
df
#    Harry  faster  home
# 0    2.0     3.0   1.0
# 1    1.0     1.0   0.0
# 2    1.0     0.0   0.0

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter3D(df.Harry, df.faster, df.home, s=20 * df.T.sum(), c=list('rgb'))
plt.xlabel('Harry')
plt.ylabel('faster')
ax.set_zlabel('home')
plt.show()
示例#9
0
    return np.random.gamma(alpha_new, 1 / beta_new)

#data_df = pd.read_csv("1113.HK.csv", header=0, delimiter=",")


beta_0_true = 0.00008503
beta_1_true = 0.60954186
tau_true = 1

N = 100
x = np.random.uniform(low = 0, high = 4, size = N)
y = np.random.normal(beta_0_true + beta_1_true * x, 1 / np.sqrt(tau_true))

synth_plot = plt.plot(x, y, "o")
plt.xlabel("x")
plt.ylabel("y")

# specify initial values
init = {"beta_0": 0,
        "beta_1": 0,
        "tau": 2}

## specify hyper parameters
hypers = {"mu_0": 0,
         "tau_0": 1,
         "mu_1": 0,
         "tau_1": 1,
         "alpha": 2,
         "beta": 1}

def gibbs(y, x, iters, init, hypers):
示例#10
0
    'q': ('Specific Humidity [kg/kg]', 'Specific humidity (kg/kg)')
}

plt.figure(figsize=(5, 5), facecolor='white')

dirs = ['double', 'reduced']
labels = ['64 bits', '22 bits']

handles = []

for d, l in zip(dirs, labels):
    print(f'Plotting {d}')

    handles += plot(d, fields[argv[2]][0], l)

plt.xlabel(f'{fields[argv[2]][1]}')
plt.ylabel('Sigma coordinate')
plt.ylim([1.0, 0.0])
plt.xlim([0.0, max(1.0, plt.gca().get_xlim()[1])])
plt.gca().set_xlim(left=0)
plt.title('')

# Add legend
leg = plt.legend(handles=handles, frameon=True, ncol=2, loc='lower center')
rect = leg.get_frame()
rect.set_linewidth(0.0)
rect.set_alpha(0.7)

plt.savefig(f'vertical_error_{argv[2]}.pdf', bbox_inches='tight')
plt.show()