Python matplotlib.pyplot.autoscale() Examples

The following are code examples for showing how to use matplotlib.pyplot.autoscale(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: sthlm-bostad-vis   Author: ashwinvis   File: sssb.py    GNU General Public License v3.0 6 votes vote down vote up
def plot_hist(self, save=True, **kwargs):
        plt.style.use("ggplot")
        self.df_hist.iloc[:, 1:].plot(kind="bar", stacked=True, **kwargs)
        plt.subplots_adjust(left=0.075, bottom=0.4, right=0.83, top=0.95)

        plt.legend(loc="best", fontsize=8, bbox_to_anchor=(1.01, 1.0))
        plt.ylabel("Max. credit days")
        plt.autoscale()

        my_credit_days = (date.today() - self.member_since).days
        plt.axhline(y=my_credit_days)

        if save:
            figname = os.path.join(self.path, self._tag + ".png")
            print("Saving", figname)
            plt.savefig(figname)
        else:
            plt.show() 
Example 2
Project: toulouse-road-network-dataset   Author: davide-belli   File: utils.py    MIT License 6 votes vote down vote up
def full_frame(plt, width=0.64, height=0.64):
    r"""
    Generates a particular tight layout for Pyplot plots
    
    :param plt: pyplot
    :param width: width, default is 64 pixels
    :param height: height, default is 64 pixels
    :return:
    """
    import matplotlib as mpl
    mpl.rcParams['savefig.pad_inches'] = 0
    figsize = None if width is None else (width, height)
    fig = plt.figure(figsize=figsize)
    ax = plt.axes([0, 0, 1, 1], frameon=False)
    ax.get_xaxis().set_visible(False)
    ax.get_yaxis().set_visible(False)
    plt.autoscale(tight=True) 
Example 3
Project: ble5-nrf52-mac   Author: tomasero   File: test_axes.py    MIT License 6 votes vote down vote up
def test_use_sticky_edges():
    fig, ax = plt.subplots()
    ax.imshow([[0, 1], [2, 3]], origin='lower')
    assert_allclose(ax.get_xlim(), (-0.5, 1.5))
    assert_allclose(ax.get_ylim(), (-0.5, 1.5))
    ax.use_sticky_edges = False
    ax.autoscale()
    xlim = (-0.5 - 2 * ax._xmargin, 1.5 + 2 * ax._xmargin)
    ylim = (-0.5 - 2 * ax._ymargin, 1.5 + 2 * ax._ymargin)
    assert_allclose(ax.get_xlim(), xlim)
    assert_allclose(ax.get_ylim(), ylim)
    # Make sure it is reversible:
    ax.use_sticky_edges = True
    ax.autoscale()
    assert_allclose(ax.get_xlim(), (-0.5, 1.5))
    assert_allclose(ax.get_ylim(), (-0.5, 1.5)) 
Example 4
Project: skultrafast   Author: Tillsten   File: plot_helpers.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def plot_spec(tup, t_list, ax=None, norm=False, **kwargs):
    if ax is None:
        ax = plt.gca()
    wl, t, d = tup.wl, tup.t, tup.data
    li = []
    for i in t_list:
        idx = dv.fi(t, i)
        dat = d[idx, :]
        if norm:
            dat = dat / abs(dat).max()
        li += ax.plot(wl, dat, label=time_formatter(t[idx], time_unit), **kwargs)

    #ulim = np.percentile(plotted_vals, 98.) + 0.1
    #llim = np.percentile(plotted_vals, 2.) - 0.1
    ax.set_xlabel(freq_label)
    ax.set_ylabel(sig_label)
    ax.autoscale(1, 'x', 1)
    ax.axhline(0, color='k', lw=0.5, zorder=1.9)
    ax.legend(loc='best', ncol=2, title='Delay time')
    return li 
Example 5
Project: opt_trade   Author: ejpjapan   File: implied_to_realized.py    MIT License 6 votes vote down vote up
def plot_vol_forecast(self, num_days=10):
        expected_volatility = self.expected_vol
        fig, ax = plt.subplots(figsize=(12, 5), dpi=80, facecolor='w', edgecolor='k')

        for i in range(-1, -(num_days + 1), -1):
            if i == -1:
                expected_volatility.iloc[:, -1].plot(color='r')
            else:
                c = cm.viridis(-i / num_days, 1)
                expected_volatility.iloc[:, i].plot(color=c)

        plt.autoscale(enable=True, axis='x', tight=True)
        legend_labels = expected_volatility.iloc[:, -num_days:].columns.strftime('%d-%b')
        _ = plt.legend(legend_labels[::-1])
        _ = plt.title('HAR Volatity Forecast')
        _ = ax.set_ylabel('Annualized Vol %')
        return ax 
Example 6
Project: PyLoT   Author: seismology-RUB   File: pdf.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def plot(self, label=None):
        import matplotlib.pyplot as plt

        plt.plot(self.axis, self.data())
        plt.xlabel('x')
        plt.ylabel('f(x)')
        plt.autoscale(axis='x', tight=True)
        if self:
            title_str = 'Probability density function '
            if label:
                title_str += label
            title_str.strip()
        else:
            title_str = 'Function not suitable as probability density function'
        plt.title(title_str)
        plt.show() 
Example 7
Project: python3_ios   Author: holzschu   File: test_axes.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_use_sticky_edges():
    fig, ax = plt.subplots()
    ax.imshow([[0, 1], [2, 3]], origin='lower')
    assert_allclose(ax.get_xlim(), (-0.5, 1.5))
    assert_allclose(ax.get_ylim(), (-0.5, 1.5))
    ax.use_sticky_edges = False
    ax.autoscale()
    xlim = (-0.5 - 2 * ax._xmargin, 1.5 + 2 * ax._xmargin)
    ylim = (-0.5 - 2 * ax._ymargin, 1.5 + 2 * ax._ymargin)
    assert_allclose(ax.get_xlim(), xlim)
    assert_allclose(ax.get_ylim(), ylim)
    # Make sure it is reversible:
    ax.use_sticky_edges = True
    ax.autoscale()
    assert_allclose(ax.get_xlim(), (-0.5, 1.5))
    assert_allclose(ax.get_ylim(), (-0.5, 1.5)) 
Example 8
Project: prclz   Author: satejsoman   File: plotting.py    GNU General Public License v3.0 6 votes vote down vote up
def plot_polygons(
    polygons: List[Polygon], 
    ax: Optional[matplotlib.axes.Axes] = None, 
    facecolors: Optional[Iterator[Color]] = None, 
    edgecolors: Optional[Iterator[Color]] = None, 
    linewidth: float=0.5, 
    zorder: int=10
) -> matplotlib.figure.Figure:
    if not ax:
        ax = plt.gca()
    if not facecolors:
        facecolors = cycle(['gray'])
    if not edgecolors:
        edgecolors = cycle(['white'])
    
    for (polygon, fc, ec) in zip(polygons, facecolors, edgecolors):
        ax.add_patch(PolygonPatch(polygon, fc=fc, ec=ec, linewidth=linewidth, zorder=zorder))
    plt.autoscale()

    return plt.gcf() 
Example 9
Project: psychrometric-chart-makeover   Author: buds-lab   File: test_axes.py    MIT License 6 votes vote down vote up
def test_use_sticky_edges():
    fig, ax = plt.subplots()
    ax.imshow([[0, 1], [2, 3]], origin='lower')
    assert_allclose(ax.get_xlim(), (-0.5, 1.5))
    assert_allclose(ax.get_ylim(), (-0.5, 1.5))
    ax.use_sticky_edges = False
    ax.autoscale()
    xlim = (-0.5 - 2 * ax._xmargin, 1.5 + 2 * ax._xmargin)
    ylim = (-0.5 - 2 * ax._ymargin, 1.5 + 2 * ax._ymargin)
    assert_allclose(ax.get_xlim(), xlim)
    assert_allclose(ax.get_ylim(), ylim)
    # Make sure it is reversible:
    ax.use_sticky_edges = True
    ax.autoscale()
    assert_allclose(ax.get_xlim(), (-0.5, 1.5))
    assert_allclose(ax.get_ylim(), (-0.5, 1.5)) 
Example 10
Project: generative-graph-transformer   Author: davide-belli   File: utils.py    MIT License 6 votes vote down vote up
def full_frame(plt, width=0.64, height=0.64):
    r"""
    Generates a particular tight layout for Pyplot plots

    :param plt: pyplot
    :param width: width, default is 64 pixels
    :param height: height, default is 64 pixels
    :return:
    """
    import matplotlib as mpl
    mpl.rcParams['savefig.pad_inches'] = 0
    figsize = None if width is None else (width, height)
    fig = plt.figure(figsize=figsize)
    ax = plt.axes([0, 0, 1, 1], frameon=False)
    ax.get_xaxis().set_visible(False)
    ax.get_yaxis().set_visible(False)
    plt.autoscale(tight=True) 
Example 11
Project: generative-graph-transformer   Author: davide-belli   File: utils.py    MIT License 6 votes vote down vote up
def full_frame_high_res(plt, width=3.2, height=3.2):
    r"""
    Generates a particular tight layout for Pyplot plots, at higher resolution
    
    :param plt: pyplot
    :param width: width, default is 320 pixels
    :param height: height, default is 320 pixels
    :return:
    """
    import matplotlib as mpl
    mpl.rcParams['savefig.pad_inches'] = 0
    figsize = None if width is None else (width, height)
    fig = plt.figure(figsize=figsize)
    ax = plt.axes([0, 0, 1, 1], frameon=False)
    ax.get_xaxis().set_visible(False)
    ax.get_yaxis().set_visible(False)
    plt.autoscale(tight=True) 
Example 12
Project: px4tools   Author: dronecrew   File: analysis.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def pos_analysis(data):
    """
    Analyze position.
    """
    tmerc_map = mapping.create_map(data.GPS_Lon.values, data.GPS_Lat.values)
    gps_y, gps_x = tmerc_map(data.GPS_Lon.values, data.GPS_Lat.values)
    gpos_y, gpos_x = tmerc_map(data.GPOS_Lon.values, data.GPOS_Lat.values)
    gpsp_y, gpsp_x = tmerc_map(
        data.GPSP_Lon[np.isfinite(data.GPSP_Lon.values)].values,
        data.GPSP_Lat[np.isfinite(data.GPSP_Lat.values)].values)

    import matplotlib.pyplot as plt
    plt.plot(gpos_y, gpos_x, '.', label='est')

    plt.plot(gps_y, gps_x, 'x', label='GPS')

    plt.plot(gpsp_y, gpsp_x, 'ro', label='cmd')

    plt.xlabel('E, m')
    plt.ylabel('N, m')
    plt.grid()
    plt.autoscale(True, 'both', True)
    plt.legend(loc='best')
    return locals() 
Example 13
Project: SignLanguage_ML   Author: mareep-raljodid   File: test_axes.py    MIT License 6 votes vote down vote up
def test_use_sticky_edges():
    fig, ax = plt.subplots()
    ax.imshow([[0, 1], [2, 3]], origin='lower')
    assert_allclose(ax.get_xlim(), (-0.5, 1.5))
    assert_allclose(ax.get_ylim(), (-0.5, 1.5))
    ax.use_sticky_edges = False
    ax.autoscale()
    xlim = (-0.5 - 2 * ax._xmargin, 1.5 + 2 * ax._xmargin)
    ylim = (-0.5 - 2 * ax._ymargin, 1.5 + 2 * ax._ymargin)
    assert_allclose(ax.get_xlim(), xlim)
    assert_allclose(ax.get_ylim(), ylim)
    # Make sure it is reversible:
    ax.use_sticky_edges = True
    ax.autoscale()
    assert_allclose(ax.get_xlim(), (-0.5, 1.5))
    assert_allclose(ax.get_ylim(), (-0.5, 1.5)) 
Example 14
Project: brainpipe   Author: EtienneCmb   File: _plot.py    GNU General Public License v3.0 6 votes vote down vote up
def _plot(xvec, yvec, title='', xlabel='', ylabel='', maxplot=10, **kwargs):
    """Simple plot"""
    def _subplot(yvec):
        dimLen = len(yvec.shape)
        if dimLen == 1:
            X = [yvec]
        elif dimLen == 2:
            X = [n.mean(yvec, 1)]
        elif dimLen == 3:
            X = [n.mean(yvec[k, :, :], 1) for k in range(0, yvec.shape[0])]
        [plt.plot(xvec, k, label=str(i), **kwargs) for i, k in enumerate(X)]
        ax = plt.gca()
        ax.set_xlabel(xlabel), ax.set_ylabel(ylabel)
        ax.set_title(title), ax.legend()
        plt.autoscale(tight=True)
        return ax

    return _sub(yvec, _subplot, maxplot=maxplot) 
Example 15
Project: Blackjack-Tracker   Author: martinabeleda   File: test_axes.py    MIT License 6 votes vote down vote up
def test_use_sticky_edges():
    fig, ax = plt.subplots()
    ax.imshow([[0, 1], [2, 3]], origin='lower')
    assert_allclose(ax.get_xlim(), (-0.5, 1.5))
    assert_allclose(ax.get_ylim(), (-0.5, 1.5))
    ax.use_sticky_edges = False
    ax.autoscale()
    xlim = (-0.5 - 2 * ax._xmargin, 1.5 + 2 * ax._xmargin)
    ylim = (-0.5 - 2 * ax._ymargin, 1.5 + 2 * ax._ymargin)
    assert_allclose(ax.get_xlim(), xlim)
    assert_allclose(ax.get_ylim(), ylim)
    # Make sure it is reversible:
    ax.use_sticky_edges = True
    ax.autoscale()
    assert_allclose(ax.get_xlim(), (-0.5, 1.5))
    assert_allclose(ax.get_ylim(), (-0.5, 1.5)) 
Example 16
Project: TranskribusDU   Author: Transkribus   File: print_res.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def plot_We(fn = 'table_plot_wE/table_F1_C5.pickle'):


    f = open(fn, 'rb')
    R = pickle.load(f)
    f.close()
    R
    R.keys()
    We = R['W_edge']
    len(We)




    W = np.vstack(We)
    W.shape

    plt.figure()
    ax = plt.gca()
    im=ax.imshow(W)
    divider = make_axes_locatable(ax)
    cax = divider.append_axes("right", size="5%", pad=0.05)
    plt.colorbar(im, cax=cax)
    plt.autoscale(enable=True, axis='x', tight=True)
    plt.show() 
Example 17
Project: million-channels-project   Author: rustyrussell   File: measures.py    MIT License 6 votes vote down vote up
def cluster(nodes, reg=True, params=None, graph=False, completeNetwork=True, bounds=(0, 1000, 1)):
    # lawParams, lawCovariance, x, y = powerLawExperiment(nodes, graph=False, completeNetwork=True)
    if completeNetwork:
        utility.setMaxChannels(nodes)
    t0 = time.time()
    avgCluster, clusterDict = clustering(nodes)
    t1 = time.time()
    print(avgCluster)
    print(str(t1-t0))
    covariance = None
    freqx, freqy, clustery = getClusterFreqData(nodes, clusterDict)
    if reg:
        params, covariance = negExpRegParam(freqx,clustery)
    if graph:
        g.simpleFreqPlot(freqx, clustery)
        g.plotFunction(negExpFunc, params, bounds, xaxisDescription="channels", yaxisDescription="average cluster" )
        plt.autoscale()
        plt.show()

    print(params)
    print(covariance)

    return avgCluster, clusterDict, freqx, clustery, params, covariance 
Example 18
Project: lambda-tensorflow-object-detection   Author: mikylucky   File: test_axes.py    GNU General Public License v3.0 6 votes vote down vote up
def test_use_sticky_edges():
    fig, ax = plt.subplots()
    ax.imshow([[0, 1], [2, 3]], origin='lower')
    assert_allclose(ax.get_xlim(), (-0.5, 1.5))
    assert_allclose(ax.get_ylim(), (-0.5, 1.5))
    ax.use_sticky_edges = False
    ax.autoscale()
    xlim = (-0.5 - 2 * ax._xmargin, 1.5 + 2 * ax._xmargin)
    ylim = (-0.5 - 2 * ax._ymargin, 1.5 + 2 * ax._ymargin)
    assert_allclose(ax.get_xlim(), xlim)
    assert_allclose(ax.get_ylim(), ylim)
    # Make sure it is reversible:
    ax.use_sticky_edges = True
    ax.autoscale()
    assert_allclose(ax.get_xlim(), (-0.5, 1.5))
    assert_allclose(ax.get_ylim(), (-0.5, 1.5)) 
Example 19
Project: Stegall   Author: mrT4ntr4   File: soxy.py    MIT License 5 votes vote down vote up
def show_image(width=None, height=None):
	import matplotlib.pyplot as plt
	import matplotlib.image as mpimg
	import matplotlib as mpl
	mpl.rcParams['savefig.pad_inches'] = 0
	figsize = None if width is None else (width, height)
	fig = plt.figure(figsize=figsize)
	ax = plt.axes([0,0,1,1], frameon=False)
	ax.get_xaxis().set_visible(False)
	ax.get_yaxis().set_visible(False)
	plt.autoscale(tight=True)
	img = mpimg.imread('spectrogram.png')
	plt.imshow(img)
	plt.show() 
Example 20
Project: esys-pbi   Author: fsxfreak   File: graph_matplotlib.py    MIT License 5 votes vote down vote up
def __init__(self, size=(600,350)):
    streams = resolve_byprop('name', 'bci', timeout=2.5)
    try:
      self.inlet = StreamInlet(streams[0])
    except IndexError:
      raise ValueError('Make sure stream name=bci is opened first.')
   
    self.running = True
    
    self.ProcessedSig = []
    self.SecondTimes = []
    self.count = -1
    self.sampleCount = self.count 
    self.maximum = 0
    self.minimum = 0

    plt.ion()
    plt.hold(False)     
    self.lineHandle = plt.plot(self.SecondTimes, self.ProcessedSig)
    plt.title("Live Stream EEG Data")
    plt.xlabel('Time (s)')
    plt.ylabel('mV')
    #plt.autoscale(True, 'y', tight = True)
    plt.show()
    #while(1):
    #secondTimes.append(serialData[0])                         #add time stamps to array 'timeValSeconds'
    #floatSecondTimes.append(float(serialData[0])/1000000)     # makes all second times into float from string
    
    #processedSig.append(serialData[6])                           #add processed signal values to 'processedSig'
    #floatProcessedSig.append(float(serialData[6])) 
Example 21
Project: EvoOpt   Author: tsyet12   File: DuelistAlgorithm.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def announce_answer(self):
		answerlog=self.bestlog[self.bestlog[:,0].argsort()]
		print("Optimized using Duelist Algorithm. Answer is:",answerlog[0][1::], "with fitness of", answerlog[0][0])
		if self.plot==True:
			mp.plot(self.plotgen,self.plotfit)
			mp.title("Duelist Algorithm Optimization")
			mp.xlabel("Number of Generation")
			mp.ylabel("Objective Function of Overall Best Solution")
			mp.autoscale()
			mp.show() 
Example 22
Project: nntour   Author: miku   File: perceptron.py    MIT License 5 votes vote down vote up
def drawimg(X, y, W, filename=None, title=''):
    """
    Save data plus boundary to filname.
    """
    if not filename:
        _, filename = tempfile.mkstemp(prefix='nntour-')

    plt.clf()

    pos = np.array([x[1:] for i, x in enumerate(X) if y[i] == 1])
    neg = np.array([x[1:] for i, x in enumerate(X) if y[i] == -1])

    axes = plt.gca()
    axes.set_xlim([-2, 2])
    axes.set_ylim([-2, 2])

    axes.get_xaxis().set_visible(False)
    axes.get_yaxis().set_visible(False)

    plt.title(title)
    plt.autoscale(enable=False)

    plt.scatter(pos[:, 0], pos[:, 1], color='b')
    plt.scatter(neg[:, 0], neg[:, 1], color='r')

    xb = np.linspace(-2, 2, 1000)
    yb = (-W[0] - W[1] * xb) / W[2]

    plt.plot(xb, yb, '-', color='k')
    plt.savefig(filename) 
Example 23
Project: BuildingMachineLearning   Author: ademyanchuk   File: analyze_webstats.py    MIT License 5 votes vote down vote up
def plot_models(x, y, models, fname, mx=None, ymax=None, xmin=None):
    ''' plot input data '''

    plt.figure(num=None, figsize=(8, 6))
    plt.clf()
    plt.scatter(x, y, s=10)
    plt.title("Web traffic over the last month")
    plt.xlabel("Time")
    plt.ylabel("Hits/hour")
    plt.xticks(
        [w * 7 * 24 for w in range(10)], ['week %i' % w for w in range(10)])

    if models:
        if mx is None:
            mx = sp.linspace(0, x[-1], 1000)
        for model, style, color in zip(models, linestyles, colors):
            # print "Model:",model
            # print "Coeffs:",model.coeffs
            plt.plot(mx, model(mx), linestyle=style, linewidth=2, c=color)

        plt.legend(["d=%i" % m.order for m in models], loc="upper left")

    plt.autoscale(tight=True)
    plt.ylim(ymin=0)
    if ymax:
        plt.ylim(ymax=ymax)
    if xmin:
        plt.xlim(xmin=xmin)
    plt.grid(True, linestyle='-', color='0.75')
    plt.savefig(fname)

# first look at the data 
Example 24
Project: ble5-nrf52-mac   Author: tomasero   File: test_axes.py    MIT License 5 votes vote down vote up
def test_autoscale_tight():
    fig, ax = plt.subplots(1, 1)
    ax.plot([1, 2, 3, 4])
    ax.autoscale(enable=True, axis='x', tight=False)
    ax.autoscale(enable=True, axis='y', tight=True)
    assert_allclose(ax.get_xlim(), (-0.15, 3.15))
    assert_allclose(ax.get_ylim(), (1.0, 4.0)) 
Example 25
Project: ble5-nrf52-mac   Author: tomasero   File: test_axes.py    MIT License 5 votes vote down vote up
def test_autoscale_log_shared():
    # related to github #7587
    # array starts at zero to trigger _minpos handling
    x = np.arange(100, dtype=float)
    fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True)
    ax1.loglog(x, x)
    ax2.semilogx(x, x)
    ax1.autoscale(tight=True)
    ax2.autoscale(tight=True)
    plt.draw()
    lims = (x[1], x[-1])
    assert_allclose(ax1.get_xlim(), lims)
    assert_allclose(ax1.get_ylim(), lims)
    assert_allclose(ax2.get_xlim(), lims)
    assert_allclose(ax2.get_ylim(), (x[0], x[-1])) 
