Ejemplo n.º 1
1
class TestDialog( QDialog, Ui_dlgMPLTest ):
    def __init__( self, parent = None ):
        super( TestDialog, self ).__init__( parent )
        self.setupUi( self )
        
        # initialize mpl plot
        self.figure = Figure()
        #self.figure.set_figsize_inches( ( 4.3, 4.2 ) )
        self.axes = self.figure.add_subplot( 111 )
        self.figure.suptitle( "Frequency distribution", fontsize = 12 )
        self.axes.grid( True )
        self.canvas = FigureCanvas( self.figure )
        
        layout = QVBoxLayout()
        self.widgetPlot.setLayout(layout)
        layout.addWidget(self.canvas)
        #self.canvas.setParent( self.widgetPlot )
        
        # draw mpl plot
        #self.axes.clear()
        #self.axes.grid( True )
        #self.figure.suptitle( "Frequency distribution", fontsize = 12 )
        self.axes.set_ylabel( "Count", fontsize = 8 )
        self.axes.set_xlabel( "Values", fontsize = 8 )
        x = [ 4, 1, 5, 3, 3, 2, 3, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1 ]
        n, bins, pathes = self.axes.hist( x, 18, alpha=0.5, histtype = "bar" )
        self.canvas.draw()
        
        self.setWindowTitle( self.tr( "MPL test" ) )
Ejemplo n.º 2
0
def draw_polygon_png(solution, bin_bounds, bin_shape, path=None):
    base_width = 8
    base_height = base_width * bin_bounds['height'] / bin_bounds['width']
    num_bin = len(solution)
    fig_height = num_bin * base_height
    fig1 = Figure(figsize=(base_width, fig_height))
    fig1.suptitle('Polygon packing', fontweight='bold')
    FigureCanvas(fig1)

    i_pic = 1  # 记录图片的索引
    for shapes in solution:
        # 坐标设置
        ax = fig1.add_subplot(num_bin, 1, i_pic, aspect='equal')
        ax.set_title('Num %d bin' % i_pic)
        i_pic += 1
        ax.set_xlim(bin_bounds['x'] - 10, bin_bounds['width'] + 50)
        ax.set_ylim(bin_bounds['y'] - 10, bin_bounds['height'] + 50)

        output_obj = list()
        output_obj.append(patches.Polygon(bin_shape.contour(0), fc='green'))
        for s in shapes[:-1]:
            output_obj.append(
                patches.Polygon(s.contour(0), fc='yellow', lw=1,
                                edgecolor='m'))
        for p in output_obj:
            ax.add_patch(p)

    if path is None:
        path = 'example'

    fig1.savefig('%s.png' % path)
Ejemplo n.º 3
0
    def __init__(self,
                 parent=None,
                 width=5,
                 height=5,
                 dpi=100,
                 cursor_visible=False,
                 title='',
                 ylabel='',
                 xlabel=''):

        fig = Figure(figsize=(width, height), dpi=dpi)
        fig.suptitle(title, fontsize=10)

        self.axes = fig.add_subplot(111)
        self.axes.set_xlim(self.xmin, self.xmax)
        self.axes.set_ylim(-5, 5)
        self.axes.grid()

        super(SimplePlot, self).__init__(fig)

        self.ydata = []
        self.ydata2 = []

        self.xdata = []
        self.x = 0

        self.line, = self.axes.plot([], [], lw=1, label='roll')
        self.line2, = self.axes.plot([], [], lw=1, label='pitch')

        self.axes.legend()

        if cursor_visible:
            self.cursor = Cursor(self.axes)
            fig.canvas.mpl_connect('motion_notify_event',
                                   self.cursor.on_mouse_move)
Ejemplo n.º 4
0
def plot_difference_histogram(group, gene_name, bins=np.arange(20.1)):
    """
    Plot a histogram of percentage differences for a specific gene.
    """
    exact_matches = group[group.V_SHM == 0]
    cdr3s_exact = len(set(s for s in exact_matches.CDR3_nt if s))
    js_exact = len(set(exact_matches.J_gene))

    fig = Figure(figsize=(100 / 25.4, 60 / 25.4))
    ax = fig.gca()
    ax.set_xlabel('Percentage difference')
    ax.set_ylabel('Frequency')
    fig.suptitle('Gene ' + gene_name, y=1.08, fontsize=16)
    ax.set_title('{:,} sequences assigned'.format(len(group)))

    ax.text(
        0.25,
        0.95,
        '{:,} ({:.1%}) exact matches\n  {} unique CDR3\n  {} unique J'.format(
            len(exact_matches),
            len(exact_matches) / len(group), cdr3s_exact, js_exact),
        transform=ax.transAxes,
        fontsize=10,
        bbox=dict(boxstyle='round', facecolor='white', alpha=0.5),
        horizontalalignment='left',
        verticalalignment='top')
    _ = ax.hist(list(group.V_SHM), bins=bins)
    return fig
Ejemplo n.º 5
0
    def draw_plot(self):
        self.mainwidget.destroy()

        tabl = self.ds.get_data("pc_show")
        d = tabl.df()  #type:DataFrame
        if tabl.centroids is not None:
            fig = Figure(figsize=(5, 5), dpi=100)  # type:Figure
            ax = fig.add_subplot(111)

            ax.clear()
            ax.grid(True)
            k = len(tabl.centroids)
            g = d.groupby(["_cluster"]).count()["Daytime"]

            lbls = ["Cluster " + str(i) for i in range(k)]
            ax.pie(g,
                   colors=COLORS,
                   labels=lbls,
                   autopct="%2.2f %%",
                   pctdistance=0.8)
            ax.axis("equal")
            fig.suptitle("Cluster-Occurence in Data")

            self.canvas = FigureCanvasTkAgg(fig,
                                            self)  # type:FigureCanvasTkAgg

            self.mainwidget = self.canvas.get_tk_widget()
        else:
            self.mainwidget = Label(
                self,
                text=
                "No cluster calculated; therefore,\n no data can be shown here."
            )
        self.mainwidget.grid(column=0, row=0, sticky=(S, W, N, E))
Ejemplo n.º 6
0
def konto_graph(request, year, konto_id):
    from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
    from matplotlib.figure import Figure
    from matplotlib.dates import DateFormatter
    # Collect data
    konto = Konto.objects.get(pk = konto_id)
    innslags = konto.innslag.order_by('bilag__dato').filter(bilag__dato__year = year)
    # make plot
    fig=Figure()
    fig.suptitle(u"%s (År:%s)"% (konto, unicode(year)))
    ax=fig.add_subplot(111)
    x=[]
    y=[]
    sum = Decimal(0)
    for innslag in innslags:
        x.append(innslag.bilag.dato)
        y.append(sum)
        x.append(innslag.bilag.dato)
        sum += innslag.value
        y.append(sum)
    ax.plot_date(x, y, '-')
    if x: # if there is transactions on the konto in the period
        # fill the period from the end of the year with a red line
        ax.plot_date([x[-1],date(int(year),12,31)],[y[-1],y[-1]],"r")
        if x[0].day != 1 or x[0].month != 1:
            ax.plot_date([date(int(year),1,1),x[0]],[0,0],"r")
    else:
        ax.plot_date([date(int(year),1,1),date(int(year),12,31)],[0,0],"r")
    ax.xaxis.set_major_formatter(DateFormatter('%b'))
    fig.autofmt_xdate()
    canvas = FigureCanvas(fig)
    response = HttpResponse(content_type='image/png')
    canvas.print_png(response)
    return response
Ejemplo n.º 7
0
    def initUI(self, master):
        self.frame1.grid(row=0, column=0)
        self.frame2.grid(row=10, column=0)

        if len(high_pass.path) > 0:
            img = cv2.imread(high_pass.path, 0)
            min = np.minimum(img.shape[0], img.shape[1])
            img = cv2.resize(img, (min, min))
            M, N = img.shape
            # computing the 2-d fourier transformation of the image
            fourier_image = np.fft.fft2(img)

            # ideal low pass filter
            u = np.array(range(0, M))
            v = np.array(range(0, N))
            idx = np.where(u > (M / 2))
            u[idx] = u[idx] - M
            idy = np.where(v > N / 2)
            v[idy] = v[idy] - N
            [V, U] = np.meshgrid(v, u)
            D = (U**2 + V**2)**(1 / 2)
            # cutoff = 40
            cutoff = [50, 40, 20, 10]

            H = 1 - np.exp(((-1) * (D**2)) / (2 * ((cutoff[1])**2)))
            G = H * fourier_image
            imback = np.fft.ifft2(G)
            imback = np.uint8(np.real(imback))

            H1 = 1 - np.exp(((-1) * (D**2)) / (2 * ((cutoff[3])**2)))
            G1 = H1 * fourier_image
            imback1 = np.fft.ifft2(G1)
            imback1 = np.uint8(np.real(imback1))

            H2 = 1 - np.exp(((-1) * (D**2)) / (2 * ((cutoff[2])**2)))
            G2 = H2 * fourier_image
            imback2 = np.fft.ifft2(G2)
            imback2 = np.uint8(np.real(imback2))

            fig = Figure(figsize=(8, 8))
            fig.suptitle("Guassian high pass filter")
            a = fig.add_subplot(221)
            a.set_title("Original Image")
            a.imshow(img, cmap='gray')
            b = fig.add_subplot(222)
            b.set_title("Cutoff = 10")
            b.imshow(imback, cmap='gray')
            c = fig.add_subplot(223)
            c.set_title("Cutoff = 40")
            c.imshow(imback1, cmap='gray')
            d = fig.add_subplot(224)
            d.set_title("Cutoff = 20")
            d.imshow(imback2, cmap='gray')

            canvas = FigureCanvasTkAgg(fig, self.frame1)
            canvas.get_tk_widget().grid(row=1,
                                        column=0,
                                        columnspan=4,
                                        rowspan=8)
            canvas.draw()
