コード例 #1
0
    def displayPreview(self, img, v, i):
        def handle_close(evt, self):
            self.__previewFigure = None
            self.__previewAxes = [None, None]

        if self.__previewFigure is None:  #preview window is not created yet, lets make it
            plt.ioff()
            self.__previewFigure, self.__previewAxes[0] = plt.subplots()
            divider = make_axes_locatable(self.__previewAxes[0])
            self.__previewAxes[1] = divider.append_axes('right',
                                                        size='5%',
                                                        pad=0.05)
            self.__previewFigure.canvas.mpl_connect(
                'close_event', lambda x: handle_close(x, self)
            )  # if preview figure is closed, lets clear the figure/axes handles so the next preview properly recreates the handles
            plt.ion()
            plt.show()

        for ax in self.__previewAxes:  #clear the axes
            ax.clear()
        img_handle = self.__previewAxes[0].imshow(img)
        self.__previewFigure.colorbar(img_handle, cax=self.__previewAxes[1])
        self.__previewAxes[0].set_title('{0} V, {1} A, {2} Laser'.format(
            v, i, self.laserpower))
        self.__previewFigure.canvas.draw()
        self.__previewFigure.canvas.flush_events()
        time.sleep(
            1e-4)  #pause allows plot to update during series of measurements
コード例 #2
0
ファイル: mike.py プロジェクト: merlin-neurotech/Backend
def live_plotter(x_vec, y1_data, line1, identifier='', pause_time=0.1):
    if line1 == []:
        # this is the call to matplotlib that allows dynamic plotting
        plt.ion()
        fig = plt.figure(figsize=(13, 6))
        ax = fig.add_subplot(111)
        # create a variable for the line so we can later update it
        line1, = ax.plot(x_vec, y1_data, '-o', alpha=0.8)
        #update plot label/title
        plt.ylabel('Y Label')
        plt.title('Title: {}'.format(identifier))
        plt.show()

    # after the figure, axis, and line are created, we only need to update the y-data
    line1.set_ydata(y1_data)
    # adjust limits if new data goes beyond bounds
    if np.min(y1_data) <= line1.axes.get_ylim()[0] or np.max(
            y1_data) >= line1.axes.get_ylim()[1]:
        plt.ylim([
            np.min(y1_data) - np.std(y1_data),
            np.max(y1_data) + np.std(y1_data)
        ])
    # this pauses the data so the figure/axis can catch up - the amount of pause can be altered above
    plt.pause(pause_time)

    # return line so we can update it again in the next iteration
    return line1
コード例 #3
0
            def plottrace(self, point):
                # 使用matplotlib之pyplot绘制船舶轨迹
                # point = 38
                def initial(ax):
                    ax.axis("equal")  #设置图像显示的时候XY轴比例
                    ax.set_xlabel('Horizontal Position')
                    ax.set_ylabel('Vertical Position')
                    ax.set_title('Vessel trajectory')
                    plt.grid(True)  #添加网格
                    return ax

                es_time = np.zeros([point])
                fig = plt.figure()
                ax = fig.add_subplot(1, 1, 1)
                ax = initial(ax)

                # test
                ax2 = fig.add_subplot(1, 1, 1)
                ax2 = initial(ax2)

                plt.ion()  #interactive mode on 动态绘制

                # IniObsX=0000
                # IniObsY=4000
                # IniObsAngle=135
                # IniObsSpeed=10*math.sqrt(2)   #米/秒
                # print('开始仿真')
                obsX = []
                obsX2 = []
                # obsY = [4000,]
                obsY = []
                obsY2 = []
                for t in range(point):
                    # t0 = time.time()
                    #障碍物船只轨迹
                    # obsX.append(IniObsX+IniObsSpeed*math.sin(IniObsAngle/180*math.pi)*t)
                    obsX.append(sim_res.SHIP1POS[t][0])
                    obsX2.append(sim_res.SHIP2POS[t][0])
                    # obsY.append(IniObsY+IniObsSpeed*math.cos(IniObsAngle/180*math.pi)*t)
                    obsY.append(sim_res.SHIP1POS[t][1])
                    obsY2.append(sim_res.SHIP2POS[t][1])
                    plt.cla()
                    ax = initial(ax)
                    ax.plot(obsX, obsY, '-g', marker='*')  #散点图

                    # test
                    ax2 = initial(ax2)
                    ax2.plot(obsX2, obsY2, '-r', marker='o')
                    risk_value_text = 'Risk value: ' + str(
                        sim_res.RISKVALUE[t])
                    plt.text(0, 7, risk_value_text)
                    plt.pause(0.5)
                    # es_time[t] = 1000*(time.time() - t0)
                plt.pause(0)
                # return es_time
                pass
