def __init__(self, parent=None, width=3, height=3, logger=None):

        sub = SubplotParams(left=0.0,
                            right=1,
                            bottom=0,
                            top=1,
                            wspace=0,
                            hspace=0)
        self.fig = Figure(figsize=(width, height),
                          facecolor='white',
                          subplotpars=sub)
        self.axes = self.fig.add_subplot(111)
        # We want the axes cleared every time plot() is called
        #self.axes.hold(False)
        #self.axes.grid(True)

        self.closed_color = 'black'
        self.open_color = 'white'
        self.onway_color = 'orange'
        self.alarm_color = 'red'

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

        FigureCanvas.setSizePolicy(self, QtGui.QSizePolicy.Expanding, \
                                   QtGui.QSizePolicy.Expanding)
        FigureCanvas.updateGeometry(self)

        # width/hight of widget
        self.w = 250
        self.h = 30
        self.logger = logger

        self.init_figure()
Beispiel #2
0
    def get_subplot_params(self, fig=None):
        """
        return a dictionary of subplot layout parameters.
        """

        if fig is None:
            hspace = rcParams["figure.subplot.hspace"]
            wspace = rcParams["figure.subplot.wspace"]
        else:
            hspace = fig.subplotpars.hspace
            wspace = fig.subplotpars.wspace

        if self._hspace is not None:
            hspace = self._hspace

        if self._wspace is not None:
            wspace = self._wspace

        figbox = self._subplot_spec.get_position(fig, return_all=False)

        left, bottom, right, top = figbox.extents

        from matplotlib.figure import SubplotParams
        sp = SubplotParams(left=left,
                           right=right,
                           bottom=bottom,
                           top=top,
                           wspace=wspace,
                           hspace=hspace)

        return sp
Beispiel #3
0
    def get_subplot_params(self, fig=None):
        """
        return a dictionary of subplot layout parameters. The default
        parameters are from rcParams unless a figure attribute is set.
        """
        from matplotlib.figure import SubplotParams
        if fig is None:
            kw = {k: rcParams["figure.subplot."+k] for k in self._AllowedKeys}
            subplotpars = SubplotParams(**kw)
        else:
            subplotpars = copy.copy(fig.subplotpars)

        update_kw = {k: getattr(self, k) for k in self._AllowedKeys}
        subplotpars.update(**update_kw)

        return subplotpars
Beispiel #4
0
def plot(R, P, c1=None, c2=None, s=500):
    fig, ax = plt.subplots(2, 5, figsize=(15,6), subplotpars=SubplotParams(right=.95, left=.05))
    plt.set_cmap('coolwarm')
    for j in range(2):
        R.lag_regressions(P.PC[j], range(0, 8, 2), pval=.05, plot=False)
        for i in range(4):
            plt.sca(ax[j,3-i])
            if c1 is None:
                pl = R.map.contourf(R._i, R._j, R.regs[i])
                print(pl.get_clim())
            else:
                R.map.contourf(R._i, R._j, R.regs[i], c1)
            R.map.contour(R._i, R._j, R.pvals[i], [0.05], linewidths=[2], colors=['w'])
            R.map.plot(P.map.boundarylons, P.map.boundarylats, latlon=True, color='k')
            R.map.drawcoastlines()
            if j==0:
                plt.title('lag {} days'.format(-R.lags[i]))
        # bb = ax[0,3].get_position()
        # plt.colorbar(cax=fig.add_axes([bb.x1+0.02,bb.y0,0.05,bb.y1-bb.y0]))
        plt.sca(ax[j,4])
        pl = P.map.scatter(*P.sta[['lon','lat']].as_matrix().T,
                      c = P.vectors[:,j],
                      s = np.abs(P.vectors[:,j]) * s,
                      latlon=True)
        P.map.drawcoastlines()
        print(pl.get_clim())
        if c2 is not None:
            plt.clim(-c2, c2)
    fig.show()
    return fig, ax
Beispiel #5
0
def get_subplot_params(figsize):
    """Return sensible default `SubplotParams` for a figure of the given size

    Parameters
    ----------
    figsize : `tuple` of `float`
         the ``(width, height)`` figure size (inches)

    Returns
    -------
    params : `~matplotlib.figure.SubplotParams`
        formatted set of subplot parameters
    """
    from matplotlib.figure import SubplotParams

    width, height, = figsize
    try:
        left, right = SUBPLOT_WIDTH[width]
    except KeyError:
        left = right = None
    try:
        bottom, top = SUBPLOT_HEIGHT[height]
    except KeyError:
        bottom = top = None
    return SubplotParams(left=left, bottom=bottom, right=right, top=top)