Ejemplo n.º 8
0
def create_rose_date(station, date):
    if date == "":
        df = pd.read_csv(
            "https://greduvent.000webhostapp.com/sensations/get-meteo.php")
    else:
        df = pd.read_csv(
            "https://greduvent.000webhostapp.com/sensations/get-meteo.php?date="
            + date)
    df.columns = [
        'date_heure', 'station', 'vent', 'orientation', 'temperature'
    ]
    df["date_heure"] = pd.to_datetime(df["date_heure"],
                                      format='%Y-%m-%d %H:%M')
    df[["vent", "orientation",
        "temperature"]] = df[["vent", "orientation",
                              "temperature"]].apply(pd.to_numeric)

    df_station = df[df['station'] == station]

    fig = Figure()
    fig.set_size_inches(7, 7, forward=True)
    fig.suptitle(station)

    ax = fig.add_subplot(1, 1, 1, projection="windrose")
    wd = df_station['orientation']
    ws = df_station['vent']
    ax.bar(wd, ws, normed=True, opening=0.8, edgecolor='white')
    ax.set_legend()

    return fig
Ejemplo n.º 9
0
def savePng2D(filename, X, Y, data, maxValue, minValue, currentTime, cellSize):
    figure = Figure()
    canvas = FigureCanvas(figure)

    t = str(currentTime)

    row = round(math.sqrt(cellSize))
    column = math.ceil(cellSize / row)

    figure.suptitle(t)

    for i in range(cellSize):
        m = 100 * row + 10 * column + i + 1
        axes = figure.add_subplot(m)
        figure.subplots_adjust(right=0.8)
        #cbaxes = figure.add_axes([0.85, 0.15, 0.05, 0.5])

        cmap = cm.jet

        layer = data[0, :, :, i]

        cb = axes.pcolormesh(X, Y, layer, vmin=minValue[i], vmax=maxValue[i])

        axes.axis([X.min(), X.max(), Y.min(), Y.max()])
        axes.set_aspect('equal')
        figure.colorbar(cb, ax=axes, fraction=0.046, pad=0.04)

    ###
    if cellSize > 1:
        figure.tight_layout()

    canvas.draw()
    figure.savefig(filename, format='png')
    figure.clear()
Ejemplo n.º 10
0
def plot_interest_graph():
    """Function to plot the cumulative interest for the next 12 months here."""

    # YOUR CODE to generate the x and y lists here which will be plotted

    # This code to add the plots to the window is a little bit fiddly so you are provided with it.
    # Just make sure you generate a list called 'x' and a list called 'y' and the graph will be plotted correctly.
    P = account.balance
    r = account.interest_rate
    n = 12.0
    t = 0.083
    x = list()
    y = list()
    for i in range(1, 13):
        temp1 = 1 + (r / n)
        temp2 = 1  # 12*(1/12) = 1
        A = (P * math.pow(temp1, temp2))
        P = A
        x.append(i)
        y.append(A)
    figure = Figure(figsize=(5, 2), dpi=100)
    figure.suptitle('Cumulative Interest 12 Months')
    a = figure.add_subplot(111)
    a.plot(x, y, marker='o')
    a.grid()

    canvas = FigureCanvasTkAgg(figure, master=win)
    canvas.draw()
    graph_widget = canvas.get_tk_widget()
    graph_widget.grid(row=4, column=0, columnspan=5, sticky='nsew', padx=10)
Ejemplo n.º 11
0
class MyMatplotlibWidget(FigureCanvas):
    """ Base class for the matplotlib widgets """
    def __init__(self,
                 parent=None,
                 aspect='auto',
                 title='',
                 width=5,
                 height=5,
                 dpi=120):

        self.fig = Figure(figsize=(width, height), dpi=dpi)
        FigureCanvas.__init__(self, self.fig)
        self.setParent(parent)
        FigureCanvas.setSizePolicy(self, QSizePolicy.Expanding,
                                   QSizePolicy.Expanding)
        FigureCanvas.updateGeometry(self)

        self.fig.suptitle(title, fontsize=10, fontweight='bold')
        self.axes = self.fig.add_subplot(111)
        self.fig.subplots_adjust(right=0.9, top=0.85, left=0.1, bottom=0.15)
        self.fig.set_facecolor('None')

        self.canvas = FigureCanvas(self.fig)
        self.canvas.setParent(parent)

        # Add the navigation control to zoom/pan/etc. the plots
        self.toolbar = NavigationToolbar(self.canvas, self.canvas)
Ejemplo n.º 12
0
def plot_interest_graph():
    """Function to plot the cumulative interest for the next 12 months here."""

    # YOUR CODE to generate the x and y lists here which will be plotted

    # This code to add the plots to the window is a little bit fiddly so you are provided with it.
    # Just make sure you generate a list called 'x' and a list called 'y' and the graph will be plotted correctly.
    principle_amount = account.balance
    rate = account.interest_rate
    n = 12.0
    t = 1 / 12  # (1/12) # n*t = 1
    x = []
    y = []
    for i in range(1, 13):
        principle_interest = (principle_amount * math.pow((1 + (rate / n)), 1))
        principle_amount = principle_interest
        x.append(i)
        y.append(principle_interest)
    figure = Figure(figsize=(5, 2), dpi=100)
    figure.suptitle('Cumulative Interest 12 Months')
    a = figure.add_subplot(111)
    a.plot(x, y, marker='o')
    a.grid()

    canvas = FigureCanvasTkAgg(figure, master=win)
    canvas.draw()
    graph_widget = canvas.get_tk_widget()
    graph_widget.grid(row=4, column=0, columnspan=5, sticky='nsew')
Ejemplo n.º 13
0
class Plottest(QMainWindow):
    def __init__(self):
        super(Plottest, self).__init__()
        self.setWindowTitle('GUI with Matplotlib')

        self.__figure()
        self.__plot()

    def __figure(self):
        self.__fig = Figure(figsize=(8, 5))
        self.__fig.suptitle('Demo')

        figcanvas = FigureCanvas(self.__fig)

        toolbar = NavigationToolBar(figcanvas, self)
        toolbar.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)
        self.addToolBar(toolbar)

        self.setCentralWidget(figcanvas)

    def __plot(self):
        self.__ax = self.__fig.add_subplot(1, 1, 1)

        x = np.linspace(-2 * np.pi, 2 * np.pi, 100)
        y = np.sin(x)

        self.__ax.plot(x, y, 'b:', label="Sin", linewidth=2)
        self.__ax.legend()
Ejemplo n.º 14
0
def processOne(fn,done,gpus,telescope,outdir,plotdir,redo=False):
    print fn
    info = decodeFilename(fn)
    print info
    pklname = ('ds_%s_%s_%s_%s.pkl' % (info['source'],info['mjd'],
                                      info['scan'],telescope))
    outfn = os.path.join(outdir,'pkls',pklname)
    if (not redo) and (outfn in done):
        return fn,None,pklname
    try:
    #if True:
        ds = loadDynSpecFromCycSpecScan(int(info['scan']), int(info['mjd']), 
                                        gpus=gpus, telescope=telescope)
        print "loaded dynspec"
        dynspec.pickle(outfn, ds)
        print "pickled",outfn
        fig = Figure(figsize=(10,12))
        fig.subplots_adjust(left=0.09,bottom=0.05,top=0.95,right=0.95)
        ds.plot(fig=fig)
        plotname = os.path.join(plotdir,pklname + '.png')
        esc_fname = outfn.replace('_',r'\_')
        fig.suptitle(('%s @ %s %s' % (info['source'],telescope,esc_fname)),size='medium')
        canvas = FigureCanvasAgg(fig)
        canvas.print_figure(plotname)
    except Exception,e:
        print fn,e,pklname
        return fn,e,pklname
Ejemplo n.º 15
0
    def callback(self, event):
        print("Pos: ", event.x, event.y)

        if(self.win != None):
            self.win.destroy()
        win = tk.Toplevel()
        self.win = win
        up_size = (opt["size"]*opt["scale"], opt["size"]*opt["scale"])

        for name, path in self.opt["image_set"].items():
            img = Image.open(path)
            img = img.crop((event.x, event.y, event.x+opt["size"], event.y+opt["size"]))
            img = img.resize(up_size)

            f = Figure((1, 1), dpi=200)  # 设置对比图像的显示大小(dpi)
            a = f.add_subplot(111)
            a.axis('off')
            f.suptitle(name, fontsize=6)
            a.imshow(img)

            canvas = FigureCanvasTkAgg(f, master=win)
            # canvas.show()
            canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)

        win.mainloop()