コード例 #4
0
    def recieve(self):
        plt.ion()
        while 1:
            if self.stat:
                addr = self.lineEdit.text()
                port = self.lineEdit_2.text()
                response = requests.get('http://' + addr + ':' + port +
                                        '/get_data')
                if response.status_code == 200:
                    self.df = pd.DataFrame.from_dict(response.json())
                    self.label_3.setText('Подключенных устройств: ' +
                                         str(len(self.df.index)))
                    print('\n')
                    print(
                        str(datetime.datetime.now().strftime(
                            '%Y/%m/%d %H:%M:%S')))
                    print(self.df)
                    if self.tableWidget.rowCount() < self.df.shape[0]:
                        self.tableWidget.setRowCount(self.df.shape[0])
                    for i in range(0, self.df.shape[0]):
                        for i2 in range(0, 4):
                            self.tableWidget.setItem(
                                i, i2,
                                QTableWidgetItem(str(self.df.iloc[i, i2])))
                    self.tableWidget.reset()
                    self.textBrowser_2.append(
                        str(datetime.datetime.now().strftime(
                            '%Y/%m/%d %H:%M:%S')) + '\n' +
                        self.df.to_string() + '\n')

                    self.d1.append(int(self.df.iloc[0][3]))
                    self.d2.append(int(self.df.iloc[1][3]))
                    drawnow(self.makeFig, stop_on_close=True)
                    plt.pause(.000001)
                    self.counter += 1
                    if self.counter > 50:
                        self.d1.pop(0)
                        self.d2.pop(0)
            else:
                return 0
            time.sleep(0.4)
コード例 #5
0
def main():
    df1_even = pd.read_csv('./adv_results/even_batch_end_400.csv', index_col=0)
    df1_odd = pd.read_csv('./adv_results/odd_batch_end_400.csv', index_col=0)
    df = df1_odd.append(df1_even)
    ## delete the following line if needed:
    #    df = df1_even
    df = df.reset_index(drop=True)

    cut = 0.3
    df_cut = df.loc[df['decision_value'] >= cut]
    df_cut = df_cut.reset_index(drop=True)

    # Initialise plot stuff
    plt.ion()
    plt.clf()
    plot_range = (0, 600)
    plot_data = []
    plot_weights = []
    plot_colors = []
    plt.rc('font', weight='bold')
    plt.rc('xtick.major', size=5, pad=7)
    plt.rc('xtick', labelsize=10)

    plotmBB(df, df_cut)
コード例 #6
0
#import numpy as np
import matplotlib as plt
from drawnow import *
from array import array

# Define var/const
menu_actions = {}  # global values for Menu routines
app_title = "*** R E A D  S E N S O R D A T A ***"
runMode = False  # keeps Main running in infinite loop, False until settings OK
global BAUD
BAUD = 0  # default baudrate = 19200, set in Menu
global COM_port
COM_port = 'NOT SET'  # serial port
global DEBUG  # for check during development
DEBUG = True
plt.ion()  #Plot live data
global cnt
cnt = 0  # counter in plot function
temp_c = []  # holds serial data to plot

PORT = 20000  # TCP
HOST = ''
sel = selectz.Selector()  # TCP
tcp_mode = False

# =======================
#     TCP options
# =======================
retval = input("Do You want to connect to TCP ? Y/N  >>")
if retval == 'Y' or retval == 'y':
    tcp_mode = True
