コード例 #1
0
ファイル: helpers.py プロジェクト: sxp825/Pytorch-NMT
def show_plot(points):
    plt.figure()
    fig, ax = plt.subplots()
    loc = ticker.MultipleLocator(base=0.2) # put ticks at regular intervals
    ax.yaxis.set_major_locator(loc)
    plt.plot(points)
コード例 #2
0
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker

# Question 2. (c) Plot

data = np.loadtxt('s_price_1yr.dat')

s = data[:, 0]
t = data[:, 1]

tick_spacing = 0.1

fig, ax = plt.subplots(1, 1)
ax.plot(t, s)
ax.xaxis.set_major_locator(ticker.MultipleLocator(tick_spacing))
plt.xlabel("Time (years)")
plt.ylabel("Stock Price")
plt.title("Daily Share Price for One Year")
plt.xlim(min(t), max(t))
plt.ylim(min(s) - 5, max(s) + 5)
plt.show()

# Question 2. (d) Plot

data_1yr = np.loadtxt('portfolio_value_1yr.dat')
data_2yr = np.loadtxt('portfolio_value_2yr.dat')
data_5yr = np.loadtxt('portfolio_value_5yr.dat')
data_20yr = np.loadtxt('portfolio_value_20yr.dat')

print(data_1yr)
コード例 #3
0
    def jacobian_aspcap(self, jacobian=None, dr=14):
        """
        NAME: cal_jacobian
        PURPOSE: calculate jacobian
        INPUT:
        OUTPUT:
        HISTORY:
            2017-Nov-20 Henry Leung
        """
        import pylab as plt
        import numpy as np
        import seaborn as sns
        import matplotlib.ticker as ticker
        from astroNN.apogee.chips import wavelength_solution, chips_split
        from urllib.request import urlopen
        from urllib.error import HTTPError
        import pandas as pd

        if jacobian is None:
            raise ValueError('Please provide jacobian to plot')
        if len(jacobian.shape) == 3:
            jacobian = np.mean(jacobian, axis=-1)
        elif len(jacobian.shape) == 2:
            pass
        else:
            raise ValueError('Unknown jacobian shape!!')

        # Some plotting variables for asthetics
        plt.rcParams['axes.facecolor'] = 'white'
        sns.set_style("ticks")
        plt.rcParams['axes.grid'] = False
        plt.rcParams['grid.color'] = 'gray'
        plt.rcParams['grid.alpha'] = '0.4'
        path = os.path.join(self.fullfilepath, 'jacobian')
        if not os.path.exists(path):
            os.makedirs(path)

        fullname = self.targetname
        lambda_blue, lambda_green, lambda_red = wavelength_solution(dr=dr)

        for j in range(self._labels_shape):
            fig = plt.figure(figsize=(45, 30), dpi=150)
            scale = np.max(np.abs((jacobian[j, :])))
            scale_2 = np.min((jacobian[j, :]))
            blue, green, red = chips_split(jacobian[j, :], dr=dr)
            blue, green, red = blue[0], green[0], red[0]
            ax1 = fig.add_subplot(311)
            fig.suptitle(f'{fullname[j]}', fontsize=50)
            ax1.set_ylabel(r'$\partial$' + fullname[j] + '/' +
                           r'$\partial\lambda$',
                           fontsize=40)
            ax1.set_ylim(scale_2, scale)
            ax1.plot(lambda_blue, blue, linewidth=0.9, label='astroNN')
            ax2 = fig.add_subplot(312)
            ax2.set_ylabel(r'$\partial$' + fullname[j] + '/' +
                           r'$\partial\lambda$',
                           fontsize=40)
            ax2.set_ylim(scale_2, scale)
            ax2.plot(lambda_green, green, linewidth=0.9, label='astroNN')
            ax3 = fig.add_subplot(313)
            ax3.set_ylim(scale_2, scale)
            ax3.set_ylabel(r'$\partial$' + fullname[j] + '/' +
                           r'$\partial\lambda$',
                           fontsize=40)
            ax3.plot(lambda_red, red, linewidth=0.9, label='astroNN')
            ax3.set_xlabel(r'Wavelength $\lambda$ (Angstrom)', fontsize=40)

            ax1.axhline(0, ls='--', c='k', lw=2)
            ax2.axhline(0, ls='--', c='k', lw=2)
            ax3.axhline(0, ls='--', c='k', lw=2)

            try:
                if dr == 14:
                    url = f"https://svn.sdss.org/public/repo/apogee/idlwrap/trunk/lib/l31c/" \
                          f"{aspcap_windows_url_correction(self.targetname[j])}.mask"
                    df = np.array(
                        pd.read_csv(urlopen(url), header=None, sep='\t'))
                else:
                    raise ValueError('Only support DR14')
                aspcap_windows = df * scale
                aspcap_windows = aspcap_windows.T  # Fix the shape to the one I expect
                aspcap_blue, aspcap_green, aspcap_red = chips_split(
                    aspcap_windows, dr=dr)
                print(
                    f'Found {aspcap_windows_url_correction(self.targetname[j])} ASPCAP window at: {url}'
                )
                ax1.plot(lambda_blue,
                         aspcap_blue[0],
                         linewidth=0.9,
                         label='ASPCAP windows')
                ax2.plot(lambda_green,
                         aspcap_green[0],
                         linewidth=0.9,
                         label='ASPCAP windows')
                ax3.plot(lambda_red,
                         aspcap_red[0],
                         linewidth=0.9,
                         label='ASPCAP windows')
            except HTTPError:
                print(
                    f'No ASPCAP window data for {aspcap_windows_url_correction(self.targetname[j])}'
                )
            tick_spacing = 50
            ax1.xaxis.set_major_locator(ticker.MultipleLocator(tick_spacing))
            ax2.xaxis.set_major_locator(
                ticker.MultipleLocator(tick_spacing / 1.5))
            ax3.xaxis.set_major_locator(
                ticker.MultipleLocator(tick_spacing / 1.7))
            ax1.minorticks_on()
            ax2.minorticks_on()
            ax3.minorticks_on()

            ax1.tick_params(labelsize=30, width=2, length=20, which='major')
            ax1.tick_params(width=2, length=10, which='minor')
            ax2.tick_params(labelsize=30, width=2, length=20, which='major')
            ax2.tick_params(width=2, length=10, which='minor')
            ax3.tick_params(labelsize=30, width=2, length=20, which='major')
            ax3.tick_params(width=2, length=10, which='minor')
            ax1.legend(loc='best', fontsize=40)
            plt.tight_layout()
            plt.subplots_adjust(left=0.05)
            plt.savefig(path + f'/{self.targetname[j]}_jacobian.png')
            plt.close('all')
            plt.clf()
コード例 #4
0
def plot_conn_mat(conn_matrix,
                  labels,
                  out_path_fig,
                  cmap,
                  binarized=False,
                  dpi_resolution=300):
    """
    Plot a connectivity matrix.

    Parameters
    ----------
    conn_matrix : array
        NxN matrix.
    labels : list
        List of string labels corresponding to ROI nodes.
    out_path_fig : str
        File path to save the connectivity matrix image as a .png figure.
    """
    import warnings
    warnings.filterwarnings("ignore")
    import matplotlib
    import mplcyberpunk
    matplotlib.use('Agg')
    from matplotlib import pyplot as plt
    plt.style.use("cyberpunk")
    from matplotlib import pyplot as plt
    from nilearn.plotting import plot_matrix
    from pynets.core import thresholding
    import matplotlib.ticker as mticker

    conn_matrix = thresholding.standardize(conn_matrix)
    conn_matrix_bin = thresholding.binarize(conn_matrix)
    conn_matrix_plt = np.nan_to_num(np.multiply(conn_matrix, conn_matrix_bin))

    try:
        plot_matrix(
            conn_matrix_plt,
            figure=(10, 10),
            labels=labels,
            vmax=np.percentile(conn_matrix_plt[conn_matrix_plt > 0], 95),
            vmin=0,
            reorder="average",
            auto_fit=True,
            grid=False,
            colorbar=True,
            cmap=cmap,
        )
    except RuntimeWarning:
        print("Connectivity matrix too sparse for plotting...")

    if len(labels) > 500:
        tick_interval = 5
    elif len(labels) > 100:
        tick_interval = 4
    elif len(labels) > 50:
        tick_interval = 2
    else:
        tick_interval = 1

    plt.axes().yaxis.set_major_locator(mticker.MultipleLocator(tick_interval))
    plt.axes().xaxis.set_major_locator(mticker.MultipleLocator(tick_interval))
    for param in ['figure.facecolor', 'axes.facecolor', 'savefig.facecolor']:
        plt.rcParams[param] = '#000000'
    plt.savefig(out_path_fig, dpi=dpi_resolution)
    plt.close()
    return