Ejemplo n.º 16
0
def plot_interest_graph():
    '''Function to plot the cumulative interest for the next 12 months here.'''

    # YOUR CODE to generate the x and y lists here which will be plotted
    P = account.balance
    x = []
    y = []
    for idx in range(1, 13):
        x.append(idx)
        val = P * (1 + account.account_interest / 12)**(idx * 12)
        y.append(val)
        P = val

    # This code to add the plots to the window is a little bit fiddly so you are provided with it.
    # Just make sure you generate a list called 'x' and a list called 'y' and the graph will be plotted correctly.
    figure = Figure(figsize=(5, 2), dpi=100)
    figure.suptitle('Cumulative Interest 12 Months')
    a = figure.add_subplot(111)
    a.plot(x, y, marker='o')
    a.grid()

    canvas = FigureCanvasTkAgg(figure, master=win)
    canvas.draw()
    graph_widget = canvas.get_tk_widget()
    graph_widget.grid(row=4, column=0, columnspan=5, sticky='nsew')
Ejemplo n.º 17
0
def plot_frame_displacement(FD_file, mean_FD_distribution=None, figsize=(11.7,8.3)):

    FD_power = np.loadtxt(FD_file)

    fig = Figure(figsize=figsize)
    FigureCanvas(fig)
    
    if mean_FD_distribution:
        grid = GridSpec(2, 4)
    else:
        grid = GridSpec(1, 4)
    
    ax = fig.add_subplot(grid[0,:-1])
    ax.plot(FD_power)
    ax.set_xlim((0, len(FD_power)))
    ax.set_ylabel("Frame Displacement [mm]")
    ax.set_xlabel("Frame number")
    ylim = ax.get_ylim()
    
    ax = fig.add_subplot(grid[0,-1])
    sns.distplot(FD_power, vertical=True, ax=ax)
    ax.set_ylim(ylim)
    
    if mean_FD_distribution:
        ax = fig.add_subplot(grid[1,:])
        sns.distplot(mean_FD_distribution, ax=ax)
        ax.set_xlabel("Mean Frame Displacement (over all subjects) [mm]")
        MeanFD = FD_power.mean()
        label = "MeanFD = %g"%MeanFD
        plot_vline(MeanFD, label, ax=ax)
        
    fig.suptitle('motion', fontsize='14')
        
    return fig
Ejemplo n.º 18
0
 def plotmap(p_table):
     
     no_hrs = int((end_time-st_time).seconds/3600)+24*(end_time-st_time).days
     if(no_hrs>48):
         Msg = mb.askyesno(title='Warning', message= 'The selected time range is very large \nHeatmap would not be clear \nWould you still want to continue?') 
     elif(no_hrs<=48):
         Msg = True
     
     if(Msg == True): 
         plwindow = tk.ThemedTk()
         plwindow.get_themes()
         plwindow.set_theme('breeze')
         plwindow.geometry('1000x1000') 
         plwindow.configure(background= '#ffc3a0')
         plwindow.title('Heat Map')
                 
         f = Figure(figsize = (10,10))
         f.clf()
         f.suptitle('Heatmap for 5 minutes')
         canvas = FigureCanvasTkAgg(f, master = plwindow)
         canvas.get_tk_widget().pack(fill = BOTH, expand = True)
 
         canvas._tkcanvas.pack(side = TOP, fill = BOTH, expand = True)
         a = f.add_subplot(111)
         Heatmap = sns.heatmap(p_table, cmap = 'RdYlGn', annot = p_table.values, ax=a).set_yticklabels(labels = p_table.index, rotation = 0)
         
         plwindow.mainloop()
Ejemplo n.º 19
0
def searchstringPieChart(request):
    page_title='Search String Pie Chart'
    year=stat.getYear()
    searchList = list(SearchTerm.objects.values_list('q', flat=True))
    search_string = ' '.join(searchList)
    result = Counter(search_string.split()).most_common(10)
    searchDict = {}
    for key,val in result:
        searchDict[key] = val

    fig=Figure()
    ax=fig.add_subplot(111)

    title='Top Ten search string submitted by user ({0})'.format(year)
    fig.suptitle(title, fontsize=14)
    try:
        x = searchDict.values()
        labels = searchDict.keys()
        ax.pie(x, labels=labels);
    except 	ValueError:
        pass
    canvas = FigureCanvas(fig)
    response = HttpResponse(content_type='image/png')
    canvas.print_png(response)
    return response
Ejemplo n.º 20
0
def plotSolarRadiationAgainstMonth(filename):
    trainRowReader = csv.reader(open(filename, 'rb'), delimiter=',')
    month_most_common_list = []
    Solar_radiation_64_list = []
    for row in trainRowReader:
        month_most_common = row[3]
        Solar_radiation_64 = row[6]
        month_most_common_list.append(month_most_common)
        Solar_radiation_64_list.append(Solar_radiation_64)   
     
    #convert all elements in the list to float while skipping the first element for the 1st element is a description of the field.
    month_most_common_list = [float(i) for i in prepareList(month_most_common_list)[1:] ]
    Solar_radiation_64_list = [float(i) for i in prepareList(Solar_radiation_64_list)[1:] ]

    fig=Figure()
    ax=fig.add_subplot(111)
    title='Scatter Diagram of solar radiation against month of the year'
    ax.set_xlabel('Most common month')
    ax.set_ylabel('Solar Radiation')
    fig.suptitle(title, fontsize=14)
    try:
        ax.scatter(month_most_common_list, Solar_radiation_64_list)
        #it is possible to make other kind of plots e.g bar charts, pie charts, histogram
    except ValueError:
        pass
    canvas = FigureCanvas(fig)
    canvas.print_figure('solarRadMonth.png',dpi=500)
Ejemplo n.º 21
0
class ExoCanvas(FigureCanvas):

    '''
    Base class to build graphs and plots.
    '''

    def __init__(self, parent, dpi):
        self.fig = Figure(dpi=dpi, facecolor='white', edgecolor='white')
        self.axes = self.fig.add_subplot(111)
        super().__init__(self.fig)
        self.setParent(parent)
        matplotlib.rcParams.update({
            'font.size': 12,
        })
        self.setObjectName('Canvas')

    def initFigure(self, x, y, title=None, color='black'):
        '''
        Initialise figure by plotting the initial state of the graph.
        '''

        self.axes.plot(x, y, color=color)
        if title is not None:
            self.fig.suptitle(title)

    def save(self, dname, figname):
        '''
        Save the current instance of the graph.
        '''
        fname = path.join(dname, figname+'.png')
        self.fig.savefig(fname, dpi=200, format='png')
Ejemplo n.º 22
0
    def __init__(self, parent=None, width=8, height=4, dpi=100, title=None):
        # create palette object
        palette = QtGui.QPalette()

        # get background color
        r, g, b, a = palette.color(QtGui.QPalette.Window.Background).toTuple()
        r, g, b, a = map(lambda x: x / 255.0, (r, g, b, a))

        # create figure
        fig = Figure(figsize=(width, height), dpi=dpi, facecolor=(r, g, b))

        # create single plot
        self.axes = fig.add_subplot(111)

        # We want the axes cleared every time plot() is called
        self.axes.hold(False)

        # set title
        if title != None:
            fig.suptitle(title, fontsize=12)

        # call base class constructor
        super(matplotlibCanvas, self).__init__(fig)
        self.setParent(parent)

        FigureCanvas.setSizePolicy(self, QtGui.QSizePolicy.Expanding,
                QtGui.QSizePolicy.Expanding)
        FigureCanvas.updateGeometry(self)
Ejemplo n.º 23
0
 def plot_file():
     """
       Hier kunnnen de data van de file in een grafiek getekend worden
     """
     try:
         anw = ReadIt.readd(self, self.fileDai)
         x, y = anw[0], anw[1]
         f = Figure(figsize=(5, 5), dpi=100)
         f.patch.set_facecolor("#fff8e8")
         f.suptitle('Growth Curve', fontsize=14, fontweight='bold')
         a = f.add_subplot(111)
         a.set_ylabel('Groei in CFU/ml')
         a.set_xlabel('Tijd in uur')
         a.plot(np.array(x), np.array(y), "#3D405B")
         a.plot(x, np.array(y), "o", color="#E07A5F")
         canvas = FigureCanvasTkAgg(f, self)
         canvas.draw()
         canvas.get_tk_widget().pack(side=tk.RIGHT,
                                     fill=tk.BOTH,
                                     expand=True)
     except Exception:
         messagebox.showwarning(
             "warning",
             "Je hebt 1 of meerdere inputs verkeerd ingevoerd,\n ----probeer het opnieuw----"
         )