コード例 #7
0
def main(args):
    usage = """Dewarp a set of points according to MFSF estimation

	Ben Lansdell
	5/25/2017
	"""
    #Test code:
    ion()

    class Args:
        pass

    args = Args()
    #Format: ID, frame, x, y
    #args.pts = './tracks/20160412/20160412_dupreannotation_stk0001.csv'
    #args.output = './tracks/20160412/20160412_dupreannotation_stk0001_dewarp.csv'

    args.pts = './tracks/20160412/detections.csv'
    args.output = './tracks/20160412/detections_dewarp.csv'

    args.name = 'stack0001_nref100_nframe250'
    args.mfsf_dir = './mfsf_output'

    #Load points
    f_in = open(args.pts, 'r')
    title = '\n'
    pts = []
    for idx, line in enumerate(f_in):
        if idx > 0:
            pt = [int(a) for a in line.split(',')]
            pts.append(pt)
        else:
            title = line
    pts = np.array(pts)

    f_in.close()

    #Load MFSF data
    fn_in = '%s/%s/result.mat' % (args.mfsf_dir, args.name)
    try:
        a = loadmat(fn_in)
        params = a['parmsOF']
        u1 = a['u']
        v1 = a['v']
    except NotImplementedError:
        print "Failed to read using loadmat, using hdf5 library to read %s" % fn_in
        f = h5py.File(fn_in, 'r')
        #Note the x and y axes may need to be switched here...
        u1 = np.transpose(np.array(f.get('u')), (1, 2, 0))
        v1 = np.transpose(np.array(f.get('v')), (1, 2, 0))

    nF = min(u1.shape[2], max(pts[:, 2]))

    #Create Warper
    u = u1[:, :, 0]
    v = v1[:, :, 0]
    warper = Warper(u[:, :, np.newaxis], v[:, :, np.newaxis])
    frame = 0
    frame_pts = pts[pts[:, 2] == frame, 5:7]
    _ = warper.run(frame_pts)

    warped_pts = np.zeros((0, 4))
    #For each frame, update warping object and dewarp points
    for frame in range(nF):
        print "Dewarping points in frame %d" % frame
        frame_pts = pts[pts[:, 2] == frame, 5:7]
        frame_pts = np.fliplr(frame_pts)
        nC = frame_pts.shape[0]
        u = u1[:, :, frame]
        v = v1[:, :, frame]
        warper.update_flow(u[:, :, np.newaxis], v[:, :, np.newaxis])
        warped_pt = warper.run(frame_pts)
        pts[pts[:, 2] == frame, 5:7] = warped_pt
        pts[pts[:, 2] == frame, 0:2] = warped_pt / 2

    #Save as new CSV
    np.savetxt(args.output, pts, delimiter=",", header=title, fmt='%d')
    orig_pts = np.loadtxt(args.pts, delimiter=",", skiprows=1)
    #pts = np.loadtxt(args.output, delimiter=",")

    #Plot the dewarped points to check they look right
    #Plot a bunch of frames
    f, (ax1, ax2) = pyplot.subplots(1, 2, sharey=True)

    for frm in range(nF):
        ax1.cla()
        ax2.cla()
        ax1.set_title('Frame %d. Transformed data' % frm)
        ax2.set_title('Original data')
        ax1.plot(pts[pts[:, 2] == frm, 5], pts[pts[:, 2] == frm, 6], '.')
        ax2.plot(orig_pts[orig_pts[:, 2] == frm, 5],
                 orig_pts[orig_pts[:, 2] == frm, 6], '.')
        pyplot.draw()
        pause(0.5)
コード例 #8
0
ファイル: robot.py プロジェクト: johnolamide/qzadok-robot
# Instantiate the Arduino Microcontroller
with serial.Serial() as arduino:
    arduino.port = 'COM7'
    arduino.baudrate = 9600

st.set_page_config(layout="wide")

status_bar = st.empty()
motor_speed_info = st.empty()
data_visual = st.empty()
data_table = st.empty()

Left_Speed = []
Right_Speed = []
plt.ion()  # activate matplotlib interactive mode


def plot_graph(Left_Speed, Right_Speed):
    left_speed = np.array(Left_Speed)
    right_speed = np.array(Right_Speed)
    data = np.array([left_speed, right_speed]).reshape(-1, 2)
    # if (cnt > 50):
    #     Left_Speed.pop(0)
    #     Right_Speed.pop(0)
    df = pd.DataFrame(data, columns=["Left Speed", "Right Speed"])
    # st.line_chart(df)


def createPlot():
    plt.title("Robot Speed")
コード例 #9
0
ファイル: testplot.py プロジェクト: UsoEwin/csfet
import numpy as np
import matplotlib as plt
import time
plt.axis([0, 10, 0, 1])
plt.ion()

for i in range(10):
    y = np.random.random()
    plt.scatter(i, y)
    plt.pause(0.05)
    time.sleep(1)


    