コード例 #5
0
ファイル: plot_threadpool.py プロジェクト: wullm/swiftsim
              bbox_to_anchor=(0.0, 1.05, 1.0, 0.2),
              mode="expand",
              ncol=5)
    box = ax.get_position()
    ax.set_position([box.x0, box.y0, box.width, box.height * 0.8])

# Start and end of time-step
real_start_t = (mintic_step - tic_step) / CPU_CLOCK
ax.plot([real_start_t, real_start_t], [0, nthread + nrow + 1],
        "k--",
        linewidth=1)

ax.plot([end_t, end_t], [0, nthread + nrow + 1], "k--", linewidth=1)

ax.set_xlabel("Wall clock time [ms]", labelpad=0.0)
if expand == 1:
    ax.set_ylabel("Thread ID", labelpad=0)
else:
    ax.set_ylabel("Thread ID * " + str(expand), labelpad=0)
ax.set_yticks(pl.array(list(range(nthread))), True)

loc = plticker.MultipleLocator(base=expand)
ax.yaxis.set_major_locator(loc)
ax.grid(True, which="major", axis="y", linestyle="-")

pl.show()
pl.savefig(outpng)
print("Graphics done, output written to", outpng)

sys.exit(0)
コード例 #6
0
ファイル: visualising.py プロジェクト: valliAlla/my-prac-repo
        ax1.plot(x1, y1, 'r-', x2, y2, 'r-', x3, y3, 'b.', markersize=10)  # , alpha=0.7)
        ax1.set_xlabel('log2(ratio)', fontsize=20)
        ax1.set_ylabel('-log10(p-value)', fontsize=20)

        if "label" in self.df.columns:
            cond = self.df["s_val"] >= s_value_cutoff
            for index_, row in self.df[cond].iterrows():
                label = row["label"]
                x_coord = row["ratio"]
                y_coord = row["p_val"]
                if x_coord < 0:
                    ax1.plot(x_coord,y_coord,'r.',markersize=10)
                    ax1.annotate(label,xy=(x_coord, y_coord),xycoords='data',xytext=(5,5),
                        textcoords='offset points',arrowprops=dict(arrowstyle="-"),fontsize=12,color='r')
                else:
                    ax1.plot(x_coord,y_coord,'g.',markersize=10)
                    ax1.annotate(label, xy=(x_coord, y_coord), xycoords='data', xytext=(5, 5),
                    textcoords='offset points', arrowprops=dict(arrowstyle="-"), fontsize=12,color="g")



                #ax1.annotate(label, xy=(x_coord, y_coord), xycoords='data', xytext=(5, 5),
                    #textcoords='offset points', arrowprops=dict(arrowstyle="-"), fontsize=12)

        return fig, ax1
       volc = Volcano(x["log(FC)"], x["log(P)"], x["Symbol"],
               s_curve_x_axis_overplot=2, s_curve_y_axis_overplot=.5)
fig, axs = volc.get_fig()
axs.xaxis.set_major_locator(ticker.MultipleLocator(1.0))
コード例 #7
0
plt.plot(lucro_hof_all[melhor][0].index, lucro_hof_all[melhor][0].iloc[:,3])
plt.plot(lucro_hof_all[melhor][0].index, lucro_hof_all[melhor][0].iloc[:,4])

# Shrink current axis by 20%
box = ax.get_position()
ax.set_position([box.x0, box.y0 + box.height * 0.1, box.width, box.height * 0.9])

# Put a legend to the right of the current axis
ax.legend(["Trading Balance (BTC)", "Holding Balance (BTC)"], loc='upper center', bbox_to_anchor=(0.5, -0.15),
           ncol=5)

#plt.title("Saldo Ao Longo do Tempo - %s" %melhor)
plt.xlabel("Date")
plt.ylabel("Balance (BTC)")

loc = plticker.MultipleLocator(base=3.5) # this locator puts ticks at regular intervals
ax.xaxis.set_major_locator(loc)
ax.xaxis.set_major_formatter(mdates.DateFormatter('%m/%d/%y'))

plt.show()

figura.savefig("D:/Dropbox/Nebuloso/Artigo/Artigo/Imagens/saldoxtempo.eps") #mudar para eps




# valor no tempo melhor resultado
melhor_saldo = np.argmax(tabela_saldo_final_hof.loc[:,"Relação Saldo Final Algoritmo/Saldo Final Manter (%)"])
figura = plt.figure()
ax = plt.subplot(111)
plt.plot(lucro_hof_all[melhor_saldo][0].index, lucro_hof_all[melhor_saldo][0].iloc[:,3])
sum_upper_asymptomatic_testing_list = [x * 100 for x in upper_asymptomatic_testing_list]

sum_mean_symptomatic_testing_list =  [x * 100 for x in mean_symptomatic_testing_list]
sum_upper_symptomatic_testing_list = [x * 100 for x in upper_symptomatic_testing_list]

x = list(range(len(sum_mean_asymptomatic_testing_list)))

plt.bar(x, sum_mean_asymptomatic_testing_list, label='ASY Testing', tick_label = xlabel, hatch = patterns[2])
plt.bar(x, sum_mean_symptomatic_testing_list, bottom= sum_mean_asymptomatic_testing_list, label='SY Testing', hatch = patterns[1])
plt.legend(loc=4)


y_upper_error = [ x-y for x,y in zip(sum_upper_asymptomatic_testing_list, sum_mean_asymptomatic_testing_list)]
ax.errorbar(x, sum_mean_asymptomatic_testing_list, yerr = y_upper_error, color = "k", capsize=13, fmt=".", ms = 0.0001, elinewidth=5, capthick = 2)

# plt.gca().xaxis.set_major_locator(mticker.MultipleLocator(10))

plt.gca().yaxis.set_major_locator(mticker.MultipleLocator(50))

plt.xlabel(r'Population $\bf{N}$', fontsize=35) 
plt.ylabel("Average POMDP action", fontsize=35)

plt.tight_layout()

plt.savefig("./Plots/Asymptomatic_Testing_Number.png", dpi = 400)
plt.close(fig)




コード例 #9
0
zmean=np.append(zmean,np.median(x11[xx[0]]))
xx=np.where((idsurvey1!=15) & (idsurvey1!=1) & (idsurvey1!=4))
n, bins, patches = ax[2].hist(x11[xx[0]], bins=15,range=[-3,3], histtype='step', alpha=0.75,color='black',linewidth=2)
zmean=np.append(zmean,np.median(x11[xx[0]]))

xx=np.where((idsurvey1!=15) & (idsurvey1!=1) & (idsurvey1!=4)&(z1>0.5))
n, bins, patches = ax[2].hist(x11[xx[0]], bins=15,range=[-.3,.3], histtype='step', alpha=0.75,color='purple',linewidth=2)
zmean=np.append(zmean,np.median(x11[xx[0]]))


str2=['black','green','blue','red','purple']
proxy = [plt.Rectangle((0,0),.02,.02,fc = str2[pc]) for pc in range(0,5)]
ax[2].legend(proxy, ["Low-z  "+fformx(zmean[3]).strip(), "SDSS  "+fformx(zmean[1]).strip(),"PS1  "+fformx(zmean[0]).strip(), "SNLS  "+fformx(zmean[2]).strip(), "HST  "+fformx(zmean[4]).strip()],loc='upper left',prop={'size':8},frameon=False,fontsize=8,ncol=2)

#plt.text(2.1,45,"x1",fontdict={'fontsize':20})

ax[2].set_xlabel(r'$x_1$',labelpad=-1)
ax[2].set_ylabel('\# of SNeIa')
ax[2].set_ylim(0.0,100)
ax[2].set_xlim(-3.0,3.0)

ax[0].yaxis.set_major_locator(ticker.MultipleLocator(20))
ax[1].yaxis.set_major_locator(ticker.MultipleLocator(20))
ax[2].yaxis.set_major_locator(ticker.MultipleLocator(20))

plt.show()

plt.savefig('csz_hist.png')