Example 26
Project: Building-Machine-Learning-Systems-With-Python-Second-Edition   Author: PacktPublishing   File: analyze_webstats.py    MIT License 5 votes vote down vote up
def plot_models(x, y, models, fname, mx=None, ymax=None, xmin=None):

    plt.figure(num=None, figsize=(8, 6))
    plt.clf()
    plt.scatter(x, y, s=10)
    plt.title("Web traffic over the last month")
    plt.xlabel("Time")
    plt.ylabel("Hits/hour")
    plt.xticks(
        [w * 7 * 24 for w in range(10)], ['week %i' % w for w in range(10)])

    if models:
        if mx is None:
            mx = sp.linspace(0, x[-1], 1000)
        for model, style, color in zip(models, linestyles, colors):
            # print "Model:",model
            # print "Coeffs:",model.coeffs
            plt.plot(mx, model(mx), linestyle=style, linewidth=2, c=color)

        plt.legend(["d=%i" % m.order for m in models], loc="upper left")

    plt.autoscale(tight=True)
    plt.ylim(ymin=0)
    if ymax:
        plt.ylim(ymax=ymax)
    if xmin:
        plt.xlim(xmin=xmin)
    plt.grid(True, linestyle='-', color='0.75')
    plt.savefig(fname)

# first look at the data 
Example 27
Project: opt_trade   Author: ejpjapan   File: vix_utilities.py    MIT License 5 votes vote down vote up
def plot_rolling_beta(self, **kwargs):
        beta, rolling_window = self.vix_beta(**kwargs)
        pc = PlotConstants()
        with plt.style.context('bmh'):
            _ = plt.figure(figsize=pc.fig_size,
                           dpi=600,
                           facecolor='None',
                           edgecolor='None')
            gs = gridspec.GridSpec(1, 1, wspace=0.5, hspace=0.25)
            ax_beta = plt.subplot(gs[:])
            ax_beta = beta.plot(lw=1.5,
                                ax=ax_beta,
                                grid=True,
                                alpha=0.4,
                                color=pc.color_yellow,
                                title='VIX beta to S&P500 - {} days rolling window'.format(rolling_window))
            ax_beta.set_ylabel('Beta')
            ax_beta.axhline(beta.mean(),
                            color='k',
                            ls='--',
                            lw=0.75,
                            alpha=1.0)
            chart_format([ax_beta], pc.color_light)
            plt.autoscale(enable=True,
                          axis='x',
                          tight=True)
        return ax_beta 