Beispiel #6
0
def plotLinearData(time, FeatureMatrix, OSignal, FeatureNames):
    """

	:param time: Time array
	:param FeatureMatrix: Matrix with the arrays of all the features
	:param OSignal: Original Signal
	:param SegmNoise: Array with noise segmentation
	:return: plot object of these params
	"""

    # color
    face_color_r = 248 / 255.0
    face_color_g = 247 / 255.0
    face_color_b = 249 / 255.0

    # pars
    left = 0.05  # the left side of the subplots of the figure
    right = 0.95  # the right side of the subplots of the figure
    bottom = 0.05  # the bottom of the subplots of the figure
    top = 0.92  # the top of the subplots of the figure
    wspace = 0.2  # the amount of width reserved for blank space between subplots
    hspace = 2  # the amount of height reserved for white space between subplots

    pars = SubplotParams(left, bottom, right, top, wspace, hspace)

    #specify Font properties with fontmanager---------------------------------------------------
    font0 = FontProperties()
    font0.set_weight('medium')
    font0.set_family('monospace')
    #Specify Font properties of Legends
    font1 = FontProperties()
    font1.set_weight('normal')
    font1.set_family('sans-serif')
    font1.set_style('italic')
    font1.set_size(12)
    #Specify font properties of Titles
    font2 = FontProperties()
    font2.set_size(15)
    font2.set_family('sans-serif')
    font2.set_weight('medium')
    font2.set_style('italic')
    #Set Figure Size
    MatrixSize = np.shape(FeatureMatrix)
    fig, axes = plt.subplots(MatrixSize[1], 1)
    fig.set_dpi(96)
    fig.set_figheight(1080 / 96)
    fig.set_figwidth(1920 / 96)

    for i in range(0, MatrixSize[1]):

        axes[i].plot(time, FeatureMatrix[:, i] + 1)
        axes[i].plot(time, OSignal)
        axes[i].set_ylabel(" Amplitude (r.u.) ", fontproperties=font1)
        axes[i].set_title("Signal Feature: " + FeatureNames[i],
                          fontproperties=font2)
        axes[i].axis('tight')
        axes[i].axes.get_xaxis().set_visible(False)

    axes[MatrixSize[1] - 1].set_xlabel(" Time (s) ", fontproperties=font1)
    axes[MatrixSize[1] - 1].axes.get_xaxis().set_visible(True)
Beispiel #7
0
def plotEMG3D(cmap, pp):
    # color
    face_color_r = 248 / 255.0
    face_color_g = 247 / 255.0
    face_color_b = 249 / 255.0

    # pars
    left = 0.05  # the left side of the subplots of the figure
    right = 0.95  # the right side of the subplots of the figure
    bottom = 0.05  # the bottom of the subplots of the figure
    top = 0.92  # the top of the subplots of the figure
    wspace = 0.5  # the amount of width reserved for blank space between subplots
    hspace = 0.4  # the amount of height reserved for white space between subplots

    pars = SubplotParams(left, bottom, right, top, wspace, hspace)

    fig1 = plt.figure(subplotpars=pars)
    fig1.set_facecolor((face_color_r, face_color_g, face_color_b))
    fig1.set_dpi(96)
    fig1.set_figheight(1080 / 96)
    fig1.set_figwidth(1920 / 96)
    fig1.suptitle("Analysis of the Beginning and End of the Spectrum")
    x = np.linspace(0, len(cmap[0]) / 1000, len(cmap[0]))
    y = np.linspace(5, len(cmap) + 5, len(cmap))
    X, Y = np.meshgrid(x, y)
    ax = p3.Axes3D(fig1)
    ax.plot_surface(X, Y, cmap, cmap=cm.hot)
    ax.set_xlabel('Time (s)')
    ax.set_ylabel('Frequency (Hz)')
    ax.set_zlabel('Amplitude (r.u.)')

    pp.savefig(fig1)
    # Release Memory.
    plt.close(fig1)
def _plot_geometry(geom, fill='#ffcccc', stroke='#333333', alpha=1, msg=None):
    from matplotlib import pyplot
    from matplotlib.figure import SubplotParams
    from descartes import PolygonPatch

    if isinstance(geom, (Polygon, MultiPolygon)):
        b = geom.bounds
        geoms = hasattr(geom, 'geoms') and geom.geoms or [geom]
        w, h = (b[2] - b[0], b[3] - b[1])
        ratio = w / h
        pad = 0.15
        fig = pyplot.figure(1,
                            figsize=(5, 5 / ratio),
                            dpi=110,
                            subplotpars=SubplotParams(left=pad,
                                                      bottom=pad,
                                                      top=1 - pad,
                                                      right=1 - pad))
        ax = fig.add_subplot(111, aspect='equal')
        for geom in geoms:
            patch1 = PolygonPatch(geom,
                                  linewidth=0.5,
                                  fc=fill,
                                  ec=stroke,
                                  alpha=alpha,
                                  zorder=0)
            ax.add_patch(patch1)
    p = (b[2] - b[0]) * 0.03  # some padding
    pyplot.axis([b[0] - p, b[2] + p, b[3] + p, b[1] - p])
    pyplot.grid(True)
    if msg:
        fig.suptitle(msg, y=0.04, fontsize=9)
    pyplot.show()