asdf
コード例 #10
0
def plotTrajPose(xyzrxryrzT, xyzrxryrzVT, xyzrxryrzAT, vTcPT, aTcpT, t):

    fig1 = plt.figure().gca()
    try:
        fig1.plot(t, xyzrxryrzT[:, 0], color='r', label='X')
        fig1.plot(t, xyzrxryrzT[:, 1], color='g', label='Y')
        fig1.plot(t, xyzrxryrzT[:, 2], color='b', label='Z')
    except:
        return 1
    fig1.xaxis.set_major_locator(ticker.MultipleLocator(0.50))
    fig1.xaxis.set_minor_locator(ticker.MultipleLocator(0.25))
    plt.grid(True)
    plt.title("Pose XYZ")
    plt.ylabel('XYZ in mm')
    plt.xlabel('Zeit in s')
    plt.legend()

    fig2 = plt.figure().gca()
    try:
        fig2.plot(t, xyzrxryrzT[:, 3], color='c', label='rx')
        fig2.plot(t, xyzrxryrzT[:, 4], color='magenta', label='ry')
        fig2.plot(t, xyzrxryrzT[:, 5], color='orange', label='rz')
    except:
        return 2
    fig2.xaxis.set_major_locator(ticker.MultipleLocator(0.50))
    fig2.xaxis.set_minor_locator(ticker.MultipleLocator(0.25))
    plt.grid(True)
    plt.title("Pose rxryrz")
    plt.ylabel('rxryrz in Rad')
    plt.xlabel('Zeit in s')
    plt.legend()

    fig3 = plt.figure().gca()
    try:
        fig3.plot(t, vTcPT[:], color='r', label='vTCP')
    except:
        return 3
    fig3.xaxis.set_major_locator(ticker.MultipleLocator(0.50))
    fig3.xaxis.set_minor_locator(ticker.MultipleLocator(0.25))
    plt.grid(True)
    plt.title("TCP Geschwindigkeit")
    plt.ylabel('Geschwindigkeit in mm/s')
    plt.xlabel('Zeit in s')
    plt.legend()

    fig4 = plt.figure().gca()
    try:
        fig4.plot(t, aTcpT[:], color='r', label='aTCP')
    except:
        return 4
    fig4.xaxis.set_major_locator(ticker.MultipleLocator(0.50))
    fig4.xaxis.set_minor_locator(ticker.MultipleLocator(0.25))
    plt.grid(True)
    plt.title("TCP Beschleunigung")
    plt.ylabel('Beschleunigung in mm/ s**2')
    plt.xlabel('Zeit in s')
    plt.legend()

    fig5 = plt.figure().gca()
    try:
        fig5.plot(t, xyzrxryrzVT[:, 0], color='r', label='dX')
        fig5.plot(t, xyzrxryrzVT[:, 1], color='g', label='dY')
        fig5.plot(t, xyzrxryrzVT[:, 2], color='b', label='dZ')
    except:
        return 5
    fig5.xaxis.set_major_locator(ticker.MultipleLocator(0.50))
    fig5.xaxis.set_minor_locator(ticker.MultipleLocator(0.25))
    plt.grid(True)
    plt.title("Pose Geschwindigkeit XYZ")
    plt.ylabel('XYZ in mm/s')
    plt.xlabel('Zeit in s')
    plt.legend()

    fig6 = plt.figure().gca()
    try:
        fig6.plot(t, xyzrxryrzAT[:, 0], color='r', label='ddX')
        fig6.plot(t, xyzrxryrzAT[:, 1], color='g', label='ddY')
        fig6.plot(t, xyzrxryrzAT[:, 2], color='b', label='ddZ')
    except:
        return 6
    fig6.xaxis.set_major_locator(ticker.MultipleLocator(0.50))
    fig6.xaxis.set_minor_locator(ticker.MultipleLocator(0.25))
    plt.grid(True)
    plt.title("Pose Beschleunigung XYZ")
    plt.ylabel('XYZ in mm/s**2')
    plt.xlabel('Zeit in s')
    plt.legend()

    return 0
コード例 #11
0
def plotCSVTcp(filenameCSV):

    filename = os.path.splitext(filenameCSV)[0]

    with open(('csv/' + filenameCSV)) as csvfile:
        r = csv_reader.CSVReader(csvfile)

    fig1 = plt.figure().gca()
    try:
        fig1.plot(r.timestamp, r.target_q_0, color='r', label='q0')
        fig1.plot(r.timestamp, r.target_q_1, color='g', label='q1')
        fig1.plot(r.timestamp, r.target_q_2, color='b', label='q2')
        fig1.plot(r.timestamp, r.target_q_3, color='c', label='q3')
        fig1.plot(r.timestamp, r.target_q_4, color='magenta', label='q4')
        fig1.plot(r.timestamp, r.target_q_5, color='orange', label='q5')
    except:
        print("Singular target_q_0-5")
        #return 1
    fig1.xaxis.set_major_locator(ticker.MultipleLocator(0.50))
    fig1.xaxis.set_minor_locator(ticker.MultipleLocator(0.25))
    plt.grid(True)
    plt.title(filenameCSV + " - Gelenkwinkel")
    plt.ylabel('Gelenkwinkel in Rad')
    plt.xlabel('Zeit in s')
    plt.legend()
    plt.savefig('png/' + filename + '_q.png', dpi=300)

    fig12 = plt.figure().gca()
    try:
        fig12.plot(r.timestamp, r.target_qd_0, color='r', label='qd0')
        fig12.plot(r.timestamp, r.target_qd_1, color='g', label='qd1')
        fig12.plot(r.timestamp, r.target_qd_2, color='b', label='qd2')
        fig12.plot(r.timestamp, r.target_qd_3, color='c', label='qd3')
        fig12.plot(r.timestamp, r.target_qd_4, color='magenta', label='qd4')
        fig12.plot(r.timestamp, r.target_qd_5, color='orange', label='qd5')
    except:
        print("Singular target_qd_0-5")
        #return 12
    fig12.xaxis.set_major_locator(ticker.MultipleLocator(0.50))
    fig12.xaxis.set_minor_locator(ticker.MultipleLocator(0.25))
    plt.grid(True)
    plt.title(filenameCSV + " - Winkelgeschwindigkeit")
    plt.ylabel('Winkelgeschwindigkeit in Rad/s')
    plt.xlabel('Zeit in s')
    plt.legend()
    plt.savefig('png/' + filename + '_qd.png', dpi=300)

    fig2 = plt.figure().gca()
    try:
        fig2.plot(r.timestamp, r.target_TCP_pose_0, color='r', label='X')
        fig2.plot(r.timestamp, r.target_TCP_pose_1, color='g', label='Y')
        fig2.plot(r.timestamp, r.target_TCP_pose_2, color='b', label='Z')
    except:
        print("Singular target_TCP_pose_0-2")
    # return 2
    fig2.xaxis.set_major_locator(ticker.MultipleLocator(0.50))
    fig2.xaxis.set_minor_locator(ticker.MultipleLocator(0.25))
    plt.grid(True)
    plt.title(filenameCSV + " - Pose XYZ")
    plt.ylabel('XYZ in m')
    plt.xlabel('Zeit in s')
    plt.legend()
    plt.savefig('png/' + filename + '_Pose_XYZ.png', dpi=300)

    fig3 = plt.figure().gca()
    try:
        fig3.plot(r.timestamp, r.target_TCP_pose_3, color='c', label='rx')
        fig3.plot(r.timestamp,
                  r.target_TCP_pose_4,
                  color='magenta',
                  label='ry')
        fig3.plot(r.timestamp, r.target_TCP_pose_5, color='orange', label='rz')
    except:
        print("Singular target_TCP_pose_3-5")
        #return 3
    fig3.xaxis.set_major_locator(ticker.MultipleLocator(0.50))
    fig3.xaxis.set_minor_locator(ticker.MultipleLocator(0.25))
    plt.grid(True)
    plt.title(filenameCSV + " - Pose rxryrz")
    plt.ylabel('rxryrz in Rad')
    plt.xlabel('Zeit in s')
    plt.legend()
    plt.savefig('png/' + filename + '_Pose_rxryrz.png', dpi=300)

    fig4 = plt.figure().gca()
    try:
        fig4.plot(r.timestamp, r.target_TCP_speed_0, color='r', label='dX')
        fig4.plot(r.timestamp, r.target_TCP_speed_1, color='g', label='dY')
        fig4.plot(r.timestamp, r.target_TCP_speed_2, color='b', label='dZ')
    except:
        print("Singular target_TCP_speed_0-2")
        #return 4
    fig4.xaxis.set_major_locator(ticker.MultipleLocator(0.50))
    fig4.xaxis.set_minor_locator(ticker.MultipleLocator(0.25))
    plt.grid(True)
    plt.title(filenameCSV + " - Pose Geschwindigkeit XYZ")
    plt.ylabel('dXYZ in m/s')
    plt.xlabel('Zeit in s')
    plt.legend()
    plt.savefig('png/' + filename + '_Pose_Geschwindigkeit_XYZ.png', dpi=300)

    fig5 = plt.figure().gca()
    try:
        fig5.plot(r.timestamp, r.target_TCP_speed_3, color='c', label='drx')
        fig5.plot(r.timestamp,
                  r.target_TCP_speed_4,
                  color='magenta',
                  label='dry')
        fig5.plot(r.timestamp,
                  r.target_TCP_speed_5,
                  color='orange',
                  label='drz')
    except:
        print("Singular target_TCP_speed_3-5")
        #return 5
    fig5.xaxis.set_major_locator(ticker.MultipleLocator(0.50))
    fig5.xaxis.set_minor_locator(ticker.MultipleLocator(0.25))
    plt.grid(True)
    plt.title(filenameCSV + " - Pose Geschwindigkeit rxryrz")
    plt.ylabel('drxryrz in Rad/s')
    plt.xlabel('Zeit in s')
    plt.legend()
    plt.savefig('png/' + filename + '_Pose_Geschwindigkeit_rxryrz.png',
                dpi=300)

    #target_TCP_acc_X
    fig6 = plt.figure().gca()
    try:
        fig6.plot(r.timestamp, r.target_TCP_acc_0, color='r', label='ddX')
        fig6.plot(r.timestamp, r.target_TCP_acc_1, color='g', label='ddY')
        fig6.plot(r.timestamp, r.target_TCP_acc_2, color='b', label='ddZ')
    except:
        print("Singular target_TCP_acc_X")
        #return 6
    fig6.xaxis.set_major_locator(ticker.MultipleLocator(0.50))
    fig6.xaxis.set_minor_locator(ticker.MultipleLocator(0.25))
    plt.grid(True)
    plt.title(filenameCSV + " - Pose Beschleunigung XYZ")
    plt.ylabel('ddXYZ in m/s**2')
    plt.xlabel('Zeit in s')
    plt.legend()
    plt.savefig('png/' + filename + '_Pose_Beschleunigung_XYZ.png', dpi=300)

    return 0