Example 28
Project: python3_ios   Author: holzschu   File: test_axes.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_autoscale_tight():
    fig, ax = plt.subplots(1, 1)
    ax.plot([1, 2, 3, 4])
    ax.autoscale(enable=True, axis='x', tight=False)
    ax.autoscale(enable=True, axis='y', tight=True)
    assert_allclose(ax.get_xlim(), (-0.15, 3.15))
    assert_allclose(ax.get_ylim(), (1.0, 4.0)) 
Example 29
Project: python3_ios   Author: holzschu   File: test_axes.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_autoscale_log_shared():
    # related to github #7587
    # array starts at zero to trigger _minpos handling
    x = np.arange(100, dtype=float)
    fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True)
    ax1.loglog(x, x)
    ax2.semilogx(x, x)
    ax1.autoscale(tight=True)
    ax2.autoscale(tight=True)
    plt.draw()
    lims = (x[1], x[-1])
    assert_allclose(ax1.get_xlim(), lims)
    assert_allclose(ax1.get_ylim(), lims)
    assert_allclose(ax2.get_xlim(), lims)
    assert_allclose(ax2.get_ylim(), (x[0], x[-1])) 
Example 30
Project: vi_vae_gmm   Author: wangg12   File: vi_GMM_2d.py    Apache License 2.0 5 votes vote down vote up
def get_plot_buf(x, clusters, mu, logstd, true_mu, true_logstd):
    N = x.shape[0]
    K = mu.shape[0]
    fig = plt.figure()
    # print(clusters.shape)
    # print(x.shape)
    ax = fig.add_subplot(111, aspect='auto')
    plt.scatter(x[:, 0], x[:, 1], c=clusters, s=50)
    # print(mu, logstd)
    ells = [Ellipse(xy=mean_, width=6*np.exp(logstd_[0]), height=6*np.exp(logstd_[1]),
                angle=0, facecolor='none', zorder=10, edgecolor='g', label='predict' if i==0 else None)
            for i, (mean_, logstd_) in enumerate(zip(mu, logstd))]
    true_ells = [Ellipse(xy=mean_, width=6*np.exp(logstd_[0]), height=6*np.exp(logstd_[1]),
                angle=0, facecolor='none', zorder=10, edgecolor='r', label='true' if i==0 else None)
            for i,(mean_, logstd_) in enumerate(zip(true_mu, true_logstd))]
    # print(ells[0])
    [ax.add_patch(ell) for ell in ells]
    [ax.add_patch(true_ell) for true_ell in true_ells]
    ax.legend(loc='best')
    ax.set_title('N={},K={}'.format(N, K))
    plt.autoscale(True)
    buf = io.BytesIO()
    fig.savefig(buf, format='png')
    plt.close()
    buf.seek(0)
    return buf 