def _plot_lines(lines):
    from matplotlib import pyplot

    def plot_line(ax, line):
        filtered = []
        for pt in line:
            if not pt.deleted:
                filtered.append(pt)
        if len(filtered) < 2:
            return
        ob = LineString(line)
        x, y = ob.xy
        ax.plot(x,
                y,
                '-',
                color='#333333',
                linewidth=0.5,
                solid_capstyle='round',
                zorder=1)

    fig = pyplot.figure(1,
                        figsize=(4, 5.5),
                        dpi=90,
                        subplotpars=SubplotParams(left=0,
                                                  bottom=0.065,
                                                  top=1,
                                                  right=1))
    ax = fig.add_subplot(111, aspect='equal')
    for line in lines:
        plot_line(ax, line)
    pyplot.grid(False)
    ax.xaxis.set_visible(False)
    ax.yaxis.set_visible(False)
    ax.set_frame_on(False)
    return (ax, fig)
Beispiel #10
0
def cycles():
    B = dict(rh.iteritems())
    B.update({'obs': RH})
    B = pd.Panel(B)
    fig = plt.figure(figsize=(10, 6), subplotpars=SubplotParams(left=.08))
    for k in range(2):
        sm = cm.ScalarMappable(
            norm=colors.Normalize(vmin=0, vmax={
                0: 30,
                1: 60
            }[k]))
        for j, s in enumerate(['obs', 'd02', 'd03_0_00', 'd03_0_12']):
            ax = plt.subplot(2, 4, 4 * k + j + 1)
            if k == 0: ax.set_title(s)
            b = B[s].apply(partial(pow, {0: 24 * 365.25, 1: 24}[k])).dropna()
            D = pd.concat((sta.loc[b.index, ('lon', 'lat')], b),
                          axis=1).dropna()
            sm.set_array(D.iloc[:, -1])
            sm.set_cmap('gnuplot')
            for i, a in D.iterrows():
                map.plot(a['lon'],
                         a['lat'],
                         'o',
                         color=sm.to_rgba(a.iloc[-1]),
                         latlon=True)
            map.drawcoastlines()
            map.drawparallels(range(-32, -28, 1),
                              labels=[max(0, 1 - j), 0, 0, 0])
            map.drawmeridians(range(-72, -69, 1), labels=[0, 0, 0, k])
            if j == 3:
                bb = ax.get_position()
                ax = fig.add_axes([bb.x1 + 0.02, bb.y0, 0.02, bb.y1 - bb.y0])
                plt.colorbar(sm, cax=ax)
Beispiel #11
0
    def __init__(self, parent=None, width=1, height=1, logger=None):

        sub=SubplotParams(left=0.0, bottom=0, right=1, \
                          top=1, wspace=0, hspace=0)
        self.fig = Figure(figsize=(width, height), facecolor='white', \
                          subplotpars=sub)
        self.axes = self.fig.add_subplot(111)
        # We want the axes cleared every time plot() is called
        #self.axes.hold(False)
        #self.axes.grid(True)

        # y axis values. these are fixed values.
        self.y_axis = [-1, 0, 1]
        self.center_y = 0.0

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

        FigureCanvas.setSizePolicy(self, QtGui.QSizePolicy.Expanding, \
                                   QtGui.QSizePolicy.Expanding)
        FigureCanvas.updateGeometry(self)

        # width/hight of widget
        self.w = 500
        self.h = 50

        self.logger = logger

        self.init_figure()
Beispiel #12
0
def _debug_show_features(features, message=None):
    from descartes import PolygonPatch
    from matplotlib import pyplot
    from matplotlib.figure import SubplotParams

    fig = pyplot.figure(1, figsize=(9, 5.5), dpi=110, subplotpars=SubplotParams(left=0, bottom=0.065, top=1, right=1))
    ax = fig.add_subplot(111, aspect='equal')
    b = (100000, 100000, -100000, -100000)
    for feat in features:
        if feat.geom is None:
            continue
        c = feat.geom.bounds
        b = (min(c[0], b[0]), min(c[1], b[1]), max(c[2], b[2]), max(c[3], b[3]))
        geoms = hasattr(feat.geom, 'geoms') and feat.geom.geoms or [feat.geom]
        for geom in geoms:
            patch1 = PolygonPatch(geom, linewidth=0.25, fc='#ddcccc', ec='#000000', alpha=0.75, zorder=0)
            ax.add_patch(patch1)
    p = (b[2] - b[0]) * 0.05  # some padding
    pyplot.axis([b[0] - p, b[2] + p, b[3], b[1] - p])
    ax.xaxis.set_visible(False)
    ax.yaxis.set_visible(False)
    ax.set_frame_on(True)
    if message:
        fig.suptitle(message, y=0.04, fontsize=9)
    pyplot.show()