コード例 #12
0
def plot_energy_landscape(x,
                          y,
                          values,
                          log_legend=False,
                          title=None,
                          legend_title=None,
                          legend_min=0,
                          legend_max=None):
    # Clearing the canvas, so we always draw on the empty canvas. Just in case.
    plt.clf()

    x, y = preprocess(x, y)
    fig, ax = plt.subplots()
    XX, YY = np.meshgrid(x, y)
    z = values.reshape(len(x) - 1, len(y) - 1).T
    # ax.grid(True, which='minor', axis='both', linestyle='-', color='k')
    # ax.set_xticks(x, minor=True)
    # ax.set_yticks(y, minor=True)

    ## This is for having ticks in the plot as multiples of pi
    ax.xaxis.set_major_formatter(
        tck.FuncFormatter(lambda val, pos: '{:.2f}$\pi$'.format(val / np.pi)
                          if val != 0 else '0'))
    ax.xaxis.set_major_locator(tck.MultipleLocator(base=np.pi / 4))

    ax.yaxis.set_major_formatter(
        tck.FuncFormatter(lambda val, pos: '{:.2f}$\pi$'.format(val / np.pi)
                          if val != 0 else '0'))
    ax.yaxis.set_major_locator(tck.MultipleLocator(base=np.pi / 4))

    if log_legend:
        mesh_plot = ax.pcolormesh(XX,
                                  YY,
                                  z,
                                  cmap='RdBu',
                                  vmax=legend_max,
                                  norm=LogNorm())
    else:
        mesh_plot = ax.pcolormesh(XX,
                                  YY,
                                  z,
                                  cmap='RdBu',
                                  vmin=legend_min,
                                  vmax=legend_max)

    ax.set_xlabel("beta")
    ax.set_ylabel("gamma")
    if title is None:
        title = "QAOA energy landscape"
    ax.set_title(title)

    # set the limits of the plot to the limits of the data
    ax.axis([x.min(), x.max(), y.min(), y.max()])
    if log_legend:
        cbar_formatter = tck.LogFormatter(10, labelOnlyBase=False)
        cbar = fig.colorbar(mesh_plot, ax=ax, format=cbar_formatter)
    else:
        cbar = fig.colorbar(mesh_plot, ax=ax)

    if legend_title is None:
        legend_title = "energy"
    cbar.set_label(legend_title)

    plt.savefig(title)
    return ax
コード例 #13
0
xs = np.linspace(0, 2 * np.pi, 100)
xs_deg = np.linspace(0, 360, 100)
times = lambda max_t : np.linspace(0, max_t, 10 * max_t)


def exp(r, x):
    return np.exp(r * x)

rate = 0.05
grow = lambda x : exp(rate, x)

# Plotting
fontsize = 20
linewidth = 3

ticks = ticker.MultipleLocator(base = 60)

def make_plot(mode, t_max = 0):
    ts = times(t_max + 1)
    for time in ts:
        """ sin wave with frequency 'mode' """
        ys = [np.sin(mode * x - np.pi * time / 10) * grow(time) for x in xs]

        figure, ax = plot.subplots(figsize = (10, 3))

        plot.plot(xs_deg, ys, 'b', linewidth = linewidth + 1)

        # Limit
        plot.xlim(0, 360)
        plot.ylim(-8, 8)
コード例 #14
0
import chaosmagpy as cp
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import numpy as np

model = cp.CHAOS.from_mat('CHAOS-6-x9.mat')  # load the mat-file of CHAOS-6-x9

nmax = 20
time = cp.data_utils.mjd2000(2018, 1, 1)
degrees = np.arange(1, nmax + 1, dtype=int)

fig, ax = plt.subplots(1, 1, figsize=(12, 7))

for deriv, label in enumerate(['nT', 'nT/yr', 'nT/yr$^2$']):

    # get spatial power spectrum from time-dependent internal field in CHAOS
    spec = model.model_tdep.power_spectrum(time, nmax=nmax, deriv=deriv)
    ax.semilogy(degrees, spec, label=label)

ax.legend()
ax.grid(which='both')

ax.yaxis.set_major_locator(ticker.LogLocator(base=10.0, numticks=15))
ax.xaxis.set_major_locator(ticker.MultipleLocator(1))

ax.set_title("Spatial power spectra at Earth's surface", fontsize=14)
ax.set_xlabel('Spherical harmonic degree')

plt.tight_layout()
plt.show()
コード例 #15
0
    data_file.close()

    if GR_Connected == True:
        fig, ax = pl.subplots(2, 2)

        pl.suptitle("Sensor " + sensor_name + " at " + temperature + " for " +
                    annealing + "\n")

        ax[0, 0].plot(bias_voltage, avg_current, "ro")
        ax[0, 0].ticklabel_format(
            style='sci', axis='y',
            scilimits=(0, 0))  #scientific notation on the y-axis
        ax[0, 0].set_xlabel("Bias Voltage (V)")  #x label
        ax[0, 0].set_ylabel("Average Current (A)")  #y label
        ax[0, 0].xaxis.set_major_locator(
            ticker.MultipleLocator(100))  #major ticks
        ax[0,
           0].xaxis.set_minor_locator(ticker.MultipleLocator(50))  #minor ticks

        # ax1.xaxis.set_major_locator(ticker.MultipleLocator(100))#major ticks
        # 		ax1.xaxis.set_minor_locator(ticker.MultipleLocator(50))#minor ticks

        ax[0, 1].plot(bias_voltage, C_freq1, "ro")
        ax[0, 1].plot(bias_voltage, C_freq2, "bo")
        ax[0, 1].ticklabel_format(
            style='sci', axis='y',
            scilimits=(0, 0))  #scientific notation on the y-axis
        ax[0, 1].set_xlabel("Bias Voltage (V)")  #x label
        ax[0, 1].set_ylabel("Capacitance (F)")  #y label
        ax[0, 1].xaxis.set_major_locator(
            ticker.MultipleLocator(100))  #major ticks