コード例 #10
0
def main():

    print("Waiting for camera Initialization...")
    cam = cv2.VideoCapture(0, cv2.CAP_DSHOW)
    if cam.isOpened():
        print("Camera Initialized!")

    # Initialize NN forward prop.
    vgg = models.vgg16(pretrained=True)
    data_transform = transforms.Compose([
        transforms.CenterCrop(154),
        transforms.ToTensor(),
        transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
    ])
    avgpool = nn.AdaptiveAvgPool2d((7, 7))
    lstm_model = lstmModel(1024 * 7 * 7, 2048, 7)
    lstm_model_path = 'state.pt'
    lstm_model.load_state_dict(torch.load(lstm_model_path,
                                          torch.device('cpu')))
    classes = [
        'No Pancake', 'Raw', 'Ready to Flip', 'Bottom Up', 'Ready to Remove',
        'Burnt', 'Obstruction'
    ]

    # ite = 0
    rgb_img, tmp_dat = read_cameras(cam)
    # ite += 1

    rgb_dim, rgb_minmax = sample_img_dim(rgb_img)
    tmp_dim, tmp_minmax = sample_img_dim(tmp_dat)
    plt.close('all')
    plt.pause(0.1)

    feature_queue = []

    # Display Image
    fig, axs = plt.subplots(1, 2)

    axs[0].set_title("RGB Image")
    ax0 = axs[0].imshow(np.zeros((154, 154, 3)))

    axs[1].set_title("Temperature Image")
    ax1 = axs[1].imshow(np.zeros((154, 154, 3)))
    fig.suptitle("Undefined")

    plt.ion()

    while True:
        # Capture Image
        rgb_img, tmp_dat = read_cameras(cam)
        # ite += 1

        # Crop Image
        rgb_cropped = crop_and_resize_image(rgb_img, rgb_minmax, rgb_dim, RES)
        #print(rgb_cropped.shape)
        tmp_cropped = crop_and_resize_data(tmp_dat, tmp_minmax)
        #print(tmp_cropped.shape)
        # print(rgb_cropped)
        # print(tmp_cropped)

        # Feed Forward
        # Transform images
        rgb_cropped_show = Image.fromarray(rgb_cropped.astype(np.uint8))
        print(rgb_cropped_show)
        tmp_cropped_show = Image.fromarray(tmp_cropped.astype(
            np.uint8)).convert('RGB')
        print(tmp_cropped_show)
        rgb_cropped = data_transform(rgb_cropped_show)
        tmp_cropped = data_transform(tmp_cropped_show)

        # Add 4th dimension
        rgb_cropped = torch.Tensor(rgb_cropped).unsqueeze(0)
        tmp_cropped = torch.Tensor(tmp_cropped).unsqueeze(0)

        rgb_feature = vgg.features(rgb_cropped)
        tmp_feature = vgg.features(tmp_cropped)

        # Concatenate features
        rgb_feature_tensor = torch.from_numpy(rgb_feature.detach().numpy())
        tmp_feature_tensor = torch.from_numpy(tmp_feature.detach().numpy())
        rgb_tmp_combined_tensor = torch.cat(
            (rgb_feature_tensor, tmp_feature_tensor), dim=1)
        rgb_tmp_combined_tensor = avgpool(rgb_tmp_combined_tensor)
        rgb_tmp_combined_tensor = torch.flatten(rgb_tmp_combined_tensor)

        # Maintain Feature Queue
        feature_queue.append(rgb_tmp_combined_tensor.detach().numpy())
        if len(feature_queue) < 8:
            continue

        feature_input_tensor = torch.Tensor(np.array(feature_queue, ndmin=3))
        outputs = lstm_model(feature_input_tensor)
        # print(outputs)
        predicted_class = outputs.detach().numpy().argmax()
        print(classes[predicted_class])
        feature_queue.pop(0)

        #axs[0].set_title("RGB Image")
        ax0.set_data(rgb_cropped_show)

        #axs[1].set_title("Temperature Image")
        ax1.set_data(tmp_cropped_show)
        # plt.show()
        fig.suptitle(classes[predicted_class])
        plt.pause(0.01)

    plt.ioff()
    plt.show()
    cam.release()
    cv2.destroyAllWindows()