Ejemplo n.º 24
0
    def cmdRun_Clicked(self):
        fig1 = Figure()
        ax1f1 = fig1.add_subplot(1, 1, 1)
        x = []
        y = []
        for i in range(10):
            x.append(i)
            y.append(i * i)
        ax1f1.plot(x, y, marker='o')

        minDemand = (float(self.txtToDemand.toPlainText()) -
                     float(self.txtFromDemand.toPlainText())) / float(
                         self.txtDeltaDemand.toPlainText())

        title = self.lstJunctions.selectedItems()
        fig1.suptitle(title[0].text())
        fig1.suptitle(self.txtToDemand.toPlainText())

        ax1f1.set(xlabel='x-label', ylabel='y-label')
        ax1f1.grid(True)
        self.canvas = FigureCanvas(fig1)
        self.mplvl.addWidget(self.canvas)
        self.canvas.draw()
        self.toolbar = NavigationToolbar(self.canvas,
                                         self.mplwindow,
                                         coordinates=True)
        self.mplvl.addWidget(self.toolbar)
Ejemplo n.º 25
0
        def cmdRun_Clicked(self):
            listitem = self.lstJunctions.selectedItems()
            junc = listitem[0].text()

            title = 'Minimum pressure vs. demand at junction ' + junc
            (d, p) = run_fire_flow(junc,
                                   float(self.txtFromDemand.toPlainText()),
                                   float(self.txtDeltaDemand.toPlainText()),
                                   float(self.txtToDemand.toPlainText()))
            fig1 = Figure()
            ax1f1 = fig1.add_subplot(1, 1, 1)
            ax1f1.plot(d, p, label='', linestyle='--', marker='o', color='b')
            fig1.suptitle(title, fontsize=14)
            ax1f1.grid(True)

            attribute = ENR_node_type.get_attribute_by_name('Pressure')
            atrn = attribute.name
            atru = attribute.units(session.output.unit_system)
            ylabel = atrn + ' (' + atru + ')'
            attribute = ENR_node_type.get_attribute_by_name('Demand')
            atrn = attribute.name
            atru = attribute.units(session.output.unit_system)
            xlabel = atrn + ' (' + atru + ')'

            ax1f1.set(xlabel=xlabel, ylabel=ylabel)

            self.canvas = FigureCanvas(fig1)
            self.mplvl.addWidget(self.canvas)
            self.canvas.draw()
            self.toolbar = NavigationToolbar(self.canvas,
                                             self.mplwindow,
                                             coordinates=True)
            self.mplvl.addWidget(self.toolbar)
Ejemplo n.º 26
0
    def __init__(self,
                 parent=None,
                 width=800,
                 height=400,
                 dpi=100,
                 title=None):

        width = width / float(dpi)
        height = height / float(dpi)

        fig = Figure(figsize=(width, height), dpi=dpi)
        self.axes_top = fig.add_subplot(211)
        self.axes_bottom = fig.add_subplot(212)
        # We want the axes cleared every time plot() is called
        self.axes_top.hold(False)
        self.axes_bottom.hold(False)

        if title != None:
            fig.suptitle(title, fontsize=12)

        FigureCanvasQTAgg.__init__(self, fig)
        self.setParent(parent)

        FigureCanvasQTAgg.setSizePolicy(self, QtGui.QSizePolicy.Expanding,
                                        QtGui.QSizePolicy.Expanding)
        FigureCanvasQTAgg.updateGeometry(self)
Ejemplo n.º 27
0
    def arma_model(self,p,q,df):
        
        if self.is_canvas_arıma == 1:
            self.canvas.get_tk_widget().pack_forget()          
        
        ar = ARMA(df['num_orders'], order=(p,q))
        ar_fitted = ar.fit(disp=0)
        forecast = ar_fitted.predict(50, 165)
        
        diff_ARIMA = (ar_fitted.fittedvalues - df['num_orders'])
        diff_ARIMA.dropna(inplace=True)

        fig = Figure(figsize=(6, 6), dpi=100)
        fig.add_subplot(111).plot(df)
        fig.add_subplot(111).plot(forecast)
        
        if self.ismov == 1:
            forecast2 = ar_fitted.predict(12,145)
        else:
            forecast2 = ar_fitted.predict(1,145)
        error = mean_squared_error(df['num_orders'], forecast2)
        fig.suptitle('Root mean squared error: %.4F'%error)
        
        # fig.suptitle('ARMA Model RSS: %.4F'%sum((diff_ARIMA)**2))
        

        self.canvas = FigureCanvasTkAgg(fig, master =self.arıma)  # A tk.DrawingArea.
        self.canvas.get_tk_widget().pack(side=RIGHT)
        self.canvas.draw()
        self.is_canvas_arıma = 1
def plotPieChart(positive, wpositive, spositive, negative, wnegative,
                 snegative, neutral, searchTerm, noOfSearchTerms):
    labels = [
        'Positive [' + str(positive) + '%]',
        'Weakly Positive [' + str(wpositive) + '%]',
        'Strongly Positive [' + str(spositive) + '%]',
        'Neutral [' + str(neutral) + '%]', 'Negative [' + str(negative) + '%]',
        'Weakly Negative [' + str(wnegative) + '%]',
        'Strongly Negative [' + str(snegative) + '%]'
    ]
    sizes = [
        positive, wpositive, spositive, neutral, negative, wnegative, snegative
    ]
    colors = [
        'yellowgreen', 'lightgreen', 'darkgreen', 'gold', 'red', 'lightsalmon',
        'darkred'
    ]

    f = Figure(figsize=(5, 5), dpi=100)
    f.suptitle('How people are reacting on ' + searchTerm + ' by analyzing ' +
               str(noOfSearchTerms) + ' Tweets.',
               fontsize=10)
    plt = f.add_subplot(111)
    patches, texts = plt.pie(sizes, colors=colors, startangle=90)
    plt.legend(patches, labels, loc="best")
    plt.axis('equal')
    canvas = FigureCanvasTkAgg(f)
    canvas.get_tk_widget().pack(side=tk.BOTTOM, fill=tk.BOTH, expand=FALSE)
Ejemplo n.º 29
0
def base_plot(df, part, cut=30, xlabel="Number of Episodes", jump=5):
    data = df.data[:cut]
    label = df.label
    with style.context("ggplot"):
        fig = Figure()
        canvas = FigureCanvas(fig)
        ax1 = fig.add_subplot(1, 1, 1)
        ax2 = ax1.twiny()
        
        ax1.plot([i.episodes for i in data], [i.win_rate for i in data], "-o")
        
        ax1.set_ylim(0., 1.1)
        ax1.set_xlim(0, data[-1].episodes + data[0].episodes)
        ax2.set_xlim(0, data[-1].episodes + data[0].episodes)
        
        ax1.set_xticks([i.episodes for i in data[::jump]])
        ax1.set_xticklabels(["{:.1e}".format(i.episodes) for i in data[::jump]])
        ax2.set_xticks([i.episodes for i in data[::jump]])
        ax2.set_xticklabels(["{:.1e}".format(i.time) for i in data[::jump]])
        
        fig.suptitle("Win Rate of {}".format(label))
        fig.subplots_adjust(top=0.8)
        ax1.set_xlabel(xlabel)
        ax1.set_ylabel("Win Rate")
        ax2.set_xlabel("Time (seconds)")
        p = Path("figures/part{}/".format(part))
        p.mkdir(parents=True, exist_ok=True)
        fig.savefig(str(p / "plot_{}.png".format(df.name)))
def plot_interest_graph():
    '''Function to plot the cumulative interest for the next 12 months here.'''

    # YOUR CODE to generate the x and y lists here which will be plotted
    
    x=[1,2,4,5,6,7,8,9,10,11,12]
    y=[]
    p = float(account.balance)
    print(p)
    rate = float(account.interest_rate)
    for val in x:
        value=(p*1*rate)/100
        y.append(p+value)
        p+=value
    
    # This code to add the plots to the window is a little bit fiddly so you are provided with it.
    # Just make sure you generate a list called 'x' and a list called 'y' and the graph will be plotted correctly.
    figure = Figure(figsize=(5,2), dpi=100)
    figure.suptitle('Cumulative Interest 12 Months')
    a = figure.add_subplot(111)
    a.plot(x, y, marker='o')
    a.grid()
    
    canvas = FigureCanvasTkAgg(figure, master=win)
    canvas.draw()
    graph_widget = canvas.get_tk_widget()
    graph_widget.grid(row=4, column=0, columnspan=5, sticky='nsew')
Ejemplo n.º 31
0
def make_histogram( metrics, outfilename, **kargs ) : 
    
    adjmetrics = np.nan_to_num(metrics)
    nonzero = np.where( adjmetrics != 0 )

#    foo = plt.hist( adjmetrics[nonzero], bins=100, normed=True )
#    plt.show()

    fig = Figure()

    if "title" in kargs : 
        fig.suptitle(kargs["title"])

    ax = fig.add_subplot(111)
    ax.grid()
    ax.hist(np.nan_to_num(metrics),bins=25)
#    ax.hist(np.nan_to_num(metrics),bins=25,normed=True)

    ax.set_xlabel( "Metric" )

    ax.set_xlim(0,1.0)

    canvas = FigureCanvasAgg(fig)
    canvas.print_figure(outfilename)
    print "wrote", outfilename