コード例 #16
0
    # size and fixed aspect ratio
    ax.set_aspect('equal')

    ax.set_xlim(minx - ROOMBA_WIDTH, maxx + ROOMBA_WIDTH)
    ax.set_ylim(miny - ROOMBA_WIDTH, maxy + ROOMBA_WIDTH)

    # set background colors
    fig.patch.set_facecolor('#065da2')
    ax.set_facecolor('#065da2')

    # setup grid
    ax.grid(which="both", linestyle="dotted", linewidth=1, alpha=.5, zorder=5)

    # spacing 0.5m
    ax.xaxis.set_major_locator(ticker.MultipleLocator(500))
    ax.yaxis.set_major_locator(ticker.MultipleLocator(500))

    # all off
    ax.spines['top'].set_visible(False)
    ax.spines['right'].set_visible(False)
    ax.spines['bottom'].set_visible(False)
    ax.spines['left'].set_visible(False)

    plt.tick_params(top=False,
                    bottom=False,
                    left=False,
                    right=False,
                    labelleft=False,
                    labelbottom=False)
コード例 #17
0
def massfractionvtime2(datafile1,
                       datafile2,
                       end,
                       num_plots=1,
                       min_mf=.00000001,
                       time_spacing=.2,
                       h_ratio=[3, 1],
                       zz_wanted='None',
                       zz_wanted2='None',
                       aa_wanted='None',
                       nuc_names_wanted='None'):
    ''' Inputs: datafile = a ts file
        datafile2 = a second ts file to be plotted simultaneously
        end = k value at end of desired time
        num_plots = number of plots to be shown simultaneously, default to 1
        min_mf = cutoff point below which mass fraction does not appear on the graph, default to .00000001
        time_spacing = desired interval between x-axis ticks, default to .2
        h_ratio = height ratio (if plotting multiple plots), default to 3:1
        zz_wanted = list of atomic numbers of desired isotopes (if multiple isotopes of the same element are desired, their zz values must be added multiple times)
        zz_wanted2 = zz_wanted for the second datafile
        aa_wanted = list of atomic masses of desired isotopes (used in conjunction with zz_wanted)
        nuc_names_wanted = list of desired species names, formatted as '$^{aa}$Symbol' (best option when plotting specific isotopes)
        
        Outputs: plot of mass fraction vs time
        '''

    import numpy as np
    import matplotlib.pyplot as plt
    from matplotlib import colors
    import matplotlib.ticker as plticker
    import matplotlib.gridspec as gridspec
    import find_file_type as fft
    import read_ts_file as rtf
    import random

    #Create plot space
    plt.figure(1)

    #Read ts file, use variables.
    zz, aa, xmf, time, temperature, density, timestep, edot, flx_end, flx = rtf.read_ts_file(
        datafile1)
    element = rtf.build_element_symbol()
    nuc_name = rtf.build_isotope_symbol(zz, aa)

    #Create plot.
    ax1 = plt.subplot(1, 1, 1)

    #Set parameter based on data.
    num_species_total = np.shape(xmf)[1]

    #Assign each species a random color.
    colors_array = []
    for counter in np.arange(1, num_species_total + 1):
        item1 = np.random.rand(counter)[0]
        item2 = np.random.rand(counter)[0]
        item3 = np.random.rand(counter)[0]
        colors_array.append(item1)
        colors_array.append(item2)
        colors_array.append(item3)
    colors_array = np.asarray(colors_array)
    colors_array = colors_array.reshape((num_species_total, 3))

    colors = []
    for counter in np.arange(1, num_species_total + 1):
        item1 = np.random.rand(counter)[0]
        item2 = np.random.rand(counter)[0]
        item3 = np.random.rand(counter)[0]
        colors.append(item1)
        colors.append(item2)
        colors.append(item3)
    colors = np.asarray(colors)
    colors = colors.reshape((num_species_total, 3))

    #Plot mf, add a legend.
    for counter in np.arange(0, num_species_total):
        if zz_wanted != 'None':
            if zz[counter] in zz_wanted and aa_wanted == 'None':  #Plot all isotopes of an element.
                if zz[counter] == 1 and aa[
                        counter] == 1:  #Explicitly plots protons and hydrogen.
                    plt.plot(time,
                             xmf[:, counter],
                             color='r',
                             label=nuc_name[counter])
                elif zz[counter] == 1 and aa[counter] == 2:
                    plt.plot(time,
                             xmf[:, counter],
                             color='b',
                             label=nuc_name[counter])
                else:
                    plt.plot(time,
                             xmf[:, counter],
                             color=colors_array[counter],
                             label=nuc_name[counter])
                box = ax1.get_position()
                ax1.set_position(
                    [box.x0, box.y0, box.width * 0.995, box.height])
                ax1.legend(loc='center left',
                           bbox_to_anchor=(1, 0.5),
                           fontsize=10)
            elif zz[counter] in zz_wanted and aa[
                    counter] in aa_wanted:  #Plot by atomic number and mass number.
                plt.plot(time,
                         xmf[:, counter],
                         color=colors_array[counter],
                         label=nuc_name[counter])
                box = ax1.get_position()
                ax1.set_position(
                    [box.x0, box.y0, box.width * 0.995, box.height])
                ax1.legend(loc='center left',
                           bbox_to_anchor=(1, 0.5),
                           fontsize=10)
                zz_wanted.remove(zz[counter])
        elif zz_wanted == 'None' and nuc_names_wanted == 'None':  #Plot all species above specified threshold.
            if np.amax(xmf[:, counter]) >= min_mf:
                plt.plot(time, xmf[:, counter], color=colors_array[counter])
        elif nuc_names_wanted != 'None':  #Listed nuclear names switches plotting mechanism.
            break

    if nuc_names_wanted != 'None':  #Sort through list to find mass fraction of named species, and plot.
        for counter in np.arange(0, len(nuc_names_wanted)):
            species_number = nuc_name.index(nuc_names_wanted[counter])
            species_number = int(species_number)
            plt.plot(time,
                     xmf[:, species_number],
                     color=colors_array[species_number],
                     label=nuc_name[species_number])
            box = ax1.get_position()
            ax1.set_position([box.x0, box.y0, box.width * 0.995, box.height])
            ax1.legend(loc='center left', bbox_to_anchor=(1, 0.5), fontsize=10)

    #Start of datafile2.

    #Read second ts file, use variables.
    zz, aa, xmf, time, temperature, density, timestep, edot, flx_end, flx = rtf.read_ts_file(
        datafile2)
    element = rtf.build_element_symbol()
    nuc_name = rtf.build_isotope_symbol(zz, aa)

    #Set parameter based on data size.
    num_species_total = np.shape(xmf)[1]

    #Repeat plotting process above, using dashed lines and second set of provided information.
    for counter in np.arange(0, num_species_total):
        if zz_wanted2 != 'None':
            if zz[counter] in zz_wanted2 and aa_wanted == 'None':
                if zz[counter] == 1 and aa[counter] == 1:
                    plt.plot(time,
                             xmf[:, counter],
                             color='r',
                             label=nuc_name[counter],
                             linestyle='--')
                elif zz[counter] == 1 and aa[counter] == 2:
                    plt.plot(time,
                             xmf[:, counter],
                             color='b',
                             label=nuc_name[counter],
                             linestyle='--')
                else:
                    plt.plot(time,
                             xmf[:, counter],
                             color=colors_array[counter],
                             label=nuc_name[counter],
                             linestyle='--')
            elif zz[counter] in zz_wanted2 and aa[counter] in aa_wanted:
                plt.plot(time,
                         xmf[:, counter],
                         color=colors_array[counter],
                         label=nuc_name[counter],
                         linestyle='--')
                zz_wanted2.remove(zz[counter])
                aa_wanted.remove(aa[counter])
        elif zz_wanted2 == 'None' and nuc_names_wanted == 'None':
            if np.amax(xmf[:, counter]) >= min_mf:
                plt.plot(time,
                         xmf[:, counter],
                         color=colors_array[counter],
                         linestyle='--')
        elif nuc_names_wanted != 'None':
            break

    if nuc_names_wanted != 'None':
        for counter in np.arange(0, len(nuc_names_wanted)):
            species_number = nuc_name.index(nuc_names_wanted[counter])
            plt.plot(time,
                     xmf[:, species_number],
                     color=colors_array[species_number],
                     label=nuc_name[species_number],
                     linestyle='--')

    #Format and label axes
    plt.yscale('log')
    plt.ylim(min_mf, 1.5)
    plt.ylabel("Mass Fraction")

    plt.xscale('linear')
    plt.xlim(time[0], time[end])
    plt.xlabel("Time (s)")

    #Add x ticks at specified intervals
    x_labels = []
    tick = time[0]

    while tick <= time[end]:
        tick = float("{0:.1f}".format(tick))
        x_labels.append(tick)
        tick += time_spacing

    loc = plticker.MultipleLocator(base=time_spacing)
    ax1.xaxis.set_major_locator(loc)
    plt.xticks(x_labels, x_labels)

    #Remove superfluous ticks, show grid line instead
    plt.tick_params(axis='both',
                    which='both',
                    bottom='on',
                    top='on',
                    labelbottom='on',
                    left='off',
                    right='off',
                    labelleft='on')
    plt.grid(True)
    plt.title("%s (solid) and %s (dashed)" % (datafile1, datafile2))

    #Show graph
    plt.show()