Beispiel #13
0
    def get_subplot_params(self, fig=None):
        """
        return a dictionary of subplot layout parameters. The default
        parameters are from rcParams unless a figure attribute is set.
        """
        from matplotlib.figure import SubplotParams
        import copy
        if fig is None:
            kw = {k: rcParams["figure.subplot."+k] for k in self._AllowedKeys}
            subplotpars = SubplotParams(**kw)
        else:
            subplotpars = copy.copy(fig.subplotpars)

        update_kw = {k: getattr(self, k) for k in self._AllowedKeys}
        subplotpars.update(**update_kw)

        return subplotpars
Beispiel #14
0
    def __changePlotWidget(self):
        """
        When plot widget is change (qwt <-> matplotlib)
        """
        self.__activateMouseTracking(False)
        while self.__frameLayout.count():
            child = self.__frameLayout.takeAt(0)
            child.widget().deleteLater()
        self.__plotWdg = None

        if self.__lib == 'Qwt5':
            self.__plotWdg = QwtPlot(self.__plotFrame)
            sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
            sizePolicy.setHorizontalStretch(10)
            sizePolicy.setVerticalStretch(0)
            self.__plotWdg.setSizePolicy(sizePolicy)
            self.__plotWdg.setAutoFillBackground(False)
            # Decoration
            self.__plotWdg.setCanvasBackground(Qt.white)
            self.__plotWdg.plotLayout().setAlignCanvasToScales(False)
            self.__plotWdg.plotLayout().setSpacing(100)
            self.__plotWdg.plotLayout().setCanvasMargin(10, QwtPlot.xBottom)
            self.__plotWdg.plotLayout().setCanvasMargin(10, QwtPlot.yLeft)
            title = QwtText(QCoreApplication.translate("VDLTools", "Distance [m]"))
            title.setFont(QFont("Helvetica", 10))
            self.__plotWdg.setAxisTitle(QwtPlot.xBottom, title)
            title.setText(QCoreApplication.translate("VDLTools", "Elevation [m]"))
            title.setFont(QFont("Helvetica", 10))
            self.__plotWdg.setAxisTitle(QwtPlot.yLeft, title)
            self.__zoomer = QwtPlotZoomer(QwtPlot.xBottom, QwtPlot.yLeft, QwtPicker.DragSelection, QwtPicker.AlwaysOff,
                                          self.__plotWdg.canvas())
            self.__zoomer.setRubberBandPen(QPen(Qt.blue))
            grid = QwtPlotGrid()
            grid.setPen(QPen(QColor('grey'), 0, Qt.DotLine))
            grid.attach(self.__plotWdg)
            self.__frameLayout.addWidget(self.__plotWdg)

        elif self.__lib == 'Matplotlib':
            # __plotWdg.figure : matplotlib.figure.Figure
            fig = Figure((1.0, 1.0), linewidth=0.0, subplotpars=SubplotParams(left=0, bottom=0, right=1, top=1,
                                                                              wspace=0, hspace=0))

            font = {'family': 'arial', 'weight': 'normal', 'size': 12}
            rc('font', **font)

            rect = fig.patch
            rect.set_facecolor((0.9, 0.9, 0.9))

            self.__axes = fig.add_axes((0.07, 0.16, 0.92, 0.82))
            self.__axes.set_xbound(0, 1000)
            self.__axes.set_ybound(0, 1000)
            self.__manageMatplotlibAxe(self.__axes)
            self.__plotWdg = FigureCanvasQTAgg(fig)
            sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
            sizePolicy.setHorizontalStretch(0)
            sizePolicy.setVerticalStretch(0)
            self.__plotWdg.setSizePolicy(sizePolicy)
            self.__frameLayout.addWidget(self.__plotWdg)
Beispiel #15
0
def _create_mock_axes():
    image_axes = MagicMock()
    image_axes.figure.subplotpars = SubplotParams(0.125, 0.11, 0.9, 0.88, 0.2,
                                                  0.2)
    image_axes.get_xlim.return_value = (-1, 1)
    image_axes.get_ylim.return_value = (-3, 3)
    image_axes.get_xlabel.return_value = 'x'
    image_axes.get_ylabel.return_value = 'y'
    return image_axes
Beispiel #16
0
    def __init__(self,
                 parent=None,
                 title='Limit',
                 width=5,
                 height=5,
                 alarm=[0, 0],
                 warn=[0, 0],
                 limit=[0, 0],
                 marker=0.0,
                 marker_txt='',
                 logger=None):

        sub = SubplotParams(left=0.05, right=0.95, wspace=0, hspace=0)
        self.fig = Figure(figsize=(width, height),
                          facecolor='white',
                          subplotpars=sub)
        self.axes = self.fig.add_subplot(111)
        # We want the axes cleared every time plot() is called
        #self.axes.hold(False)
        #self.axes.grid(True)

        self.title = title
        self.limit_low = min(limit)
        self.limit_high = max(limit)
        self.alarm_low = min(alarm)
        self.alarm_high = max(alarm)
        self.warn_low = min(warn)
        self.warn_high = max(warn)
        self.marker = marker
        self.marker_txt = marker_txt

        self.cur_color = 'green'
        self.cmd_color = 'blue'
        self.warn_color = 'orange'
        self.alarm_color = 'red'

        # y axis values. these are fixed values.
        self.y_axis = [-1, 0.0, 1]
        self.center_y = 0.0
        self.init_x = 0.0  # initial value of x

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

        FigureCanvas.setSizePolicy(self, QtGui.QSizePolicy.Expanding,
                                   QtGui.QSizePolicy.Expanding)
        FigureCanvas.updateGeometry(self)

        # width/hight of widget
        self.w = 350
        self.h = 80
        self.logger = logger

        self.init_figure()