Example 31
Project: monsoon-onset   Author: jenfly   File: compare-indices.py    MIT License 5 votes vote down vote up
def plot_tseries(dayrel, ind, std, clr, key, xlabel, ylabel):
    plt.plot(dayrel, ind, clr, label=key)
    plt.fill_between(dayrel, ind-std, ind+std, color=clr, alpha=0.2)
    plt.title(key, fontsize=12)
    plt.xlabel(xlabel)
    plt.ylabel(ylabel)
    plt.grid(True)
    plt.autoscale(tight=True) 
Example 32
Project: monsoon-onset   Author: jenfly   File: daily-tseries.py    MIT License 5 votes vote down vote up
def plot_tseries(dayrel, ind, std, clr, key, xlabel, ylabel):
        plt.plot(dayrel, ind, clr, label=key)
        plt.fill_between(dayrel, ind-std, ind+std, color=clr, alpha=0.2)
        plt.legend(loc='lower right')
        plt.xlabel(xlabel)
        plt.ylabel(ylabel)
        plt.grid(True)
        plt.autoscale(tight=True) 
Example 33
Project: psychrometric-chart-makeover   Author: buds-lab   File: test_axes.py    MIT License 5 votes vote down vote up
def test_autoscale_tight():
    fig, ax = plt.subplots(1, 1)
    ax.plot([1, 2, 3, 4])
    ax.autoscale(enable=True, axis='x', tight=False)
    ax.autoscale(enable=True, axis='y', tight=True)
    assert_allclose(ax.get_xlim(), (-0.15, 3.15))
    assert_allclose(ax.get_ylim(), (1.0, 4.0)) 