Ejemplo n.º 32
0
def Generation_figure (listData,tolBasse,tolHaute,titre = "Titre", legendTolBasse = "Tolérance -", legendTolHaute = "Tolérance +", legendData = "Donnée"):
	'''
	Fonction pour la génération des figures
'''
	#Création des lignes pour les tolérances
	listTolBasse = []
	listTolHaute = []
	
	for element in range(len(listData)) :
		listTolBasse.append(tolBasse)

	for element in range(len(listData)):
		listTolHaute.append(tolHaute)

	#Création du graphique
	figure = Figure(figsize = (6,5), dpi = 96)
	ax = figure.add_subplot(111)
	ax.plot(range(len(listData)),listData,label = legendData) #Data
	ax.plot (range (len(listTolBasse)),listTolBasse, label = legendTolBasse)#TolBasse
	ax.plot (range (len(listTolHaute)),listTolHaute,label = legendTolHaute)#TolBasse
	figure.suptitle(titre)
	figure.align_labels()
	ax.legend()
	#ax.text(0.5,0.5,"Test")
	#Print des labels
	#xlabel('x label')
	
	#plt.show()
	return figure
Ejemplo n.º 33
0
def plot_DVARS(title, DVARS_file, mean_DVARS_distribution=None, figsize=(11.7,8.3)):

    DVARS = np.loadtxt(DVARS_file)

    fig = Figure(figsize=figsize)
    FigureCanvas(fig)
    
    if mean_DVARS_distribution:
        grid = GridSpec(2, 4)
    else:
        grid = GridSpec(1, 4)
    
    ax = fig.add_subplot(grid[0,:-1])
    ax.plot(DVARS)
    ax.set_xlim((0, len(DVARS)))
    ax.set_ylabel("DVARS")
    ax.set_xlabel("Frame number")
    ylim = ax.get_ylim()
    
    ax = fig.add_subplot(grid[0,-1])
    sns.distplot(DVARS, vertical=True, ax=ax)
    ax.set_ylim(ylim)
    
    if mean_DVARS_distribution:
        ax = fig.add_subplot(grid[1,:])
        sns.distplot(mean_DVARS_distribution, ax=ax)
        ax.set_xlabel("Mean DVARS (over all subjects) [std]")
        MeanFD = DVARS.mean()
        label = "Mean DVARS = %g"%MeanFD
        plot_vline(MeanFD, label, ax=ax)
        
    fig.suptitle(title, fontsize='14')
        
    return fig
Ejemplo n.º 34
0
def plot_mosaic(nifti_file,
                title=None,
                overlay_mask=None,
                figsize=(11.7, 8.3)):
    if isinstance(nifti_file, str):
        nii = nb.load(nifti_file)
        mean_data = nii.get_data()
    else:
        mean_data = nifti_file

    n_images = mean_data.shape[2]
    row, col = _calc_rows_columns(figsize[0] / figsize[1], n_images)

    if overlay_mask:
        overlay_data = nb.load(overlay_mask).get_data()

    # create figures
    fig = Figure(figsize=figsize)
    FigureCanvas(fig)

    fig.subplots_adjust(top=0.85)
    for image in (range(n_images)):
        ax = fig.add_subplot(row, col, image + 1)
        data_mask = np.logical_not(np.isnan(mean_data))
        if overlay_mask:
            ax.set_rasterized(True)
        ax.imshow(np.fliplr(mean_data[:, :, image].T),
                  vmin=np.percentile(mean_data[data_mask], 0.5),
                  vmax=np.percentile(mean_data[data_mask], 99.5),
                  cmap=cm.Greys_r,
                  interpolation='nearest',
                  origin='lower')  # @UndefinedVariable
        if overlay_mask:
            cmap = cm.Reds  # @UndefinedVariable
            cmap._init()
            alphas = np.linspace(0, 0.75, cmap.N + 3)
            cmap._lut[:, -1] = alphas
            ax.imshow(np.fliplr(overlay_data[:, :, image].T),
                      vmin=0,
                      vmax=1,
                      cmap=cmap,
                      interpolation='nearest',
                      origin='lower')  # @UndefinedVariable

        ax.axis('off')
    fig.subplots_adjust(left=0.05,
                        right=0.95,
                        bottom=0.05,
                        top=0.95,
                        wspace=0.01,
                        hspace=0.1)

    if not title:
        _, title = os.path.split(nifti_file)
        title += " (last modified: %s)" % time.ctime(
            os.path.getmtime(nifti_file))
    fig.suptitle(title, fontsize='10')

    #fig.savefig(output_name)
    return fig
Ejemplo n.º 35
0
def displayrankedItemwithBidsPieChart(request):
    page_title='Pie Chart on Ranked Item'
    year=stat.getYear()
    itemBidDict, bidtotalSum = stat.createItemIDBidCountDict()
    top_ten_dict = stat.sortedItemDictionary(itemBidDict)
    itemobjDict = {}	
    for key,value in top_ten_dict:
        itemObj = get_object_or_404(Item, pk=key)
        itemobjDict[itemObj.name] = value

    fig=Figure()
    ax=fig.add_subplot(111)

    title='Top Ten ranked items with the highest bids ({0})'.format(year)
    fig.suptitle(title, fontsize=14)
    try:
        x = itemobjDict.values()
        labels = itemobjDict.keys()
        ax.pie(x, labels=labels);
    except ValueError:
        pass
    canvas = FigureCanvas(fig)
    response = HttpResponse(content_type='image/png')
    canvas.print_png(response)
    return response
Ejemplo n.º 36
0
def plot_interest_graph():
    global account
    '''Function to plot the cumulative interest for the next 12 months here.'''
    x = []
    y = []
    # YOUR CODE to generate the x and y lists here which will be plotted

    interest = 1 + ((account.interest_rate) / 12)

    for i in range(1, 13):
        x.append(i)

    y.append(account.balance)

    for j in range(1, 12):
        y.append(y[j - 1] * interest)

    # This code to add the plots to the window is a little bit fiddly so you are provided with it.
    # Just make sure you generate a list called 'x' and a list called 'y' and the graph will be plotted correctly.
    figure = Figure(figsize=(5, 2), dpi=90)
    figure.suptitle('Cumulative Interest 12 Months')
    a = figure.add_subplot(111)
    a.plot(x, y, marker='o')
    a.grid()

    canvas = FigureCanvasTkAgg(figure, master=win)
    canvas.draw()
    graph_widget = canvas.get_tk_widget()
    graph_widget.grid(row=4, column=0, columnspan=5, sticky='n')
Ejemplo n.º 37
0
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent, bg='Navy')
        label = tk.Label(self, text="Report 4!", font=LARGE_FONT).pack(pady=10,
                                                                       padx=10)

        button1 = ttk.Button(
            self,
            text="Back to Home",
            command=lambda: controller.show_frame(StartPage)).pack()
        button2 = ttk.Button(
            self,
            text="Report 1",
            command=lambda: controller.show_frame(PageOne)).pack()
        sql = 'SELECT `result_demo`.`TimeStamp`, `result_demo`.`Provider_Bene_before`, `result_demo`.`Provider_Bene_after` from `pvdata_home1`.`result_demo`'
        cursor.execute(sql)
        rows = cursor.fetchall()
        df = pd.DataFrame([[ij for ij in i] for i in rows])
        df.rename(columns={0: 'time', 1: 'before', 2: 'after'}, inplace=True)
        f = Figure(figsize=(5, 3), dpi=100)
        canvas = FigureCanvasTkAgg(f, self)
        canvas.show()
        canvas.get_tk_widget().pack(side=tk.BOTTOM, fill=tk.BOTH, expand=True)

        toolbar = NavigationToolbar2TkAgg(canvas, self)
        toolbar.update()
        canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=True)
        f.suptitle('ss')
        a = f.add_subplot(111)
        a.plot(df['time'], df['before'], label='without aggregator')
        a.plot(df['time'], df['after'], label='with aggregator')
Ejemplo n.º 38
0
def create_figure(builds, gold_precision, gold_recall, silver_precision, silver_recall):
    fig = Figure(figsize=(20, 20))
    fig.suptitle('Precision Recall Martix', fontsize=16)
    grid = plt.GridSpec(4, 1, hspace=0.8, wspace=5)

    axis = fig.add_subplot(grid[0:1, :])
    axis2 = fig.add_subplot(grid[1:2, :])
    axis3 = fig.add_subplot(grid[2:3, :])
    axis4 = fig.add_subplot(grid[3:4, :])

    axis.grid()
    axis2.grid()
    axis3.grid()
    axis4.grid()

    axis.title.set_text('Gold Precision')
    axis2.title.set_text('Gold Recall')
    axis3.title.set_text('Silver Precision')
    axis4.title.set_text('Silver Recall')

    axis.plot(builds, gold_precision)
    axis2.plot(builds, gold_recall)
    axis3.plot(builds, silver_precision)
    axis4.plot(builds, silver_recall)

    return fig