Beispiel #17
0
def cycles():
    fig = plt.figure(
        figsize=(10, 8),
        subplotpars=SubplotParams(
            left=.1, right=.96, bottom=.06, top=.92, wspace=.1, hspace=.12))
    for k in range(4):
        for j in range(5):
            ax = plt.subplot(4, 5, k * 5 + j + 1)
            if j == 0: B = T
            else:
                x = Tm.minor_axis[j - 1]
                B = Tm.minor_xs(x).dropna(0, 'all')
            if k == 0:
                ax.set_title('obs') if j == 0 else ax.set_title(x)
                b = B.groupby(B.index.month).mean()
                c = b.max() - b.min()
                sm = cm.ScalarMappable(norm=colors.Normalize(
                    vmin=c.min(), vmax=c.max()))
                sm.set_cmap('gnuplot')
            elif k == 1:
                b = B.groupby(B.index.month).mean()
                c = b.idxmax().dropna().astype(int)
                sm = cm.ScalarMappable(norm=colors.Normalize(vmin=1, vmax=12))
                sm.set_cmap('hsv')
            elif k == 2:
                b = B.groupby(B.index.month).std()
                c = b.mean()
                sm = cm.ScalarMappable(norm=colors.Normalize(
                    vmin=c.min(), vmax=c.max()))
                sm.set_cmap('gnuplot')
            else:
                b = B.groupby(B.index.month).std()
                c = b.max() - b.min()
                sm = cm.ScalarMappable(norm=colors.Normalize(
                    vmin=c.min(), vmax=c.max()))
                sm.set_cmap('gnuplot')

            D = pd.concat(
                (sta.loc[c.index, ('lon', 'lat')], c), axis=1).dropna()
            sm.set_array(D.iloc[:, -1])

            for i, a in D.iterrows():
                map.plot(
                    a['lon'],
                    a['lat'],
                    'o',
                    color=sm.to_rgba(a.iloc[-1]),
                    latlon=True)
            map.drawcoastlines()
            map.drawparallels(
                range(-32, -28, 1), labels=[max(1 - j, 0), 0, 0, 0])
            map.drawmeridians(
                range(-72, -69, 1), labels=[0, 0, 0, max(k - 2, 0)])
            plt.colorbar(sm)
Beispiel #18
0
def subplot_pars():
    # pars
    left = 0.05  # the left side of the subplots of the figure
    right = 0.95  # the right side of the subplots of the figure
    bottom = 0.05  # the bottom of the subplots of the figure
    top = 0.92  # the top of the subplots of the figure
    wspace = 0.2  # the amount of width reserved for blank space between subplots
    hspace = 2  # the amount of height reserved for white space between subplots

    pars = SubplotParams(left, bottom, right, top, wspace, hspace)

    return pars
Beispiel #19
0
def _create_mock_axes():
    image_axes = MagicMock()
    image_axes.figure.subplotpars = SubplotParams(0.125, 0.11, 0.9, 0.88, 0.2,
                                                  0.2)
    image_axes.get_xlim.return_value = (-1, 1)
    image_axes.get_ylim.return_value = (-3, 3)
    image_axes.get_xlabel.return_value = 'x'
    image_axes.get_ylabel.return_value = 'y'
    image_axes.xaxis.get_label().set_visible.return_value = MagicMock()
    image_axes.yaxis.get_label().set_visible.return_value = MagicMock()
    image_axes.tick_params.return_value = MagicMock()

    return image_axes