Example 34
Project: psychrometric-chart-makeover   Author: buds-lab   File: test_axes.py    MIT License 5 votes vote down vote up
def test_autoscale_log_shared():
    # related to github #7587
    # array starts at zero to trigger _minpos handling
    x = np.arange(100, dtype=float)
    fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True)
    ax1.loglog(x, x)
    ax2.semilogx(x, x)
    ax1.autoscale(tight=True)
    ax2.autoscale(tight=True)
    plt.draw()
    lims = (x[1], x[-1])
    assert_allclose(ax1.get_xlim(), lims)
    assert_allclose(ax1.get_ylim(), lims)
    assert_allclose(ax2.get_xlim(), lims)
    assert_allclose(ax2.get_ylim(), (x[0], x[-1])) 
Example 35
Project: report-python-docx   Author: kleberandrade   File: beta_report_send_email.py    MIT License 5 votes vote down vote up
def full_frame(width=None, height=None):
    import matplotlib as mpl
    mpl.rcParams['savefig.pad_inches'] = 0
    figsize = None if width is None else (width, height)
    fig = plt.figure(figsize=figsize)
    ax = plt.axes([0,0,1,1], frameon=False)
    ax.get_xaxis().set_visible(False)
    ax.get_yaxis().set_visible(False)
    #plt.autoscale(tight=True)
    return fig 