Ejemplo n.º 39
0
def graph_click_position(fig_tags, xy_seq):
    fig = Figure(figsize=(12, 8), dpi=80)
    fig.suptitle(fig_tags['title'])
    canvas = FigureCanvas(fig)
    for i in range(0, 4):
        ax = fig.add_subplot(2, 2, i + 1)
        # ax.xaxis.set_ticks_position('top')  # 将X坐标轴移到上面
        # ax.invert_yaxis()
        axname = fig_tags['plot' + str(i)]['axname']
        axname = axname
        xlabel = fig_tags['plot' + str(i)]['xlabel']
        ylabel = fig_tags['plot' + str(i)]['ylabel']
        ax.set_xlim(fig_tags['plot' + str(i)]['xlim'])
        ax.set_ylim(fig_tags['plot' + str(i)]['ylim'])
        dataname = fig_tags['plot' + str(i)]['dataname1']
        seq = xy_seq[i]
        x = [int(n[0]) for n in seq]
        y = [int(n[1]) for n in seq]
        ax.plot(x, y, 'b.', label=dataname, linewidth=2)
        ax.set_xlabel(xlabel, labelpad=2)
        ax.set_ylabel(ylabel)
        ax.set_title(axname)
        ax.legend()  # 图例
        ax.grid()  # 网格
    canvas.print_figure('demo1.png')

    def get_page_switch_time():
        pass
Ejemplo n.º 40
0
class Temperature:
    def __init__(self, param):
        self.__name = param[0]
        self.__root = param[1]
        # prepare matplotlib objects
        font = {'family': 'Verdana', 'weight': 'normal'}
        rc('font', **font)
        self.__figure = None
        self.__plot = None
        self.__prepare_figures()

    def __prepare_figures(self):
        self.__figure = Figure(figsize=(3, 2), dpi=100)
        self.__figure.suptitle(self.__name)
        self.__figure.subplots_adjust(top=0.85, bottom=0.3)
        # subplot customize
        self.__plot = self.__figure.add_subplot(111)
        self.__plot.set_xlabel(u'время')
        self.__plot.set_ylabel(u'температура')

    def show(self):
        canvas = FigureCanvasTkAgg(self.__figure, master=self.__root)
        canvas.get_tk_widget().pack(fill=Tkinter.X)
        canvas.show()

    def update_data(self, step):
        #self.__figure.clear()
        #self.__prepare_figures()
        #canvas = FigureCanvasTkAgg(self.__figure, master=self.__root)
        #canvas.get_tk_widget().destroy()
        #canvas.get_tk_widget().delete("all")
        t = arange(0.0, 3.0, 0.01)
        s = sin(2 * pi * t + step)
        self.__plot.plot(t, s)
Ejemplo n.º 41
0
 def _setup_figure(self, figure=None):
     """create figure if not supplied; apply the top-level formatting
     """
     attrs    = self.attrs
     if figure is None:
         figure = Figure() #use to create an object oriented only figure which can be gargbage collected
     suptitle = attrs['suptitle']
     if not suptitle is None:
         figure.suptitle(suptitle)
     return figure
Ejemplo n.º 42
0
def quality_control_plot(eid, experiment, plot_dir):
    print('starting quality controlplots')
    plt.style.use('bmh')
    print('set style to bmh')
    fig = Figure(figsize=(16, 10), dpi=100)
    canvas = FigureCanvas(fig)
    # fig = plt.figure(figsize=(16, 10), dpi=500)
    gs = grd.GridSpec(5, 8, wspace=1, hspace=1)

    step_top_ax = fig.add_subplot(gs[1:3, 0:4])
    step_bot_ax = fig.add_subplot(gs[3:5, 0:4])
    squiggle_ax = fig.add_subplot(gs[1:5, 4:8])


    # Set title
    title = '{eid}\n {name}'.format(eid=eid, name=experiment.basename)
    fig.suptitle(title, size=20)

    st = StepPlot(experiment=experiment)
    st.make_figures(ax2=step_top_ax, ax1=step_bot_ax)
    step_top_ax.text(2.9, 0.1, '5 < t < 40 min', fontsize=16,
                     verticalalignment='bottom', horizontalalignment='right',
                     )

    step_bot_ax.text(2.9, 0.1, 't > 40 min', fontsize=16,
                     verticalalignment='bottom', horizontalalignment='right',
                     )

    # Squiggle Plot!
    squiggle_plot(e=experiment, ax=squiggle_ax)

    for ax in [step_top_ax, step_bot_ax, squiggle_ax]:
        ax.set_axis_bgcolor('white')
        # print('fixing axes boarder')
        # ax.axis('on')
        # [i.set_linewidth(0.5) for i in ax.spines.itervalues()]
        # ax.patch.set_visible(True)
        # ax.spines['top'].set_visible(True)
        # ax.spines['right'].set_visible(True)
        # ax.spines['bottom'].set_visible(True)
        # ax.spines['left'].set_visible(True)
        draw_border(ax)

    gs.tight_layout(fig)

    path = pathlib.Path(plot_dir)
    if not path.is_dir():
        path.mkdir()
    name = path / '{eid}-check.png'.format(eid=eid)
    print('Saving figure as {}'.format(name)) 
    #fig.savefig(str(name))
    #plt.close(fig)
    canvas.print_png(str(name))
    print('End!')
Ejemplo n.º 43
0
class MatplotlibWidget(QWidget):
	def __init__(self,parent=None):
		super(MatplotlibWidget,self).__init__(parent)
		self.figure = Figure(figsize=(1,1))
		self.figure.subplots_adjust(left=0.2)
		self.canvas = FigureCanvasQTAgg(self.figure)
		self.axis = self.figure.add_subplot(111,xlim=(0,60),ylim=(0,20))
		self.axis.tick_params(axis='x',labelsize=8)
		self.axis.tick_params(axis='y',labelsize=8)
		self.layoutVertical = QVBoxLayout(self)
		self.layoutVertical.addWidget(self.canvas)
		self.figure.suptitle("Queue Length",fontsize=8)
Ejemplo n.º 44
0
def plot_2_distributions(distribution1,  xlabel1, distribution2,  xlabel2, subject_value1=None, subject_value_label1='',
                           subject_value2=None, subject_value_label2='', title='', figsize=(8.3, 7)):

    fig = Figure(figsize=figsize)
    FigureCanvas(fig)

    gs = GridSpec(2, 1)
    ax = fig.add_subplot(gs[0, 0])
    plot_distribution_of_values(ax, distribution1, xlabel1, subject_value=subject_value1, subject_value_label=subject_value_label1)
    ax = fig.add_subplot(gs[1, 0])
    plot_distribution_of_values(ax, distribution2, xlabel2, subject_value=subject_value2, subject_value_label=subject_value_label2)
    fig.suptitle(title)
    return fig
Ejemplo n.º 45
0
def drawGraph(n, flag, endowments, prices, graphs):
    roundN = len(endowments)

    fig = Figure(figsize=[10, 10])
    fig.suptitle(flag)

    drawEP(fig, n, roundN, endowments, prices)
    drawG(fig, n, roundN, graphs)

    canvas = FigureCanvasAgg(fig)
    filePath = folder + "/" + flag + ".png"
    print 'log: ' + filePath
    canvas.print_figure( filePath )
Ejemplo n.º 46
0
    def finalize(self, key):
        logi = self.instances.pop(key)

        from matplotlib.figure import Figure
        from matplotlib.backends.backend_pdf import FigureCanvasPdf

        fig = Figure(figsize=(6, 8))
        fig.suptitle("%s - order:%d" % (key))
        logi.render(fig)

        FigureCanvasPdf(fig)

        self.pdf.savefig(figure=fig)
Ejemplo n.º 47
0
class MyMplCanvas(FigureCanvas):
    """FigureCanvas的最终的父类其实是QWidget。"""

    def __init__(self, parent=None, width=5, height=4, dpi=100):

        # 配置中文显示
        plt.rcParams['font.family'] = ['SimHei']  # 用来正常显示中文标签
        plt.rcParams['axes.unicode_minus'] = False  # 用来正常显示负号

        self.fig = Figure(figsize=(width, height), dpi=dpi)  # 新建一个figure
        self.axes = self.fig.add_subplot(111)  # 建立一个子图,如果要建立复合图,可以在这里修改

        self.axes.hold(False)  # 每次绘图的时候不保留上一次绘图的结果

        FigureCanvas.__init__(self, self.fig)
        self.setParent(parent)

        '''定义FigureCanvas的尺寸策略,这部分的意思是设置FigureCanvas,使之尽可能的向外填充空间。'''
        FigureCanvas.setSizePolicy(self,
                                   QSizePolicy.Expanding,
                                   QSizePolicy.Expanding)
        FigureCanvas.updateGeometry(self)

    '''绘制静态图,可以在这里定义自己的绘图逻辑'''

    def start_static_plot(self):
        self.fig.suptitle('测试静态图')
        t = arange(0.0, 3.0, 0.01)
        s = sin(2 * pi * t)
        self.axes.plot(t, s)
        self.axes.set_ylabel('静态图:Y轴')
        self.axes.set_xlabel('静态图:X轴')
        self.axes.grid(True)

    '''启动绘制动态图'''

    def start_dynamic_plot(self, *args, **kwargs):
        timer = QtCore.QTimer(self)
        timer.timeout.connect(self.update_figure)  # 每隔一段时间就会触发一次update_figure函数。
        timer.start(1000)  # 触发的时间间隔为1秒。

    '''动态图的绘图逻辑可以在这里修改'''

    def update_figure(self):
        self.fig.suptitle('测试动态图')
        l = [random.randint(0, 10) for i in range(4)]
        self.axes.plot([0, 1, 2, 3], l, 'r')
        self.axes.set_ylabel('动态图:Y轴')
        self.axes.set_xlabel('动态图:X轴')
        self.axes.grid(True)
        self.draw()