コード例 #18
0
    def renderFrameBlocks(self):
        self.axFrameBlocks1.clear()
        self.axFrameBlocks2.clear()

        # after a clear() annSelection object is gone. reset variable
        self.annSelection = None

        padding = 0.0
        duration = 0.0

        cnt = len(self.jointFrames)
        if (cnt > 0):
            duration = self.jointFrames[cnt - 1]['timeS'][0]

            maxTime = (duration / 1000.0)

            def format_func(value, tick_number):
                return r"${:.2f}$".format(value)

            self.axSliderTime.set_xlim((0, maxTime))
            self.axSliderTime.tick_params(axis='x', labelsize=8)
            self.axSliderTime.get_xaxis().set_major_locator(
                ticker.AutoLocator())
            self.axSliderTime.get_xaxis().set_minor_locator(
                ticker.AutoMinorLocator())

            # show minor ticks every 5 frames and major ticks every 10 frames on the top of frame block 1
            onetick = (maxTime) / float(cnt)
            self.axFrameBlocks1.set_xlim((0, maxTime))
            self.axFrameBlocks1.xaxis.tick_top()
            self.axFrameBlocks1.xaxis.set_minor_locator(
                ticker.MultipleLocator(onetick * 5))
            self.axFrameBlocks1.xaxis.set_major_locator(
                ticker.MultipleLocator(onetick * 10))
            self.axFrameBlocks1.set_xticklabels([])
            self.axFrameBlocks1.get_yaxis().set_visible(False)

            self.axFrameBlocks2.set_xlim((0, maxTime))
            self.axFrameBlocks2.get_xaxis().set_visible(False)
            self.axFrameBlocks2.get_yaxis().set_visible(False)

        # render individual kinect joint frame blocks
        xx = self.axFrameBlocks1.get_xlim()
        yy = self.axFrameBlocks1.get_ylim()
        cx = (xx[1] - xx[0])
        cy = (yy[1] - yy[0])
        padding = cx * 0.01
        cnt = len(self.jointFrames)
        if (cnt > 0):
            padding = (cx / cnt) * 0.3
            for i in range(0, cnt):
                start = (self.jointFrames[i]['timeS'][0] / 1000.0) - (padding /
                                                                      2.0)
                x_width = padding
                isFilled = self.jointFrames[i]['filled'][0]
                c = 'r' if (isFilled) else 'b'
                p = patches.Rectangle((start, yy[0]),
                                      x_width,
                                      cy,
                                      alpha=0.50,
                                      color=c)
                self.axFrameBlocks1.add_patch(p)

        self.axFrameBlocks1.text((maxTime), (cy / 2.0),
                                 '  Original',
                                 horizontalalignment='left',
                                 verticalalignment='center',
                                 color='black')

        # render individual laban frame blocks
        xx = self.axFrameBlocks2.get_xlim()
        yy = self.axFrameBlocks2.get_ylim()
        cx = (xx[1] - xx[0])
        cy = (yy[1] - yy[0])
        cnt = len(self.timeS)
        if (cnt > 0):
            for i in range(0, cnt):
                start = (self.timeS[i] / 1000.0) - (padding / 2.0)
                x_width = padding
                p = patches.Rectangle((start, yy[0]),
                                      x_width,
                                      cy,
                                      alpha=0.50,
                                      color='g')
                self.axFrameBlocks2.add_patch(p)

        self.axFrameBlocks2.text((maxTime), (cy / 2.0),
                                 '  Labanotation',
                                 horizontalalignment='left',
                                 verticalalignment='center',
                                 color='black')

        self.fig.canvas.draw_idle()
コード例 #19
0
ファイル: 4.py プロジェクト: bulinayas/lab3
data = np.loadtxt("points.txt")
p = int(input("Введите степень полинома: "))
n = len(data)

x = np.arange(data[0][0] - 2, data[n - 1][0] + 2, 0.1)
y = polinom(p, n, x, *data)

xmin = data[0][0] - 2
xmax = data[n - 1][0] + 2
ymin = data[0][1] - 15
ymax = data[n - 1][1] + 10

fig, ax = plt.subplots()

ax.axis([xmin, xmax, ymin, ymax])
ax.xaxis.set_major_locator(ticker.MultipleLocator(10))
ax.xaxis.set_minor_locator(ticker.MultipleLocator(5))
ax.yaxis.set_major_locator(ticker.MultipleLocator(5))
ax.yaxis.set_minor_locator(ticker.MultipleLocator(1))

ax.scatter(data[:, 0], data[:, 1], c='deeppink')
ax.plot(x, y, color='r', linewidth=3)

ax.grid(which='major', color='k')

ax.minorticks_on()

ax.grid(which='minor', color='gray', linestyle=':')

fig.set_figwidth(8)
fig.set_figheight(5)
コード例 #20
0
def data_summary_vis(scrna_fname, dlp_fname, ifmpif_fname, wgs_fname,
                     storage_filename, plot_file_name):
    scrna_file = import_scrna_from_github(scrna_fname)
    dlp_file = import_dlp_from_github(dlp_fname)
    if_file = import_ifmpif_from_github(ifmpif_fname)
    wgs_file = import_wgs_from_github(wgs_fname)

    # import elab pull and filter for storage aliquots from patients included in study
    storage_aliquots = pd.read_excel(storage_filename)
    filtered_aliquots = storage_aliquots.loc[
        (storage_aliquots['Excluded'] == "No")
        & (storage_aliquots['Downstream Submission'] == "Storage Only")]
    pt_id_aliquots = filtered_aliquots["Patient ID"].drop_duplicates()
    patients = pt_id_aliquots.tolist()

    all_data_files = pd.concat([scrna_file, dlp_file, if_file, wgs_file],
                               axis=0,
                               sort=True)
    all_data_files = all_data_files[["Platform", "Patient ID"]]

    data_dict = {}
    for i in all_data_files["Platform"].tolist():
        data_dict[i] = all_data_files[all_data_files["Platform"] ==
                                      i]["Patient ID"].tolist()

    platforms = []
    matrix = []

    #identify matrix size (x and y length)
    for key, value in sorted(data_dict.items()):
        platforms.append(key)
        for patient in value:
            if patient not in patients:
                patients.append(patient)
    patients.sort()

    #create matrix from key value pairs
    currentPlatform = 0
    for key, value in sorted(data_dict.items()):
        matrix.append([])
        # initialize each matrix row to 0
        matrix[currentPlatform] = [0] * len(patients)
        for patient in value:
            patientIndex = patients.index(patient)
            matrix[currentPlatform][patientIndex] = 1
        currentPlatform += 1

    patients = [patient.lstrip("SPECTRUM-") for patient in patients]
    print(patients)

    # plot matrix
    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.matshow(matrix, cmap=plt.cm.Blues)

    plt.title('SPECTRUM Data Summary', weight='bold', fontsize=8)
    plt.xlabel('Patients wtih scs Stored', fontsize=4, weight='bold')
    plt.ylabel('Platforms', rotation='vertical', fontsize=4, weight='bold')

    ax.set_xticklabels([''] + patients,
                       rotation='vertical',
                       fontsize=3,
                       ha="center")
    ax.set_yticklabels([''] + platforms, fontsize=3)
    ax.xaxis.set_major_locator(ticker.MultipleLocator(1))
    ax.yaxis.set_major_locator(ticker.MultipleLocator(1))
    plt.gca().xaxis.tick_bottom()

    ax.set_xticks(np.arange(-.5, len(patients)), minor=True)
    ax.set_yticks(np.arange(-.5, len(platforms)), minor=True)
    ax.grid(which="minor", linewidth=0.5, alpha=0.5)

    plt.tight_layout()
    plt.savefig(fname=plot_file_name, dpi=300)