Example 36
Project: Duelist-Algorithm-Python   Author: tsyet12   File: Duelist_Algorithm.py    GNU Lesser General Public License v2.1 5 votes vote down vote up
def announce_answer(self):
		answerlog=self.bestlog[self.bestlog[:,0].argsort()]
		print("Optimized using Duelist Algorithm. Answer is:",answerlog[0][1::], "with fitness of", answerlog[0][0])
		if self.plot==True:
			mp.plot(self.plotgen,self.plotfit)
			mp.title("Duelist Algorithm Optimization")
			mp.xlabel("Number of Generation")
			mp.ylabel("Objective Function of Overall Best Solution")
			mp.autoscale()
			mp.show() 
Example 37
Project: sarviewer   Author: juliojsb   File: loadaverage.py    GNU General Public License v3.0 5 votes vote down vote up
def generate_graph():
    with open('../../data/loadaverage.dat', 'r') as csvfile:
        data_source = csv.reader(csvfile, delimiter=' ', skipinitialspace=True)
        for row in data_source:
            # [0] column is a time column
            # Convert to datetime data type
            a = datetime.strptime((row[0]),'%H:%M:%S')
            x.append((a))
            # The remaining columns contain data
            m1.append(row[3])
            m5.append(row[4])
            m15.append(row[5])
    
    # Plot lines
    plt.plot(x,m1, label='1 min', color='g', antialiased=True)
    plt.plot(x,m5, label='5 min', color='r', antialiased=True)
    plt.plot(x,m15, label='15 min', color='b', antialiased=True)
    
    # Graph properties
    plt.xlabel('Time',fontstyle='italic')
    plt.ylabel('Load average',fontstyle='italic')
    plt.title('Load average graph')
    plt.grid(linewidth=0.4, antialiased=True)
    plt.legend(loc='upper center', bbox_to_anchor=(0.5, -0.15), ncol=2, fancybox=True, shadow=True)
    plt.autoscale(True)
    
    # Graph saved to PNG file
    plt.savefig('../../graphs/loadaverage.png', bbox_inches='tight')
    #plt.show()

# ======================
# MAIN
# ====================== 
Example 38
Project: sarviewer   Author: juliojsb   File: ram.py    GNU General Public License v3.0 5 votes vote down vote up
def generate_graph():
    with open('../../data/ram.dat', 'r') as csvfile:
        data_source = csv.reader(csvfile, delimiter=' ', skipinitialspace=True)
        for row in data_source:
            # [0] column is a time column
            # Convert to datetime data type
            a = datetime.strptime((row[0]),'%H:%M:%S')
            x.append((a))
            # The remaining columns contain data
            free_mem.append(str((int(row[1])/1024)+(int(row[4])/1024)+(int(row[5])/1024)))
            used_mem.append(str((int(row[2])/1024)-(int(row[4])/1024)-(int(row[5])/1024)))
            buffer_mem.append(str(int(row[4])/1024))
            cached_mem.append(str(int(row[5])/1024))
    
    # Plot lines
    plt.plot(x,free_mem, label='Free', color='g', antialiased=True)
    plt.plot(x,used_mem, label='Used', color='r', antialiased=True)
    plt.plot(x,buffer_mem, label='Buffer', color='b', antialiased=True)
    plt.plot(x,cached_mem, label='Cached', color='c', antialiased=True)
    
    # Graph properties
    plt.xlabel('Time',fontstyle='italic')
    plt.ylabel('Memory (MB)',fontstyle='italic')
    plt.title('RAM usage graph')
    plt.grid(linewidth=0.4, antialiased=True)
    plt.legend(loc='upper center', bbox_to_anchor=(0.5, -0.15), ncol=2, fancybox=True, shadow=True)
    plt.autoscale(True)
    
    # Graph saved to PNG file
    plt.savefig('../../graphs/ram.png', bbox_inches='tight')
    #plt.show()

# ======================
# MAIN
# ====================== 
Example 39
Project: sarviewer   Author: juliojsb   File: swap.py    GNU General Public License v3.0 5 votes vote down vote up
def generate_graph():
    with open('../../data/swap.dat', 'r') as csvfile:
        data_source = csv.reader(csvfile, delimiter=' ', skipinitialspace=True)
        for row in data_source:
            # [0] column is a time column
            # Convert to datetime data type
            a = datetime.strptime((row[0]),'%H:%M:%S')
            x.append((a))
            # The remaining columns contain data
            swap_free.append(str(int(row[1])/1024))
            swap_used.append(str(int(row[2])/1024))
            

    # Plot lines
    plt.plot(x,swap_used, label='Used', color='r', antialiased=True)
    plt.plot(x,swap_free, label='Free', color='g', antialiased=True)
    
    # Graph properties
    plt.xlabel('Time',fontstyle='italic')
    plt.ylabel('SWAP (MB)',fontstyle='italic')
    plt.title('SWAP usage graph')
    plt.grid(linewidth=0.4, antialiased=True)
    plt.legend(loc='upper center', bbox_to_anchor=(0.5, -0.15), ncol=2, fancybox=True, shadow=True)
    plt.autoscale(True)
    
    # Graph saved to PNG file
    plt.savefig('../../graphs/swap.png', bbox_inches='tight')
    #plt.show()