コード例 #11
0
def plotmBB(df, df_cut):

    bins = np.linspace(0, 500, 51)

    # Initialise plot stuff
    plt.ion()
    plt.clf()
    plot_range = (0, 500)
    plot_data = []
    plot_weights = []
    plot_colors = []
    plt.rc('font', weight='bold')
    plt.rc('xtick.major', size=5, pad=7)
    plt.rc('xtick', labelsize=10)

    plt.rcParams["font.weight"] = "bold"
    plt.rcParams["axes.labelweight"] = "bold"
    plt.rcParams["mathtext.default"] = "regular"

    df_signal = df.loc[df['Class'] == 1.0]
    df_background = df.loc[df['Class'] == 0.0]

    df_signal_cut = df_cut.loc[df_cut['Class'] == 1.0]
    df_background_cut = df_cut.loc[df_cut['Class'] == 0.0]

    plot_weights_signal = df_signal['post_fit_weight']
    plot_weights_signal = (1 / sum(plot_weights_signal)) * plot_weights_signal
    plot_weights_signal_cut = df_signal_cut['post_fit_weight']
    plot_weights_signal_cut = (
        1 / sum(plot_weights_signal_cut)) * plot_weights_signal_cut

    plot_weights_background = df_background['post_fit_weight']
    plot_weights_background = (
        1 / sum(plot_weights_background)) * plot_weights_background
    plot_weights_background_cut = df_background_cut['post_fit_weight']
    plot_weights_background_cut = (
        1 / sum(plot_weights_background_cut)) * plot_weights_background_cut

    mbb_vals = df['mBB'].tolist()
    for i in range(len(df)):
        if mbb_vals[i] >= 500000:
            mbb_vals[i] = 499500

    df['mBB'] = mbb_vals

    mbb_vals_cut = df_cut['mBB'].tolist()
    for i in range(len(df_cut)):
        if mbb_vals_cut[i] >= 500000:
            mbb_vals_cut[i] = 499500

    df_cut['mBB'] = mbb_vals_cut

    variable_values_signal = df_signal['mBB'] / 1000
    variable_values_background = df_background['mBB'] / 1000
    variable_values_signal_cut = df_signal_cut['mBB'] / 1000
    variable_values_background_cut = df_background_cut['mBB'] / 1000

    if True == False:
        count_sig_cut = plt.hist(
            variable_values_signal_cut,
            bins=bins,
            weights=plot_weights_signal_cut,
            range=plot_range,
            rwidth=1,
            color='#b32400',  #dark red
            label='Signal after cut',
            stacked=False,
            alpha=1,
            #hatch=4*'\\'
        )
    if True != False:
        count_back_cut = plt.hist(
            variable_values_background_cut,
            bins=bins,
            weights=plot_weights_background_cut,
            range=plot_range,
            rwidth=1,
            linewidth=3,
            color='#0066CC',  #dark blue
            label='Background after cut',
            alpha=1,
            #hatch=4*'//'
        )
    if True == False:
        # Plot.
        count_sig = plt.hist(
            variable_values_signal,
            bins=bins,
            weights=plot_weights_signal,
            range=plot_range,
            rwidth=1,
            histtype='step',
            linewidth=3,
            edgecolor='#FF0000',
            #edgecolor='red',
            label='Signal',
            stacked=False,
            alpha=1,
            #hatch=4*'\\'
        )
    if True != False:
        count_back = plt.hist(
            variable_values_background,
            bins=bins,
            weights=plot_weights_background,
            range=plot_range,
            rwidth=1,
            histtype='step',
            linewidth=3,
            edgecolor='#0000b3',
            #edgecolor='blue',
            label='Background',
            alpha=1,
            #hatch=4*'//'
        )

    x1, x2, y1, y2 = plt.axis()
    #plt.yscale('log', nonposy='clip')
    plt.axis((x1, x2, y1, y2 * 1.2))
    axes = plt.gca()
    axes.set_ylim([0, 0.12])
    axes.set_xlim(plot_range)
    x = [-1, -0.8, -0.6, -0.4, -0.2, 0, 0.2, 0.4, 0.6, 0.8, 1]
    #plt.xticks(x, x,fontweight = 'normal',fontsize = 16)
    y = ["10", r"10$^{2}$", r"10$^{3}$", r"10$^{4}$", r"10$^{5}$"]
    yi = [10, 100, 1000, 10000, 100000]
    #plt.yticks(yi, y,fontweight = 'normal',fontsize = 16)
    axes.yaxis.set_ticks_position('both')
    axes.yaxis.set_tick_params(which='both', direction='in')
    axes.xaxis.set_ticks_position('both')
    axes.xaxis.set_tick_params(which='both', direction='in')
    axes.xaxis.set_minor_locator(AutoMinorLocator(4))
    axes.yaxis.set_minor_locator(AutoMinorLocator(4))
    handles, labels = axes.get_legend_handles_labels()
    plt.legend(loc='upper right',
               ncol=1,
               prop={'size': 12},
               frameon=False,
               handles=handles[::-1])
    plt.ylabel('Normalised Number of Events', fontsize=16, fontweight='normal')
    axes.yaxis.set_label_coords(-0.1, 0.5)
    plt.xlabel("$m_{bb}$ [GeV]", fontsize=16, fontweight='normal')
    axes.xaxis.set_label_coords(0.89, -0.07)
    an1 = axes.annotate("ATLAS",
                        xy=(0.05, 0.91),
                        xycoords=axes.transAxes,
                        fontstyle='italic',
                        fontsize=16)

    offset_from = OffsetFrom(an1, (0, -1.4))
    an2 = axes.annotate(r'$\sqrt{s}$' + " = 13 TeV , 36.1 fb$^{-1}$",
                        xy=(0.05, 0.91),
                        xycoords=axes.transAxes,
                        textcoords=offset_from,
                        fontweight='normal',
                        fontsize=12)

    offset_from = OffsetFrom(an2, (0, -1.4))
    an3 = axes.annotate("1 lepton, " + str(nJets) + " jets, 2 b-tags",
                        xy=(0.05, 0.91),
                        xycoords=axes.transAxes,
                        textcoords=offset_from,
                        fontstyle='italic',
                        fontsize=12)

    offset_from = OffsetFrom(an3, (0, -1.6))
    an4 = axes.annotate("p$^V_T \geq$ 150 GeV",
                        xy=(0.05, 0.91),
                        xycoords=axes.transAxes,
                        textcoords=offset_from,
                        fontstyle='italic',
                        fontsize=12)
    plt.show(block=True)