コード例 #21
0
    errs_aper[j] = np.std((cat['mag_input'] - cat['mag_aper'])[inds])
    errs_err_aper[j] = calc_std_err((cat['mag_input'] - cat['mag_aper'])[inds])

# second plot
pyplot.subplot(2, 1, 2)
m = ns > 3
pyplot.errorbar(hist.locations[m],
                errs[m],
                errs_err[m],
                fmt='o',
                color='black')
pyplot.errorbar(hist.locations[m],
                errs_aper[m],
                errs_err_aper[m],
                fmt='o',
                color='black',
                mfc='white')
pyplot.axis([xmin, xmax, 0, 0.75])
pyplot.ylabel('$\sigma$Mag')
axis = pyplot.axis()
pyplot.gca().xaxis.set_major_locator(ticker.MultipleLocator(2))
pyplot.xlabel('Mag In')

# plot estimated limit due to sky noise
mags = np.linspace(xmin, xmax, 1000)
fluxes = 10**(-0.4 * (mags - zpt))
errs = -2.5 * np.log10((fluxes - sky) / fluxes)
#pyplot.plot( mags, errs, 'k-' )

pyplot.gcf().set_size_inches((6, 4))
pyplot.savefig('ps/irac_sims_cut.eps')
コード例 #22
0
ファイル: DQN.py プロジェクト: CyChan811/DQN
        action_val = dqn.eval_net.forward(current_state)    #前向传播
        action = torch.max(action_val, 1)[1].data.numpy()[0]  # 选出最大值
        next_state, reward, done, _, _ = environ.run(current_state, action)
        print('current_state: {}, action: {}, next_state: {}'.format((current_state == POS_VALUE).nonzero()[0, 2:4],
                                                                     actions[action],
                                                                     (next_state == POS_VALUE).nonzero()[0, 2:4]))
        if done:
            break
        current_state = copy.deepcopy(next_state)


dqn = DQN()     # 定义 DQN 系统
start = time.clock()
train_net()     # 训练网络
test_net()      # 测试网络
elapsed = (time.clock() - start)
print("Time used:", elapsed)
fig = plt.figure(figsize = (10, 10))
plt.plot(episode_list, step_list)
plt.ylabel("step")
plt.xlabel("episode")
plt.title("DQN")
plt.ylim(0, 6000)
plt.xlim(0, 1000)
ax = plt.gca()
ax.xaxis.set_major_locator(tk.MultipleLocator(100))
ax.yaxis.set_major_locator(tk.MultipleLocator(500))
plt.show()


コード例 #23
0
def plot_community_conn_mat(conn_matrix,
                            labels,
                            out_path_fig_comm,
                            community_aff,
                            cmap,
                            dpi_resolution=300):
    """
    Plot a community-parcellated connectivity matrix.

    Parameters
    ----------
    conn_matrix : array
        NxN matrix.
    labels : list
        List of string labels corresponding to ROI nodes.
    out_path_fig_comm : str
        File path to save the community-parcellated connectivity matrix image
        as a .png figure.
    community_aff : array
        Community-affiliation vector.
    """
    import warnings
    warnings.filterwarnings("ignore")
    import matplotlib
    import mplcyberpunk
    from matplotlib import pyplot as plt
    matplotlib.use("agg")
    plt.style.use("cyberpunk")
    import matplotlib.patches as patches
    import matplotlib.ticker as mticker
    from nilearn.plotting import plot_matrix
    from pynets.core import thresholding

    plt.style.use("cyberpunk")

    conn_matrix_bin = thresholding.binarize(conn_matrix)
    conn_matrix = thresholding.standardize(conn_matrix)
    conn_matrix_plt = np.nan_to_num(np.multiply(conn_matrix, conn_matrix_bin))

    sorting_array = sorted(range(len(community_aff)),
                           key=lambda k: community_aff[k])
    sorted_conn_matrix = conn_matrix[sorting_array, :]
    sorted_conn_matrix = sorted_conn_matrix[:, sorting_array]
    rois_num = sorted_conn_matrix.shape[0]
    if rois_num < 100:
        try:
            plot_matrix(
                conn_matrix_plt,
                figure=(10, 10),
                labels=labels,
                vmax=np.percentile(conn_matrix_plt[conn_matrix_plt > 0], 95),
                vmin=0,
                reorder=False,
                auto_fit=True,
                grid=False,
                colorbar=False,
                cmap=cmap,
            )
        except RuntimeWarning:
            print("Connectivity matrix too sparse for plotting...")
    else:
        try:
            plot_matrix(
                conn_matrix_plt,
                figure=(10, 10),
                vmax=np.abs(np.max(conn_matrix_plt)),
                vmin=0,
                auto_fit=True,
                grid=False,
                colorbar=False,
                cmap=cmap,
            )
        except RuntimeWarning:
            print("Connectivity matrix too sparse for plotting...")

    ax = plt.gca()
    total_size = 0
    for community in np.unique(community_aff):
        size = sum(sorted(community_aff) == community)
        ax.add_patch(
            patches.Rectangle(
                (total_size, total_size),
                size,
                size,
                fill=False,
                edgecolor="white",
                alpha=None,
                linewidth=1,
            ))
        total_size += size

    if len(labels) > 500:
        tick_interval = 5
    elif len(labels) > 100:
        tick_interval = 4
    elif len(labels) > 50:
        tick_interval = 2
    else:
        tick_interval = 1

    plt.axes().yaxis.set_major_locator(mticker.MultipleLocator(tick_interval))
    plt.axes().xaxis.set_major_locator(mticker.MultipleLocator(tick_interval))
    for param in ['figure.facecolor', 'axes.facecolor', 'savefig.facecolor']:
        plt.rcParams[param] = '#000000'
    plt.savefig(out_path_fig_comm, dpi=dpi_resolution)
    plt.close()
    return
コード例 #24
0
def set_y_major(base):
    loc = plticker.MultipleLocator(
        base=base)  # this locator puts ticks at regular intervals
    plt.gca().yaxis.set_major_locator(loc)
コード例 #25
0
ファイル: effect-cluster.py プロジェクト: mac389/phikal
    for label, shape in zip(np.unique(labels), ['o', 's', '*', 'x', 'D'])
}

fig, axs = plt.subplots(ncols=2, sharex=True, sharey=True)
#display pcs on left
axs[0].scatter(X[:, 0],
               X[:, 1],
               c=X[:, 2],
               cmap=plt.cm.seismic,
               alpha=0.8,
               clip_on=False)
artist.adjust_spines(axs[0])
axs[0].set_xlabel(artist.format('PC 1'))
axs[0].set_ylabel(artist.format('PC 2'))
axs[0].set_aspect('equal')
loc = plticker.MultipleLocator(base=1.0)
axs[0].xaxis.set_major_locator(loc)
axs[0].yaxis.set_major_locator(loc)

#--Print out effects in each cluster
d = {
    cluster:
    [effect for i, effect in enumerate(effects) if labels[i] == cluster]
    for cluster in np.unique(labels)
}