def Regression_sin():
    # 生成训练数据
    n_dots = 200
    X = np.linspace(-2 * np.pi, 2 * np.pi, n_dots)
    Y = np.sin(X) + 0.2 * np.random.rand(n_dots) - 0.1
    # 把一个n维向量转换成一个n*1维的矩阵
    X = X.reshape(-1, 1)
    Y = Y.reshape(-1, 1)

    # 分别用2/3/5/10阶多项式来拟合数据集
    degrees = [2, 3, 5, 10]
    results = []
    for d in degrees:
        model = polynomial_model(degree=d)
        model.fit(X, Y)
        train_score = model.score(X, Y)
        mse = mean_squared_error(Y, model.predict(X))
        results.append({
            "model": model,
            "degree": d,
            "score": train_score,
            "mse": mse
        })
    for r in results:
        print("degree: {}; train score: {}; mean squared error: {}".format(
            r["degree"], r["score"], r["mse"]))

    # 绘制不同阶数的多项式的拟合效果
    plt.figure(figsize=(12, 6), dpi=200, subplotpars=SubplotParams(hspace=0.3))
    for i, r in enumerate(results):
        fig = plt.subplot(2, 2, i + 1)
        plt.xlim(-8, 8)
        plt.title("LinearRegression degree={}".format(r["degree"]))
        plt.scatter(X, Y, s=5, c='b', alpha=0.5)
        plt.plot(X, r["model"].predict(X), 'r-')
    plt.show()

    # 绘制10阶模型在[-20,20]的区域内的曲线
    plt.figure(figsize=(12, 6), dpi=200)
    X = np.linspace(-20, 20, 2000).reshape(-1, 1)
    Y = np.sin(X).reshape(-1, 1)
    model_10 = results[3]["model"]
    plt.xlim(-20, 20)
    plt.ylim(-2, 2)
    plt.plot(X, Y, 'b-')
    plt.plot(X, model_10.predict(X), 'r-')
    dot1 = [-2 * np.pi, 0]
    dot2 = [2 * np.pi, 0]
    plt.scatter(dot1[0], dot1[1], s=50, c='r')
    plt.scatter(dot2[0], dot2[1], s=50, c='r')
    plt.show()
Beispiel #21
0
 def setupCanvas(self):
     self.f = Figure(figsize=(5, 4),
                     dpi=100,
                     subplotpars=SubplotParams(left=0.06,
                                               top=0.95,
                                               right=0.97,
                                               bottom=0.1))
     self.setupSubplots()
     self.canvas = FigureCanvas(self.f)
     #self.canvas.show()
     self.lower_vbox.pack_start(self.canvas)
     #self.canvas.get_tk_widget().pack(side=TOP, fill=BOTH, expand=1)
     self.toolbar = NavigationToolbar(self.canvas, self.window)
     self.lower_vbox.pack_start(self.toolbar, False, False)
Beispiel #22
0
def plotBurst3D(cmapB, cmapE, pp, maxT, nbr):
    # color
    face_color_r = 248 / 255.0
    face_color_g = 247 / 255.0
    face_color_b = 249 / 255.0

    # pars
    left = 0.05  # the left side of the subplots of the figure
    right = 0.95  # the right side of the subplots of the figure
    bottom = 0.05  # the bottom of the subplots of the figure
    top = 0.92  # the top of the subplots of the figure
    wspace = 0.5  # the amount of width reserved for blank space between subplots
    hspace = 0.4  # the amount of height reserved for white space between subplots

    pars = SubplotParams(left, bottom, right, top, wspace, hspace)

    fig1 = plt.figure(subplotpars=pars)
    fig1.set_facecolor((face_color_r, face_color_g, face_color_b))
    fig1.set_dpi(96)
    fig1.set_figheight(1080 / 96)
    fig1.set_figwidth(1920 / 96)
    fig1.suptitle("Analysis of the Beginning and End of the Spectrum " + "(Average sets of " + str(nbr) + " Scalogram)")

    x = np.linspace(0, 100, len(cmapB[0]))
    y = np.linspace(5, len(cmapB) + 5, len(cmapB))
    X, Y = np.meshgrid(x, y)

    ax1 = fig1.add_subplot(1, 2, 1, projection='3d')
    im1 = ax1.plot_surface(X, Y, cmapB / maxT, cmap=cm.hot, vmin=0, vmax=maxT / maxT)
    ax1.set_xlabel('Pedal Cycle (%)')
    ax1.set_ylabel('Frequency (Hz)')
    ax1.set_zlabel('Amplitude (r.u.)')

    ax2 = fig1.add_subplot(1, 2, 2, projection='3d')
    im2 = ax2.plot_surface(X, Y, cmapE / maxT, cmap=cm.hot, vmin=0, vmax=maxT / maxT)
    ax2.set_xlabel('Pedal Cycle (%)')
    ax2.set_ylabel('Frequency (Hz)')
    ax2.set_zlabel('Amplitude (r.u.)')

    if np.max(cmapE) > np.max(cmapB):
        fig1.colorbar(im2, ax=ax2)
        fig1.colorbar(im2, ax=ax1)
    else:
        fig1.colorbar(im1, ax=ax1)
        fig1.colorbar(im1, ax=ax2)

    pp.savefig(fig1)
    # Release Memory.
    plt.close(fig1)