Ejemplo n.º 48
0
def plotit( data, outfilename, **kargs ) :

    # going to make a 1 row x N column plot
    if len(data.shape)==1 : 
        num_rows = 1
    else : 
        num_rows = data.shape[1]

    # davep 02-Oct-2012 ; bump up the size to accommodate multiple rows
    fig = Figure()
    figsize = fig.get_size_inches()
#    fig.set_size_inches( (figsize[0],figsize[1]*num_rows) )

    if "title" in kargs : 
        fig.suptitle(kargs["title"])

    # http://matplotlib.org/faq/howto_faq.html
    # "Move the edge of an axes to make room for tick labels"
    # hspace is "the amount of height reserved for white space between
    # subplots"
    fig.subplots_adjust( hspace=0.40 )

    ax = fig.add_subplot(111)
    ax.grid()
    ax.set_ylim(-0.1,1.1)

    label_iter = iter( ("Strip Metric","FullPage Metric","All Strips' Mean"))
    for i in range(num_rows) : 
        if num_rows==1 :
            column = data 
        else : 
            column = data[ :, i ] 

        fmt = kargs.get("fmt","+")
        if "color" in kargs : 
            fmt += kargs["color"]            
        ax.plot(column,fmt,label=label_iter.next())

    if "axis_title" in kargs : 
        title = kargs["axis_title"][i]
        ax.set_title(title)

    ax.legend(loc="lower left")

    ax.set_xlabel( "Strip Number" )
    ax.set_ylabel( "Match Metric" )

    canvas = FigureCanvasAgg(fig)
    canvas.print_figure(outfilename)
    print "wrote", outfilename
Ejemplo n.º 49
0
    def createSpectra(self, xHighlight=None, yHighlight=None, contour=False, index=0):
        """
        Creates a spectragram graph. This function is called from the
        Core class. The spectragram is a three dimensional plot that
        shows current vs cycle vs time.

        @param xHighlight: defaults to none
        @param yHighlight: defaults to none
        @param contour: defaults to false
        @return null
        """

        # haven't touched this yet. will likely add new field in gui to cycle through indexes of spectras

        self.plotInfoStr = self.dataset.getInfo()

        print("Plotting spectra at index:", index)
        f = Figure()
        a = f.add_subplot(111)

        x = np.array(list(self.dataset.getXUnits()))
        y = np.array(range(len(self.dataset.getYUnits())))

        print("---\nsize of x: %i\nsize of y: %i" % (len(x), len(y)))

        X, Y = np.meshgrid(x, y)
        Z = np.array(self.dataset.getPlane()).transpose()

        if self.dataset.logifyY:
            Z = Z + np.abs(Z.min())
            a.pcolormesh(X, Y, Z, norm=matplotlib.colors.LogNorm(vmin=Z.min(), vmax=Z.max()))
        else:
            a.pcolormesh(X, Y, Z)
        bar = matplotlib.cm.ScalarMappable()
        bar.set_array(Z)
        if contour:
            a.contour(X, Y, Z)
        f.colorbar(bar, ax=a, label="Current (Im)")
        f.suptitle(str(self.dataset))

        if xHighlight != None:
            a.axvline(x=xHighlight)
            print("Trying to put bar at " + str(xHighlight))

        if yHighlight != None:
            a.axhline(y=yHighlight)
            print("Trying to put hLine at " + str(yHighlight))

        a.axis([X.min(), X.max(), Y.min(), Y.max()])
        return f
Ejemplo n.º 50
0
    def __init__(self, full_data, segment_data, persistences, kNN) :
        self.kNN = kNN
        self.dataset_name = ""
        if isinstance(full_data.config.data_file, list) :
            self.dataset_name = ", ".join([os.path.split(f)[1] for f in full_data.config.data_file])
        else :
            self.dataset_name = os.path.split(full_data.config.data_file)[1]
        wx.Frame.__init__(self, None, -1, self.dataset_name, size=(550, 550))
        self.full_data = full_data
        self.segment_data = segment_data
        self.persistences = persistences
        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.Bind(wx.EVT_KEY_UP, self.KeyEvent)
        self.label_index = 0
        self.segment_index = 0
        self.labels = list(set([s.max_label() for s in self.full_data.segments]))
        self.colors = dict([(str(l), (random.random(), random.random(), random.random())) for l in self.labels])
        self.figures = []
        for i in range(self.kNN+1) :
            data_figure = Figure()
            data_axes = data_figure.add_subplot(111)
            data_canvas = FigureCanvas(self, -1, data_figure)
            data_title = data_figure.suptitle("Line %s of %s Label %s" % \
                                         (self.segment_index, len(self.full_data.segments),
                                          self.full_data.segments[self.segment_index].max_label()))
            persistence_figure = Figure()
            persistence_axes = persistence_figure.add_subplot(111)
            persistence_canvas = FigureCanvas(self, -1, persistence_figure)
            persistence_title = persistence_figure.suptitle("Persistence Diagram %s of %s window size %s" % \
                                                            (self.segment_index, len(self.full_data.segments),
                                                             self.segment_data.segments[self.segment_index].window_size))
            self.figures.append(dict([("data_figure", data_figure),
                                      ("data_axes", data_axes),
                                      ("data_canvas", data_canvas),
                                      ("data_title", data_title),
                                      ("persistence_figure", persistence_figure),
                                      ("persistence_axes", persistence_axes),
                                      ("persistence_canvas", persistence_canvas),
                                      ("persistence_title", persistence_title)]))
                                      
        self.sizer = wx.GridBagSizer(hgap=5, vgap=5)
        for i in range(self.kNN+1) :
            self.sizer.Add(NavigationToolbar2Wx(self.figures[i]['data_canvas']), pos=(0,(i*2)), span=(1,2), flag=wx.EXPAND)
            self.sizer.Add(self.figures[i]['data_canvas'], pos=(1,(i*2)), span=(8,2), flag=wx.EXPAND)
            self.sizer.Add(self.figures[i]['persistence_canvas'], pos=(9,(i*2)), span=(8,2), flag=wx.EXPAND)

        self.SetSizer(self.sizer)
        self.Fit()
        self.background = self.figures[0]['data_axes'].figure.canvas.copy_from_bbox(self.figures[0]['data_axes'].bbox)
        self.refresh()
Ejemplo n.º 51
0
def per_file_server_status(request):
    '''Displays as separate individual pie charts the 
    free vs used space for each file server.  If there is 
    only one file server this graph will not be rendered
    as it will be identical to the other graphs already shown'''
    fileservers = models.FileServer.objects.all()
    if len(fileservers)>1:
        free_space = []
        used_space = []
        total_space = []
        titles = []
        frac = []
        for fs in fileservers:
            try:
                att = disk_attributes(fs.filesPrefix)
            except OSError:
                continue
            total_space.append(att[1])
            used_space.append(att[1]-att[2])
            free_space.append(att[2])
            titles.append(fs.name)
        frac = [(float(us)/float(ts),float(fs)/float(ts)) for us,fs,ts in zip(used_space,free_space,total_space)]
        labels = ['Used','Free']
        numGraphs = math.ceil(math.sqrt(len(frac)))
        # create figure
        figwidth = 3   # inches
        figheight = 3   # inches
        matplotlib.rcParams['font.size'] = 10.0-math.sqrt(float(numGraphs))
        matplotlib.rcParams['axes.titlesize'] = 14.0-math.sqrt(float(numGraphs))
        matplotlib.rcParams['xtick.labelsize'] = 10.0-math.sqrt(float(numGraphs))
        matplotlib.rcParams['legend.fontsize'] = 10.0-math.sqrt(float(numGraphs))
        explode=(0.05, 0.0)
        colors=('b','g')
        fig = Figure(figsize=(figwidth,figheight))
        for n,(f,t) in enumerate(zip(frac,titles)):
            n = n+1
            ax = fig.add_subplot(numGraphs,numGraphs,n)
            fig.subplots_adjust(wspace=0.5,hspace=0.5,top=0.84)
            ax.pie(f,
                   autopct='%1.f%%',
                   labels=labels)
            ax.set_title('%s' % t)
        fig.suptitle('Free Space/Fileserver',fontsize=15)
        canvas = FigureCanvas(fig)
        response = http.HttpResponse(content_type='image/png')
        canvas.print_png(response)
        return response
    else:
        return http.HttpResponse()
def plot_coefficients(picid, coeffs, psc_dir):
    fig = Figure()
    FigureCanvas(fig)

    fig.set_size_inches(9, 6)
    ax = fig.add_subplot(111)

    ax.plot(coeffs)
    ax.set_xlabel('Reference Index')
    ax.set_ylabel('Coefficient Value')

    fig.suptitle(f'Reference coeffecients - {picid}')

    coeff_fn = os.path.join(psc_dir, 'plots', f'coefficients-{picid}.png')
    fig.savefig(coeff_fn, transparent=False)