コード例 #12
0
def final_decision_plot(df,
                        figureName,
                        z_s=10,
                        z_b=10,
                        show=False,
                        block=False,
                        trafoD_bins=True,
                        bin_number=15):
    """Plots histogram decision score output of classifier"""

    nJets = df['nJ'].tolist()[1]

    if trafoD_bins == True:
        bins, arg2, arg3 = trafoD_with_error(df)
        print(len(bins))
    else:
        bins = np.linspace(-1, 1, bin_number + 1)

    # Initialise plot stuff
    plt.ion()
    plt.close("all")
    fig = plt.figure(figsize=(8.5, 7))
    plot_range = (-1, 1)
    plot_data = []
    plot_weights = []
    plot_colors = []
    plt.rc('font', weight='bold')
    plt.rc('xtick.major', size=5, pad=7)
    plt.rc('xtick', labelsize=10)

    plt.rcParams["font.weight"] = "bold"
    plt.rcParams["axes.labelweight"] = "bold"
    plt.rcParams["mathtext.default"] = "regular"

    df = setBinCategory(df, bins)

    bins = np.linspace(-1, 1, len(bins))

    decision_value_list = df['bin_scaled'].tolist()
    post_fit_weight_list = df['post_fit_weight'].tolist()
    sample_list = df['sample'].tolist()

    # Get list of hists.
    for t in class_names_grouped[::-1]:
        class_names = class_names_map[t]
        class_decision_vals = []
        plot_weight_vals = []
        for c in class_names:
            for x in range(0, len(decision_value_list)):
                if sample_list[x] == c:
                    class_decision_vals.append(decision_value_list[x])
                    plot_weight_vals.append(post_fit_weight_list[x])

        plot_data.append(class_decision_vals)
        plot_weights.append(plot_weight_vals)
        plot_colors.append(colour_map[t])

    # Plot.
    if nJets == 2:

        multiplier = 20
    elif nJets == 3:
        multiplier = 100

    plt.plot([], [],
             color='#FF0000',
             label=r'VH $\rightarrow$ Vbb x ' + str(multiplier))

    plt.hist(plot_data,
             bins=bins,
             weights=plot_weights,
             range=plot_range,
             rwidth=1,
             color=plot_colors,
             label=legend_names[::-1],
             stacked=True,
             edgecolor='none')

    df_sig = df.loc[df['Class'] == 1]

    plt.hist(df_sig['bin_scaled'].tolist(),
             bins=bins,
             weights=(df_sig['post_fit_weight'] * multiplier).tolist(),
             range=plot_range,
             rwidth=1,
             histtype='step',
             linewidth=2,
             color='#FF0000',
             edgecolor='#FF0000')

    x1, x2, y1, y2 = plt.axis()
    plt.yscale('log', nonposy='clip')
    plt.axis((x1, x2, y1, y2 * 1.2))
    axes = plt.gca()
    axes.set_ylim([5, 135000])
    axes.set_xlim([-1, 1])
    x = [-1, -0.8, -0.6, -0.4, -0.2, 0, 0.2, 0.4, 0.6, 0.8, 1]
    plt.xticks(x, x, fontweight='normal', fontsize=20)
    y = [r"10", r"10$^{2}$", r"10$^{3}$", r"10$^{4}$", r"10$^{5}$"]
    yi = [10, 100, 1000, 10000, 100000]
    plt.yticks(yi, y, fontweight='normal', fontsize=20)

    axes.yaxis.set_ticks_position('both')
    axes.yaxis.set_tick_params(which='major',
                               direction='in',
                               length=10,
                               width=1)
    axes.yaxis.set_tick_params(which='minor',
                               direction='in',
                               length=5,
                               width=1)

    axes.xaxis.set_ticks_position('both')
    axes.xaxis.set_tick_params(which='major',
                               direction='in',
                               length=10,
                               width=1)
    axes.xaxis.set_tick_params(which='minor',
                               direction='in',
                               length=5,
                               width=1)

    axes.xaxis.set_minor_locator(AutoMinorLocator(4))
    handles, labels = axes.get_legend_handles_labels()

    #Weird hack thing to get legend entries in correct order
    handles = handles[::-1]
    handles = handles + handles
    handles = handles[1:12]

    plt.legend(loc='upper right',
               ncol=1,
               prop={'size': 12},
               frameon=False,
               handles=handles)

    plt.ylabel("Events", fontsize=20, fontweight='normal')
    axes.yaxis.set_label_coords(-0.07, 0.93)
    plt.xlabel(r"BDT$_{VH}$ output", fontsize=20, fontweight='normal')
    axes.xaxis.set_label_coords(0.89, -0.07)
    an1 = axes.annotate("ATLAS Internal",
                        xy=(0.05, 0.91),
                        xycoords=axes.transAxes,
                        fontstyle='italic',
                        fontsize=16)

    offset_from = OffsetFrom(an1, (0, -1.4))
    an2 = axes.annotate(r'$\sqrt{s}$' + " = 13 TeV , 36.1 fb$^{-1}$",
                        xy=(0.05, 0.91),
                        xycoords=axes.transAxes,
                        textcoords=offset_from,
                        fontweight='normal',
                        fontsize=12)

    offset_from = OffsetFrom(an2, (0, -1.4))
    an3 = axes.annotate("1 lepton, " + str(nJets) + " jets, 2 b-tags",
                        xy=(0.05, 0.91),
                        xycoords=axes.transAxes,
                        textcoords=offset_from,
                        fontstyle='italic',
                        fontsize=12)

    offset_from = OffsetFrom(an3, (0, -1.6))
    an4 = axes.annotate("p$^V_T \geq$ 150 GeV",
                        xy=(0.05, 0.91),
                        xycoords=axes.transAxes,
                        textcoords=offset_from,
                        fontstyle='italic',
                        fontsize=12)

    fig = plt.gcf()
    #fig.set_size_inches(10, 4)
    plt.savefig(figureName, bbox_inches='tight',
                dpi=300)  # should before plt.show method
    plt.show(block=block)

    return fig, axes
コード例 #13
0
ファイル: read.py プロジェクト: eloyina/arduinopython
import serial, time  #conexion
import matplotlib as plt  #graficar en python
from drawnow import *  #brinda caracteristas para redibujar el grafico
import atexit  #para definir funciones con de limpieza registro y no registradas

valuesH = []  #arreglo
valuesT = []
plt.ion()  #modo iterativo, nuevas versiones no necesitan
cnt = 0  #inicializamos una variable del tipo entero

serialArduino = serial.Serial('COM7', 115200)


def plotValues():
    plt.title('Serial value from Arduino')
    plt.grid(True)
    plt.ylabel('Valores del sensor ')
    plt.plot(valuesH, 'rx-', label='values')

    plt.legend(loc='upper right')


def doAtExit():
    serialArduino.close()
    print("Close serial")
    print("serialArduino.isOpen() = " + str(serialArduino.isOpen()))


atexit.register(doAtExit)

print("serialArduino.isOpen() = " + str(serialArduino.isOpen()))