Beispiel #23
0
    def __init__(self, parent=None, width=1, height=1, dpi=None, logger=None):

        #        sub  =SubplotParams(left=0, bottom=0.234, right=1, \
        #                            top=0.998, wspace=0, hspace=0)

        sub = SubplotParams(left=0, bottom=0.03, right=1, \
                            top=1, wspace=0, hspace=0)

        self.fig = Figure(figsize=(width, height), facecolor='white', \
                          subplotpars=sub)

        #self.fig = Figure(figsize=(width, height), dpi=dpi, facecolor='white')
        #self.fig = Figure(facecolor='white')
        self.axes = self.fig.add_subplot(111)
        # We want the axes cleared every time plot() is called
        #self.axes.hold(False)
        #self.axes.grid(True)

        self.limit = [-14.5, 14.5]

        self.wind = 'blue'
        self.normal = 'green'
        self.warn = 'orange'
        self.alarm = 'red'

        # y axis values. these are fixed values.
        self.x_axis = [0, 1]
        self.y_axis = [-14.5, 14.5]
        self.center_x = 0.5
        self.init_x = 0.0  # initial value of x

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

        #FigureCanvas.setSizePolicy(self, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)
        FigureCanvas.updateGeometry(self)

        # width/hight of widget
        self.w = 125
        self.h = 450
        #FigureCanvas.resize(self, self.w, self.h)

        # top screen lenght/width
        self.len = 6
        self.width = 0.1

        self.logger = logger

        self.init_figure()
Beispiel #24
0
def mae_maps():
    cols = ['fnl', 'd01', 'd02', 'd03_orl', 'd03_0_00', 'd03_0_12']
    ncols = len(cols)
    cmin = np.zeros((3, ncols))
    cmax = cmin.copy()
    p = [[], [], []]
    fig, axs = plt.subplots(
        3,
        ncols,
        figsize=(10, 8),
        subplotpars=SubplotParams(
            left=0.08, right=0.86, wspace=0.06, hspace=0.04))
    for j, x in enumerate(cols):
        B = (Tm[x] - T).dropna(0, 'all')
        dz = sta['elev'] - Z[z[x]]
        axs[0, j].set_title(x)
        for k in range(3):
            plt.sca(axs[k, j])
            if k == 0:
                b = abs(B).mean().dropna()
                D = pd.concat(
                    (sta.loc[b.index, ('lon', 'lat')], b), axis=1).dropna()
            elif k == 1:
                b = abs(B - 0.0065 * dz).mean().dropna()
                D = pd.concat((sta.loc[:, ('lon', 'lat')], b), axis=1).dropna()
            else:
                b = abs(B - B.mean()).mean().dropna()
                D = pd.concat((sta.loc[:, ('lon', 'lat')], b), axis=1).dropna()

            cmin[k, j] = min(b)
            cmax[k, j] = max(b)
            print('{} {}'.format(b.max(), b.min()))
            lon, lat, c = D.as_matrix().T
            plt.set_cmap('gnuplot')
            p[k].append(ma.scatter(lon, lat, c=c, latlon=True))
            ma.drawcoastlines()
            ma.drawparallels(
                range(-32, -28, 1), labels=[max(1 - j, 0), 0, 0, 0])
            ma.drawmeridians(
                range(-72, -69, 1), labels=[0, 0, 0, max(k - 1, 0)])
            if j == ncols - 1:
                for i in range(ncols):
                    p[k][i].set_clim((min(cmin[k, :]), max(cmax[k, :])))
                bb = axs[k, j].get_position()
                plt.colorbar(
                    p[k][j],
                    cax=fig.add_axes(
                        [bb.x1 + 0.02, bb.y0, 0.02, bb.y1 - bb.y0]))
    fig.show()
Beispiel #25
0
 def _init_widgets(self):
     sp_params = SubplotParams(0, 0, 1, 1)
     self.figure = Figure(frameon=False, subplotpars=sp_params)
     self.axes = self.figure.add_subplot(111)
     self.canvas = BBoxCanvas(self.figure)
     self.json_view = InputJsonWidget(self.schema_type(), parent=self)
     self.rerun_button = QtWidgets.QPushButton("Reprocess Frame",
                                               parent=self)
     self.pupil_radio = QtWidgets.QRadioButton("Pupil BBox", parent=self)
     self.cr_radio = QtWidgets.QRadioButton("CR BBox", parent=self)
     self.slider = QtWidgets.QSlider(parent=self)
     self.slider.setMinimum(0)
     self.slider.setOrientation(QtCore.Qt.Horizontal)
     self._connect_signals()
     self._init_layout()
Beispiel #26
0
 def __init__(self, aln, name=None, div=0.25, overview=True):
     if isinstance(aln, MultipleSeqAlignment):
         self.aln = aln
     else:
         self.aln = align.read(aln)
     self.name = name
     self.div_value = div
     pars = SubplotParams(
         left=0.2, right=1, bottom=0.05, top=1, wspace=0.01
         )
     fig = pyplot.figure(subplotpars=pars, facecolor="white")
     self.figure = fig
     self.initialize_subplots(overview)
     self.show()
     self.connect_events()