# ======================
# MAIN
# ====================== 
Example 40
Project: sarviewer   Author: juliojsb   File: proc.py    GNU General Public License v3.0 5 votes vote down vote up
def generate_graph():
    with open('../../data/proc.dat', 'r') as csvfile:
        data_source = csv.reader(csvfile, delimiter=' ', skipinitialspace=True)
        for row in data_source:
            # [0] column is a time column
            # Convert to datetime data type
            a = datetime.strptime((row[0]),'%H:%M:%S')
            x.append((a))
            # The remaining columns contain data
            procs_per_second.append(row[1])

    # Plot lines
    plt.plot(x,procs_per_second, label='Processes created per second', color='r', antialiased=True)
    
    # Graph properties
    plt.xlabel('Time',fontstyle='italic')
    plt.ylabel('Processes',fontstyle='italic')
    plt.title('Processes created per second graph')
    plt.grid(linewidth=0.4, antialiased=True)
    plt.legend(loc='upper center', bbox_to_anchor=(0.5, -0.15), ncol=2, fancybox=True, shadow=True)
    plt.autoscale(True)
    
    # Graph saved to PNG file
    plt.savefig('../../graphs/proc.png', bbox_inches='tight')
    #plt.show()

# ======================
# MAIN
# ====================== 
Example 41
Project: sarviewer   Author: juliojsb   File: tasks.py    GNU General Public License v3.0 5 votes vote down vote up
def generate_graph():
    with open('../../data/loadaverage.dat', 'r') as csvfile:
        data_source = csv.reader(csvfile, delimiter=' ', skipinitialspace=True)
        for row in data_source:
            # [0] column is a time column
            # Convert to datetime data type
            a = datetime.strptime((row[0]),'%H:%M:%S')
            x.append((a))
            # The remaining columns contain data
            t_run_queue.append(row[1])
            t_total.append(row[2])
            t_blocked.append(row[6])
    
    # Plot lines
    plt.plot(x,t_run_queue, label='Tasks in run queue', color='g', antialiased=True)
    plt.plot(x,t_total, label='Total active tasks (processes + threads)', color='r', antialiased=True)
    plt.plot(x,t_blocked, label='Blocked tasks', color='m', antialiased=True)
    
    # Graph properties
    plt.xlabel('Time',fontstyle='italic')
    plt.ylabel('Tasks',fontstyle='italic')
    plt.title('Tasks graph')
    plt.grid(linewidth=0.4, antialiased=True)
    plt.legend(loc='upper center', bbox_to_anchor=(0.5, -0.15), ncol=2, fancybox=True, shadow=True)
    plt.autoscale(True)
    
    # Graph saved to PNG file
    plt.savefig('../../graphs/tasks.png', bbox_inches='tight')
    #plt.show()

# ======================
# MAIN
# ====================== 
Example 42
Project: sarviewer   Author: juliojsb   File: netinterface.py    GNU General Public License v3.0 5 votes vote down vote up
def generate_graph():
    with open('../../data/netinterface.dat', 'r') as csvfile:
        data_source = csv.reader(csvfile, delimiter=' ', skipinitialspace=True)
        for row in data_source:
            # [0] column is a time column
            # Convert to datetime data type
            a = datetime.strptime((row[0]),'%H:%M:%S')
            x.append((a))
            # The remaining columns contain data
            r_kb.append(row[4])
            s_kb.append(row[5])
    
    # Plot lines
    plt.plot(x,r_kb, label='Kilobytes received per second', color='#009973', antialiased=True)
    plt.plot(x,s_kb, label='Kilobytes sent per second', color='#b3b300', antialiased=True)
    
    # Graph properties
    plt.xlabel('Time',fontstyle='italic')
    plt.ylabel('Kb/s',fontstyle='italic')
    plt.title('Network statistics')
    plt.grid(linewidth=0.4, antialiased=True)
    plt.legend(loc='upper center', bbox_to_anchor=(0.5, -0.18), ncol=2, fancybox=True, shadow=True)
    plt.autoscale(True)
    
    # Graph saved to PNG file
    plt.savefig('../../graphs/netinterface.png', bbox_inches='tight')
    #plt.show()

# ======================
# MAIN
# ====================== 
Example 43
Project: sarviewer   Author: juliojsb   File: iotransfer.py    GNU General Public License v3.0 5 votes vote down vote up
def generate_graph():
    with open('../../data/iotransfer.dat', 'r') as csvfile:
        data_source = csv.reader(csvfile, delimiter=' ', skipinitialspace=True)
        for row in data_source:
            # [0] column is a time column
            # Convert to datetime data type
            a = datetime.strptime((row[0]),'%H:%M:%S')
            x.append((a))
            # The remaining columns contain data
            b_read_second.append(row[4])
            b_written_second.append(row[5])
            
    # Plot lines
    plt.plot(x,b_read_second, label='Blocks read per second', color='r', antialiased=True)
    plt.plot(x,b_written_second, label='Blocks written per second', color='g', antialiased=True)
    
    # Graph properties
    plt.xlabel('Time',fontstyle='italic')
    plt.ylabel('Blocks per second',fontstyle='italic')
    plt.title('IO Transfer graph')
    plt.grid(linewidth=0.4, antialiased=True)
    plt.legend(loc='upper center', bbox_to_anchor=(0.5, -0.15), ncol=2, fancybox=True, shadow=True)
    plt.autoscale(True)
    
    # Graph saved to PNG file
    plt.savefig('../../graphs/iotransfer.png', bbox_inches='tight')
    #plt.show()