Ejemplo n.º 53
0
def plot_mosaic(nifti_file, title=None, overlay_mask=None, bright_mask=False, figsize=(11.7,8.3)):
    if isinstance(nifti_file,str):
        nii = nb.load(nifti_file)
        mean_data = nii.get_data()
    else:
        mean_data = nifti_file
   
    n_images = mean_data.shape[2]
    row, col = _calc_rows_columns(figsize[0]/figsize[1], n_images)
    
    if overlay_mask:
        overlay_data = nb.load(overlay_mask).get_data()

    # create figures
    fig = Figure(figsize=figsize)
    FigureCanvas(fig)
    
    fig.subplots_adjust(top=0.85)
    for image in (range(n_images)):
        ax = fig.add_subplot(row, col, image+1)
        data_mask = np.logical_not(np.isnan(mean_data))
        if overlay_mask:
            ax.set_rasterized(True)
        ax.imshow(np.fliplr(mean_data[:,:,image].T), vmin=np.percentile(mean_data[data_mask], 0.5), 
                   vmax=np.percentile(mean_data[data_mask],99.5), 
                   cmap=cm.Greys_r, interpolation='nearest', origin='lower')  # @UndefinedVariable
        if overlay_mask:
            overlay_data[overlay_data==0]=np.nan
            if bright_mask:
                cmap = cm.rainbow
                cmap._init()
            else:
                cmap = cm.Reds #rainbow #cool #Reds  # @UndefinedVariable
                cmap._init()
                alphas = np.linspace(0, 0.75, cmap.N+3)
                cmap._lut[:,-1] = alphas
            ax.imshow(np.fliplr(overlay_data[:,:,image].T), vmin=0, vmax=1,
                   cmap=cmap, interpolation='nearest', origin='lower')  # @UndefinedVariable
            
        ax.axis('off')
    fig.subplots_adjust(left = 0.05, right = 0.95, bottom = 0.05, top = 0.95, wspace=0.01, hspace=0.1)
    
    if not title:
        _, title = os.path.split(nifti_file)
        title += " (last modified: %s)"%time.ctime(os.path.getmtime(nifti_file))
    fig.suptitle(title, fontsize='13', fontweight='bold')
    
    return fig
Ejemplo n.º 54
0
def plot_convergence_increment(**kwargs):

    steps = extract_steps(**kwargs)
    
    fig = Figure()
    ax = fig.add_subplot(111)
    title = fig.suptitle(kwargs.get('title'), fontsize = 14, fontweight = 'bold')
    canvas = FigureCanvas(fig)

    ax.clear()
    fig.suptitle(title, fontsize=14, fontweight='bold')
    ax.hold(True)
    
    for step in steps:

        if step.status_convergence == 1:

            values_plot = [
                step.iters_nonlinear[x].norm_increment for x in step.iters_nonlinear]

            ax.plot(
                values_plot[1:-1],
                values_plot[2:])

    try:
        ax.set_xscale('log')
        ax.set_yscale('log')
    except:
        ax.set_xscale('linear')
        ax.set_yscale('linear')
    ax.set_xlabel(r'Increment Norm $\left\| \Delta u^{(n)} \right\|$')
    ax.set_ylabel(r'Increment Norm $\left\| \Delta u^{(n+1)} \right\|$')

    string_legend = [str(i + 1) for i in range(len(steps))]

    legend = ax.legend(
        string_legend,
        bbox_to_anchor = (1.05, 1), 
        loc = 2, 
        borderaxespad = 0.,
        fontsize = 15,
        ncol = np.max([1, int(len(string_legend) / 15.)]),
        title = 'Step')

    canvas.print_figure(
        'norm_increment_convergence.pdf',
        bbox_extra_artists = [title, legend],
        bbox_inches = 'tight')
class TkinterGraph(Frame):

    def __init__(self, parent):
        Frame.__init__(self, parent)

        self.figure = Figure(figsize=(10,10), dpi=50)
        self.title= self.figure.suptitle('', fontsize=20)
        self.graph_a = self.figure.add_subplot(111)
        self.graph_a.set_ylabel('ln(numberof filled boxes)')
        self.graph_a.set_xlabel('ln(Box size)')
        
       
        self.canvas = FigureCanvasTkAgg(self.figure, self)
        self.canvas.show()
        self.canvas._tkcanvas.pack(side=TOP)#,fill=BOTH, expand=1)
        

    def change_data(self,data_x,data_y):
        self.graph_a.clear()
        #self.graph_a.scatter(data_x,data_y)
        fit = polyfit(data_x,data_y,1)
        #DEBUG print fit
        self.title.set_text('Fractal dimension: %.3f' % fit[0])
        fit_fn = poly1d(fit)
        self.graph_a.plot(data_x,data_y, 'yo', data_x, fit_fn(data_x), '--k')
        self.canvas.draw()
Ejemplo n.º 56
0
def plot_nonlinear_iterations(**kwargs):

    steps = extract_steps(**kwargs)
    
    fig = Figure()
    ax = fig.add_subplot(111)
    title = fig.suptitle(kwargs.get('title'), fontsize = 14, fontweight = 'bold')
    canvas = FigureCanvas(fig)

    step_numbers = [
        step.step_number for step in steps if step.status_convergence == 1]

    num_iters_nonlinear = [
        step.num_iters_nonlinear for step in steps if step.status_convergence == 1]

    ax.bar(
        step_numbers,
        num_iters_nonlinear)

    ax.set_xlabel('Continuation Step')
    ax.set_ylabel('Nonlinear Iterations')

    set_num_ticks(ax, integer = (True, True))

    canvas.print_figure(
        'nonlinear_iterations.pdf',
        bbox_extra_artists = [title],
        bbox_inches = 'tight')
Ejemplo n.º 57
0
class MathTextLabel(qt.QWidget):
    def __init__(self, mathText, parent=None, **kwargs):
        qt.QWidget.__init__(self, parent, **kwargs)

        l=qt.QVBoxLayout(self)
        l.setContentsMargins(0,0,0,0)

        r,g,b,a=self.palette().base().color().getRgbF()

        self._figure=Figure(edgecolor=(r,g,b), facecolor=(r,g,b))
        self._canvas=FigureCanvas(self._figure)
        l.addWidget(self._canvas)

        self._figure.clear()
        text=self._figure.suptitle(
            mathText,
            x=0.0,
            y=1.0,
            horizontalalignment='left',
            verticalalignment='top',
            size=qt.qApp.font().pointSize()*3)
        self._canvas.draw()
        (x0,y0),(x1,y1)=text.get_window_extent().get_points()
        w=x1-x0; h=y1-y0

        #self._figure.set_size_inches(w/4, h/4)
        self.setFixedSize(w,h)
Ejemplo n.º 58
0
    def createPlotCanvases(self, title):
        # create figure instances to plot on
        figure = Figure(figsize=(5,4), dpi=100)
        
        self.plot = figure.add_subplot(111)
        self.plot.grid(True)
        self.plot.tick_params(axis='x', labelsize=6)
        self.plot.tick_params(axis='y', labelsize=6)

        figure.subplots_adjust(left=0.15, bottom=0.2, right=0.9, top=0.9, wspace=0.2, hspace=0.5)
        
        figure.suptitle(title, fontsize=8)
        # this is the Canvas Widget that displays the `figure`
        self.canvas = FigureCanvas(figure)
        self.canvas.setContentsMargins(110, 50, 50, 50)
        # this is the Navigation widget
        self.toolbar = NavigationToolbar(self.canvas, self)  
Ejemplo n.º 59
0
    def __init__(self, parent=None, width=8, height=4, dpi=100, title=None):

        fig = Figure(figsize=(width, height), dpi=dpi)
        self.axes_top = fig.add_subplot(211)
        self.axes_bottom = fig.add_subplot(212)
        # We want the axes cleared every time plot() is called
        self.axes_top.hold(False)
        self.axes_bottom.hold(False)

        if title != None:
            fig.suptitle(title, fontsize=12)

        FigureCanvas.__init__(self, fig)
        self.setParent(parent)

        FigureCanvas.setSizePolicy(self, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)
        FigureCanvas.updateGeometry(self)
Ejemplo n.º 60
0
def draw_ticker_figure(symbol, fig=None):

    # TODO: Figure() in the keyargs makes it give to same Figure somehow
    # messing things up
    if fig is None:
        fig = Figure()

    """ method to produce a data plot for the ticker """
    # TODO: implementing plot using historical data, could be changed later

    # get the historical data (this is what we will show)
    q = QueryInterface.query_historicaldata("Volume,Open,Close,Date",
                                            symbol)

    if q.count == 0:
        return fig

    # convert to pandas and make the df numerical
    df = q.to_pandas()
    df_make_numerical(df, Historical)

    # start plotting
    fig.suptitle("ticker {} historical data".format(symbol))

    # dates
    x = df['Date']

    # add the Open and Close data
    ax = fig.add_subplot(211)
    ax.plot_date(x, df['Open'], 'b-x', label='Open')
    ax.plot_date(x, df['Close'], 'r-x', label='Close')
    ax.set_ylabel('Open/Close Prices')
    ax.legend()

    # add the volume data
    ax = fig.add_subplot(212)
    ax.plot_date(x, df['Volume'], 'b-x')
    ax.set_ylabel('Volume')

    # make the date axis nice
    ax.xaxis.set_major_formatter(DateFormatter('%Y-%m-%d'))
    fig.autofmt_xdate()
    ax.set_xlabel('Date')

    return fig