Beispiel #27
0
	def makeGraph(self):
		
		#Set up plotting objects
		##################################
		sp = SubplotParams(left=0.,bottom=0.,right=1.,top=1.); 
		fig = Figure(subplotpars=sp); 
		canvas = FigureCanvas(fig); 
		ax = fig.add_subplot(111); 

		#Get Data
		##################################
		genes = self.model.getGenes(); 
		tmp = {'Empty':0,'Half':0,'Full':0}
		for g in genes:
			if(g[0] == 0 and g[1] == 0):
				tmp['Empty'] += 1; 
			elif((g[0] == 0 and g[1] == 1) or (g[0] == 1 and g[1] == 0)):
				tmp['Half'] += 1; 
			elif(g[0] == 1 and g[1] == 1):
				tmp['Full'] += 1; 

		for key in tmp.keys():
			self.stateTrace[key].append(tmp[key]); 


		colors = {'Empty':'r','Half':'y','Full':'g'}; 
		sizeHintX = 0; 
		for key in self.stateTrace.keys():
			ax.plot(self.stateTrace[key],c=colors[key],linewidth = 3); 
			sizeHintX = 5*len(self.stateTrace[key])/4
		ax.axhline(0); 
		ax.axhline(len(genes)); 

		ax.set_xlim([0,int(sizeHintX)]); 
		ax.set_ylim([-3,len(genes)+3]); 
		

		canvas.draw(); 

		#canvas = makeBeliefMap(wind); 
		size = canvas.size(); 
		width,height = size.width(),size.height(); 
		im = QImage(canvas.buffer_rgba(),width,height,QtGui.QImage.Format_ARGB32); 
		im = im.rgbSwapped(); 
		pm = QPixmap(im); 
		pm = pm.scaled(150*4,150*3);

		self.graphPixmap.setPixmap(pm); 
Beispiel #28
0
    def __init__(self, parent=None, width=1, height=1, dpi=None, logger=None):

        sub=SubplotParams(left=0.0, bottom=0, right=0.999, \
                          top=1, wspace=0, hspace=0)
        self.fig = Figure(figsize=(width, height), \
                          facecolor='white', subplotpars=sub)

        #self.fig = Figure(figsize=(width, height), dpi=dpi, facecolor='white')
        #self.fig = Figure(facecolor='white')
        self.axes = self.fig.add_subplot(111)
        # We want the axes cleared every time plot() is called
        #self.axes.hold(False)
        #self.axes.grid(True)

        self.limit_low = 0.0
        self.limit_high = 90.0

        self.alarm_high = 89.5
        self.alarm_low = 10.0

        self.warn_high = 89.0
        self.warn_low = 15.0

        self.normal_color = 'green'
        self.warn_color = 'orange'
        self.alarm_color = 'red'

        # y axis values. these are fixed values.
        #self.x_scale=[-0.007, 1.0]
        #self.y_scale=[-0.002,  1.011]

        self.x_scale = [-0.001, 1.0]
        self.y_scale = [0.0, 1.0055]

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

        #FigureCanvas.setSizePolicy(self, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)
        #FigureCanvas.updateGeometry(self)

        # width/hight of widget
        self.w = 250
        self.h = 250
        #FigureCanvas.resize(self, self.w, self.h)

        self.logger = logger

        self.init_figure()
Beispiel #29
0
    def ColourMap(self, img):

        sp = SubplotParams(left=0., bottom=0., right=1., top=1.)
        fig = Figure((1, 1), subplotpars=sp)
        canvas = FigureCanvas(fig)
        ax = fig.add_subplot(111)

        ax.imshow(self.img_read)

        ax.set_axis_off()
        canvas.draw()
        size = canvas.size()
        width, height = size.width(), size.height()
        im = QImage(canvas.buffer_rgba(), width, height, QImage.Format_ARGB32)

        return QPixmap(im)
Beispiel #30
0
def _set_gridspec(fig, **gridspec_kw):
    """
    Utility for setting up gridspec

    :param fig: Figure instance

    :param gridspec_kw: dictionary of keywords for gridspec/subplotparams
    """
    gridkw = ['left', 'bottom', 'right', 'top', 'wspace', 'hspace']
    if any([thing in gridspec_kw.keys() for thing in gridkw]):
        from matplotlib.figure import SubplotParams
        spkw = {}
        for thing in gridkw:
            spkw[thing] = gridspec_kw.pop(thing, None)
        sp = SubplotParams(**spkw)
        fig.set_subplotpars(sp)
Beispiel #31
0
def makeBeliefMap(wind):

    [x, y,
     c] = wind.assumedModel.belief.plot2D(low=[0, 0],
                                          high=[wind.imgWidth, wind.imgHeight],
                                          vis=False)
    sp = SubplotParams(left=0., bottom=0., right=1., top=1.)
    fig = Figure(subplotpars=sp)
    canvas = FigureCanvas(fig)
    ax = fig.add_subplot(111)
    ax.contourf(np.transpose(c), cmap='viridis', alpha=1)
    ax.invert_yaxis()
    ax.set_axis_off()

    canvas.draw()
    return canvas