# ======================
# MAIN
# ====================== 
Example 44
Project: sarviewer   Author: juliojsb   File: cpu.py    GNU General Public License v3.0 5 votes vote down vote up
def generate_graph():
    with open('../../data/cpu.dat', 'r') as csvfile:
        data_source = csv.reader(csvfile, delimiter=' ', skipinitialspace=True)
        for row in data_source:
            # [0] column is a time column
            # Convert to datetime data type
            a = datetime.strptime((row[0]),'%H:%M:%S')
            x.append((a))
            # The remaining columns contain data
            user_cpu.append(row[2])
            system_cpu.append(row[4])
            idle_cpu.append(row[7])
    
    # Plot lines
    plt.plot(x,user_cpu, label='User %', color='g', antialiased=True)
    plt.plot(x,system_cpu, label='System %', color='r', antialiased=True)
    plt.plot(x,idle_cpu, label='Idle %', color='b', antialiased=True)
    
    # Graph properties
    plt.xlabel('Time',fontstyle='italic')
    plt.ylabel('CPU %',fontstyle='italic')
    plt.title('CPU usage graph')
    plt.grid(linewidth=0.4, antialiased=True)
    plt.legend(loc='upper center', bbox_to_anchor=(0.5, -0.15), ncol=2, fancybox=True, shadow=True)
    plt.autoscale(True)
    
    # Graph saved to PNG file
    plt.savefig('../../graphs/cpu.png', bbox_inches='tight')
    #plt.show()

# ======================
# MAIN
# ====================== 
Example 45
Project: sarviewer   Author: juliojsb   File: sockets.py    GNU General Public License v3.0 5 votes vote down vote up
def generate_graph():
    with open('../../data/sockets.dat', 'r') as csvfile:
        data_source = csv.reader(csvfile, delimiter=' ', skipinitialspace=True)
        for row in data_source:
            # [0] column is a time column
            # Convert to datetime data type
            a = datetime.strptime((row[0]),'%H:%M:%S')
            x.append((a))
            # The remaining columns contain data
            t_tcp.append(str((int(row[2]))+(int(row[6]))))
            t_tcp_use.append(row[2])
            t_udp_use.append(row[3])
            t_tcp_time_wait.append(row[6])
    
    # Plot lines
    plt.plot(x,t_tcp, label='Total TCP sockets', color='#ff9933', antialiased=True)
    plt.plot(x,t_tcp_use, label='TCP sockets in use', color='#66ccff', antialiased=True)
    plt.plot(x,t_udp_use, label='UDP sockets in use', color='#009933', antialiased=True)
    plt.plot(x,t_tcp_time_wait, label='TCP sockets in TIME WAIT state', color='#cc3300', antialiased=True)
    
    # Graph properties
    plt.xlabel('Time',fontstyle='italic')
    plt.ylabel('Number of sockets',fontstyle='italic')
    plt.title('Sockets')
    plt.grid(linewidth=0.4, antialiased=True)
    plt.legend(loc='upper center', bbox_to_anchor=(0.5, -0.20), ncol=2, fancybox=True, shadow=True)
    plt.autoscale(True)
    
    # Graph saved to PNG file
    plt.savefig('../../graphs/sockets.png', bbox_inches='tight')
    #plt.show()

# ======================
# MAIN
# ====================== 
Example 46
Project: SSGPR   Author: linesd   File: plots.py    MIT License 5 votes vote down vote up
def plot_convergence(path, convergence):
    N = convergence.shape[0]
    X = np.arange(N)
    Y = convergence[:,0]
    plt.figure()
    plt.plot(X, Y)
    plt.grid()
    plt.ylabel("Negative marginal log likelihood")
    plt.xlabel("Number of iterations")
    plt.autoscale(enable=True, axis='x', tight=True)
    plt.show() 
Example 47
Project: SignLanguage_ML   Author: mareep-raljodid   File: test_axes.py    MIT License 5 votes vote down vote up
def test_autoscale_tight():
    fig, ax = plt.subplots(1, 1)
    ax.plot([1, 2, 3, 4])
    ax.autoscale(enable=True, axis='x', tight=False)
    ax.autoscale(enable=True, axis='y', tight=True)
    assert_allclose(ax.get_xlim(), (-0.15, 3.15))
    assert_allclose(ax.get_ylim(), (1.0, 4.0)) 
Example 48
Project: SignLanguage_ML   Author: mareep-raljodid   File: test_axes.py    MIT License 5 votes vote down vote up
def test_autoscale_log_shared():
    # related to github #7587
    # array starts at zero to trigger _minpos handling
    x = np.arange(100, dtype=float)
    fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True)
    ax1.loglog(x, x)
    ax2.semilogx(x, x)
    ax1.autoscale(tight=True)
    ax2.autoscale(tight=True)
    plt.draw()
    lims = (x[1], x[-1])
    assert_allclose(ax1.get_xlim(), lims)
    assert_allclose(ax1.get_ylim(), lims)
    assert_allclose(ax2.get_xlim(), lims)
    assert_allclose(ax2.get_ylim(), (x[0], x[-1])) 
Example 49
Project: Blackjack-Tracker   Author: martinabeleda   File: test_axes.py    MIT License 5 votes vote down vote up
def test_autoscale_tight():
    fig, ax = plt.subplots(1, 1)
    ax.plot([1, 2, 3, 4])
    ax.autoscale(enable=True, axis='x', tight=False)
    ax.autoscale(enable=True, axis='y', tight=True)
    assert_allclose(ax.get_xlim(), (-0.15, 3.15))
    assert_allclose(ax.get_ylim(), (1.0, 4.0)) 
Example 50
Project: Blackjack-Tracker   Author: martinabeleda   File: test_axes.py    MIT License 5 votes vote down vote up
def test_autoscale_log_shared():
    # related to github #7587
    # array starts at zero to trigger _minpos handling
    x = np.arange(100, dtype=float)
    fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True)
    ax1.loglog(x, x)
    ax2.semilogx(x, x)
    ax1.autoscale(tight=True)
    ax2.autoscale(tight=True)
    plt.draw()
    lims = (x[1], x[-1])
    assert_allclose(ax1.get_xlim(), lims)
    assert_allclose(ax1.get_ylim(), lims)
    assert_allclose(ax2.get_xlim(), lims)
    assert_allclose(ax2.get_ylim(), (x[0], x[-1]))