for i in xrange(X.shape[0]):
    axs[1].scatter(X[i, 0],
                   X[i, 1],
                   marker=shapes[labels[i]],
                   c=colors[labels[i]],
コード例 #26
0
from textblob import TextBlob
import matplotlib.pyplot as plt
import matplotlib.ticker as plticker
import time

start = time.time()
print(plt.style.available)
plt.style.use("seaborn-talk"
              )  # _classic_test, fivethirtyeight, classic, bmh, seaborn-talk

loc = plticker.MultipleLocator(base=.3)

polarity = []
subjectivity = []

lines = []
polarityEqualsZero = 0

with open("./GambinoSong.txt") as f:
    for line in f.read().split("\n"):
        if line != "" and line not in lines:
            sentiment = TextBlob(line)
            if sentiment.sentiment.polarity != 0:
                polarity.append(sentiment.sentiment.polarity)
            else:
                polarityEqualsZero += 1
                polarity.append(sentiment.sentiment.polarity)
            subjectivity.append(sentiment.subjectivity)
            lines.append(line)

コード例 #27
0
ファイル: matplotlib-6.py プロジェクト: tttienthinh/AlgoTrade
def setup(ax):
    ax.spines['right'].set_color('none')
    ax.spines['left'].set_color('none')
    ax.yaxis.set_major_locator(ticker.NullLocator())
    ax.spines['top'].set_color('none')
    ax.xaxis.set_ticks_position('bottom')
    ax.tick_params(which='major', width=1.00)
    ax.tick_params(which='major', length=5)
    ax.tick_params(which='minor', width=0.75)
    ax.tick_params(which='minor', length=2.5)
    ax.set_xlim(0, 5)
    ax.set_ylim(0, 1)
    ax.patch.set_alpha(0.0)


labels = [2, 3, 4, 5, 8, 9, 10, 11, 12, 15, 16]
seconds = [i.seconds for i in time_list]
f = plt.figure()
ax = plt.subplot(1, 1, 1)
setup(ax)
ax.bar(labels, seconds)

ax.yaxis.set_major_formatter(formatter)

# this locates y-ticks at the hours
ax.yaxis.set_major_locator(ticker.MultipleLocator(base=3600))

# this ensures each bar has a 'date' label
ax.xaxis.set_major_locator(ticker.MultipleLocator(base=1))

plt.show()
コード例 #28
0
# adding sub plot using subplot2grid
fig1 = plt.figure()
bx3 = plt.subplot2grid((6, 1), (4, 0), rowspan=2, colspan=1)
bx1 = plt.subplot2grid((6, 1), (0, 0),
                       rowspan=2,
                       colspan=1,
                       sharex=bx3,
                       sharey=bx3)
bx2 = plt.subplot2grid((6, 1), (2, 0),
                       rowspan=2,
                       colspan=1,
                       sharex=bx3,
                       sharey=bx3)

bx3.xaxis.set_major_locator(mticker.MultipleLocator(1))
## Y axis ticks are not constant, it's [0,5] or [2.5, 5, 7.5], changing this here
bx3.yaxis.set_major_locator(mticker.MultipleLocator(1))

bx3TwinX = bx3.twinx(
)  ##creates a new copy of x axis with an y axis to the other side
#with different range(default 0->1 may be) and ticks
bx3TwinX.axes.set_ylim(0, 9)  ## I need to set the y axis range explicitly
bx3TwinX.yaxis.set_major_locator(mticker.MultipleLocator(1))
## one way of changing tick size
bx1.tick_params(axis='y', labelsize=8, color='m')
bx2.tick_params(axis='y', labelsize=8, color='m')
bx3.tick_params(axis='y', labelsize=8, color='m')
bx3TwinX.tick_params(axis='y', labelsize=8, color='g')

bx1.plot(x1, y1)
コード例 #29
0
def plot_rt(result, ax, state_name, fig):
    ax.set_title(f"{state_name}")

    # Colors
    ABOVE = [1, 0, 0]
    MIDDLE = [1, 1, 1]
    BELOW = [0, 0, 0]
    cmap = ListedColormap(np.r_[np.linspace(BELOW, MIDDLE, 25),
                                np.linspace(MIDDLE, ABOVE, 25)])

    def color_mapped(y):
        return np.clip(y, .5, 1.5) - .5

    index = result['ML'].index.get_level_values('date')
    values = result['ML'].values

    # Plot dots and line
    ax.plot(index, values, c='k', zorder=1, alpha=.25)
    ax.scatter(index,
               values,
               s=40,
               lw=.5,
               c=cmap(color_mapped(values)),
               edgecolors='k',
               zorder=2)

    # Aesthetically, extrapolate credible interval by 1 day either side
    lowfn = interp1d(date2num(index),
                     result['Low'].values,
                     bounds_error=False,
                     fill_value='extrapolate')

    highfn = interp1d(date2num(index),
                      result['High'].values,
                      bounds_error=False,
                      fill_value='extrapolate')

    extended = pd.date_range(start=pd.Timestamp('2020-03-01'),
                             end=index[-1] + pd.Timedelta(days=1))

    ax.fill_between(extended,
                    lowfn(date2num(extended)),
                    highfn(date2num(extended)),
                    color='k',
                    alpha=.1,
                    lw=0,
                    zorder=3)

    ax.axhline(1.0, c='k', lw=1, label='$R_t=1.0$', alpha=.25)

    # Formatting
    ax.xaxis.set_major_locator(mdates.MonthLocator())
    ax.xaxis.set_major_formatter(mdates.DateFormatter('%b'))
    ax.xaxis.set_minor_locator(mdates.DayLocator())

    ax.yaxis.set_major_locator(ticker.MultipleLocator(1))
    ax.yaxis.set_major_formatter(ticker.StrMethodFormatter("{x:.1f}"))
    ax.yaxis.tick_right()
    ax.spines['left'].set_visible(False)
    ax.spines['bottom'].set_visible(False)
    ax.spines['right'].set_visible(False)
    ax.margins(0)
    ax.grid(which='major', axis='y', c='k', alpha=.1, zorder=-2)
    ax.margins(0)
    ax.set_ylim(0.0, 3.5)
    ax.set_xlim(
        pd.Timestamp('2020-03-01'),
        result.index.get_level_values('date')[-1] + pd.Timedelta(days=1))
    fig.set_facecolor('w')
コード例 #30
0
    def plot(self, *args, **kwargs):
        ps = self.env.ps
        myc = self._get_class_config()
        iter_list = self.config['iter_list']
        l, b, r, t = myc['bbox_rect']
        drange = [[20, 160], [-.5, 1.2]]

        gammaF_all = np.empty(0)
        gridness_all = np.empty(0)

        # Separate noise sigmas
        for ns_idx, noise_sigma in enumerate(ps.noise_sigmas):
            if ns_idx == 0:
                mi_title = 'Gamma frequency vs. gridness score'
            else:
                mi_title = None

            gammaFData = aggr.GammaAggregateData('freq',
                                                 ps.bumpGamma[ns_idx],
                                                 iter_list,
                                                 normalizeTicks=False,
                                                 collapseTrials=True)
            gridnessData = aggr.GridnessScore(ps.grids[ns_idx],
                                              iter_list,
                                              normalizeTicks=False,
                                              collapseTrials=True)

            gammaFData, _, _ = gammaFData.getData()
            gridnessData, _, _ = gridnessData.getData()
            gammaF_all = np.hstack((gammaF_all, gammaFData.flatten()))
            gridness_all = np.hstack((gridness_all, gridnessData.flatten()))

            # Gamma frequency vs. gridness score
            fig = self._get_final_fig(myc['fig_size'])
            ax = fig.add_axes(Bbox.from_extents(l, b, r, t))
            self.plotDistribution(gammaFData,
                                  gridnessData,
                                  ax,
                                  noise_sigma=noise_sigma,
                                  range=drange,
                                  xlabel='Gridness score',
                                  ylabel='',
                                  yticks=False,
                                  title_size=self.myc['title_size'])
            ax.axis('tight')
            ax.xaxis.set_major_locator(ti.MultipleLocator(0.5))
            if 'strip_axis' in self.myc and self.myc['strip_axis']:
                ax.axis('off')
            fname = self.config[
                'output_dir'] + "/gammaFreq_gridness_probability_{0}.pdf"
            fig.savefig(fname.format(int(noise_sigma)),
                        dpi=300,
                        transparent=True)
            plt.close(fig)

            self.mutual_information(gridnessData,
                                    gammaFData,
                                    noise_sigma=noise_sigma,
                                    title=mi_title)

        # All together
        fig = self._get_final_fig(myc['fig_size'])
        ax = fig.add_axes(Bbox.from_extents(l, b, r, t))
        self.plotDistribution(gammaF_all,
                              gridness_all,
                              ax,
                              xlabel='Gridness score',
                              ylabel='Oscillation frequency (Hz)',
                              range=drange,
                              title_size=self.myc['title_size'])
        ax.axis('tight')
        ax.xaxis.set_major_locator(ti.MultipleLocator(0.5))
        if 'strip_axis' in self.myc and self.myc['strip_axis']:
            ax.axis('off')
        fname = self.config[
            'output_dir'] + "/gammaFreq_gridness_probability_all.pdf"
        fig.savefig(fname, dpi=300, transparent=True)
        plt.close(fig)

        self.mutual_information(gammaF_all, gridness_all)