Python matplotlib.pyplot.subplot2grid() Examples

The following are code examples for showing how to use matplotlib.pyplot.subplot2grid(). 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: Stock_Market_Forecast   Author: cuevas1208   File: visualize.py    MIT License 6 votes vote down vote up
def candlestickGraph(df):
    # Drop the rows where all of the elements are nan, i dont doo that here because I will do it in the futer when I combine all data

    df.dropna(axis=0, how='any', inplace=True)

    df_ohlc = df['Adj Close'].resample('10D').ohlc()
    df_volume = df['Volume'].resample('10D').sum()

    df_ohlc.reset_index(inplace=True)
    df_ohlc['Date'] = df_ohlc['Date'].map(mdates.date2num)

    ax1 = plt.subplot2grid((6,1), (0,0), rowspan=5, colspan=1)
    ax2 = plt.subplot2grid((6,1), (5,0), rowspan=1, colspan=1, sharex=ax1)
    ax1.xaxis_date()

    # candlestick_ohlc(ax1, df_ohlc.values, width=5, colorup='g')
    ax2.fill_between(df_volume.index.map(mdates.date2num), df_volume.values, 0)
    plt.show() 
Example 2
Project: RLTrader   Author: notadamking   File: TradingChart.py    GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, df):
        self.df = df

        # Create a figure on screen and set the title
        self.fig = plt.figure()

        # Create top subplot for net worth axis
        self.net_worth_ax = plt.subplot2grid((6, 1), (0, 0), rowspan=2, colspan=1)

        # Create bottom subplot for shared price/volume axis
        self.price_ax = plt.subplot2grid((6, 1), (2, 0), rowspan=8, colspan=1, sharex=self.net_worth_ax)

        # Create a new axis for volume which shares its x-axis with price
        self.volume_ax = self.price_ax.twinx()

        # Add padding to make graph easier to view
        plt.subplots_adjust(left=0.11, bottom=0.24, right=0.90, top=0.90, wspace=0.2, hspace=0)

        # Show the graph without blocking the rest of the program
        plt.show(block=False) 
Example 3
Project: basenji   Author: calico   File: basenji_sat_plot2.py    Apache License 2.0 6 votes vote down vote up
def setup_plot(figure_width, plot_len):
  spp = subplot_params(plot_len)

  plt.figure(figsize=(figure_width, 6))

  axes_list = []
  axes_list.append(plt.subplot2grid(
      (4, spp['heat_cols']), (0, spp['logo_start']),
      colspan=spp['logo_span']))
  axes_list.append(plt.subplot2grid(
      (4, spp['heat_cols']), (1, 0), colspan=spp['heat_cols']))
  axes_list.append(plt.subplot2grid(
      (4, spp['heat_cols']), (2, spp['logo_start']),
      colspan=spp['logo_span']))
  axes_list.append(plt.subplot2grid(
      (4, spp['heat_cols']), (3, 0), colspan=spp['heat_cols']))

  return axes_list 
Example 4
Project: nmsat   Author: rcfduarte   File: visualization.py    GNU General Public License v2.0 6 votes vote down vote up
def summary_statistics(data_list, labels, loc=0, fig=None, cmap='jet'):
    """

    :param data_list:
    :param labels:
    :param loc:
    :param fig:
    :param cmap:
    :return:
    """
    n_axes = len(data_list)
    if fig is None:
        fig = pl.figure()
    cm = get_cmap(n_axes, cmap)
    for i in range(n_axes):
        ax = pl.subplot2grid((1, n_axes*2), (0, i*2), rowspan=1, colspan=2)
        try:
            violin_plot(ax, [data_list[i]], pos=[0], location=loc, color=[cm(i)])
        except:
            continue
        ax.set_title(labels[i])
        box_plot(ax, [data_list[i]], pos=[0]) 
Example 5
Project: nmsat   Author: rcfduarte   File: visualization.py    GNU General Public License v2.0 6 votes vote down vote up
def isi_analysis_histogram_axes(label=''):
    """
    Returns the standard axes for the isi histogram plots
    :return:
    """
    fig1 = pl.figure()
    fig1.suptitle('ISI Metrics - {0}'.format(str(label)))
    ax11 = pl.subplot2grid((3, 11), (0, 0), rowspan=1, colspan=11)
    ax11.set_xscale('log')
    ax12 = pl.subplot2grid((3, 11), (1, 0), rowspan=1, colspan=2)
    ax13 = pl.subplot2grid((3, 11), (1, 3), rowspan=1, colspan=2)
    ax14 = pl.subplot2grid((3, 11), (1, 6), rowspan=1, colspan=2)
    ax15 = pl.subplot2grid((3, 11), (1, 9), rowspan=1, colspan=2)
    ax16 = pl.subplot2grid((3, 11), (2, 0), rowspan=1, colspan=2)
    ax17 = pl.subplot2grid((3, 11), (2, 3), rowspan=1, colspan=2)
    ax18 = pl.subplot2grid((3, 11), (2, 6), rowspan=1, colspan=2)
    ax19 = pl.subplot2grid((3, 11), (2, 9), rowspan=1, colspan=2)
    return fig1, [ax11, ax12, ax13, ax14, ax15, ax16, ax17, ax18, ax19]


# TODO - remove 
Example 6
Project: nmsat   Author: rcfduarte   File: visualization.py    GNU General Public License v2.0 6 votes vote down vote up
def plot_response_activity(spike_list, input_stimulus, start=None, stop=None):
    """
    Plot population responses to stimuli (spiking activity)

    :param spike_list:
    :param input_stimulus:
    :return:
    """
    fig = pl.figure()
    ax1 = pl.subplot2grid((12, 1), (0, 0), rowspan=6, colspan=1)
    ax2 = pl.subplot2grid((12, 1), (7, 0), rowspan=2, colspan=1, sharex=ax1)

    rp = SpikePlots(spike_list, start, stop)
    plot_props = {'xlabel': 'Time [ms]', 'ylabel': 'Neuron', 'linewidth': 1.0, 'linestyle': '-'}
    rp.dot_display(ax=[ax1, ax2], with_rate=True, display=False, save=False, **plot_props)

    rp.mark_events(ax1, input_stimulus, start, stop)
    rp.mark_events(ax2, input_stimulus, start, stop) 
Example 7
Project: pisa   Author: IceCubeOpenSource   File: plotter.py    Apache License 2.0 6 votes vote down vote up
def plot_1d_cmp(self, map_sets, plot_axis, fname=None, **kwargs):
        """1d comparisons for two map_sets as projections"""
        for i in range(len(map_sets[0])):
            maps = [map_set[i] for map_set in map_sets]
            self.stamp = maps[0].tex
            for k, map_set in enumerate(map_sets):
                maps[k].tex = map_set.tex
            self.init_fig()
            if self.ratio:
                ax1 = plt.subplot2grid((4, 1), (0, 0), rowspan=3)
                plt.setp(ax1.get_xticklabels(), visible=False)
            self.reset_colors()
            for map in maps:
                self.next_color()
                self.plot_1d_projection(map, plot_axis, **kwargs)
            self.add_stamp()
            self.add_leg()
            if self.ratio:
                plt.subplot2grid((4, 1), (3, 0), sharex=ax1)
                #self.plot_1d_ratio(maps, plot_axis, r_vmin=0.1, r_vmax=0.1, **kwargs)
                self.plot_1d_ratio(maps, plot_axis, **kwargs)
            self.dump('%s_%s'%(fname, maps[0].name))

    # --- plotting core functions --- 
Example 8
Project: ble5-nrf52-mac   Author: tomasero   File: test_tightlayout.py    MIT License 6 votes vote down vote up
def test_tight_layout4():
    'Test tight_layout for subplot2grid'

    fig = plt.figure()

    ax1 = plt.subplot2grid((3, 3), (0, 0))
    ax2 = plt.subplot2grid((3, 3), (0, 1), colspan=2)
    ax3 = plt.subplot2grid((3, 3), (1, 0), colspan=2, rowspan=2)
    ax4 = plt.subplot2grid((3, 3), (1, 2), rowspan=2)

    example_plot(ax1)
    example_plot(ax2)
    example_plot(ax3)
    example_plot(ax4)

    plt.tight_layout() 
Example 9
Project: skultrafast   Author: Tillsten   File: fitview.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __init__(self, global_fit_obj):
        self.gfo = global_fit_obj
        self.fig = plt.figure(figsize=(12, 10))
        self.fig.subplots_adjust(0.05, 0.05, 0.98, 0.98, 0.1)
        self.image_data = self.gfo.data[:]
        self.overview = plt.subplot2grid((8, 4), (0, 0), rowspan=7, colspan=2)
        self.ov_plot = self.overview.pcolormesh(self.gfo.w, self.gfo.t, self.gfo.data)
        self.overview.autoscale(1, 'both', 1)
        self.spectrum = plt.subplot2grid((8, 4), (0, 2), rowspan=4, colspan=2)
        self.signal = plt.subplot2grid((8, 4), (4, 2), rowspan=4, colspan=2)
        self.mpl_connect = self.fig.canvas.mpl_connect
        self.cursor = Cursor(self.overview, color='black', linewidth=2)

        buax = plt.subplot2grid((8, 4), (7, 0))
        bu2ax = plt.subplot2grid((8, 4), (7, 1))
        self.reset_button = Button(buax, 'Reset')
        self.norm_button = Button(bu2ax, 'Change Norm')
        self.norm = 'no_norm'
        self.connect() 
Example 10
Project: opt_trade   Author: ejpjapan   File: vix_utilities.py    MIT License 6 votes vote down vote up
def _tsplot(y, lags=None, figsize=(16, 9), style='bmh'):
        if not isinstance(y, pd.Series):
            y = pd.Series(y)
        with plt.style.context(style):
            _ = plt.figure(figsize=figsize)
            mpl.rcParams['font.sans-serif'] = 'Roboto Condensed'
            mpl.rcParams['font.family'] = 'sans-serif'
            layout = (3, 2)
            ts_ax = plt.subplot2grid(layout, (0, 0), colspan=2)
            acf_ax = plt.subplot2grid(layout, (1, 0))
            pacf_ax = plt.subplot2grid(layout, (1, 1))
            qq_ax = plt.subplot2grid(layout, (2, 0))
            pp_ax = plt.subplot2grid(layout, (2, 1))

            y.plot(ax=ts_ax)
            ts_ax.set_title('Time Series Analysis Plots')
            smt.graphics.plot_acf(y, lags=lags, ax=acf_ax, alpha=0.5)
            smt.graphics.plot_pacf(y, lags=lags, ax=pacf_ax, alpha=0.5)
            sm.qqplot(y, line='s', ax=qq_ax)
            qq_ax.set_title('QQ Plot')
            scs.probplot(y, sparams=(y.mean(), y.std()), plot=pp_ax)

            plt.tight_layout()
        return 
Example 11
Project: software-suite-movie-market-analysis   Author: 93lorenzo   File: forecast.py    GNU General Public License v3.0 6 votes vote down vote up
def tsplot(y, lags=None, figsize=(10, 8), style='bmh'):
    if not isinstance(y, pd.Series):
        y = pd.Series(y)
    with plt.style.context(style):
        fig = plt.figure(figsize=figsize)
        # mpl.rcParams['font.family'] = 'Ubuntu Mono'
        layout = (3, 2)
        ts_ax = plt.subplot2grid(layout, (0, 0), colspan=2)
        acf_ax = plt.subplot2grid(layout, (1, 0))
        pacf_ax = plt.subplot2grid(layout, (1, 1))
        qq_ax = plt.subplot2grid(layout, (2, 0))
        pp_ax = plt.subplot2grid(layout, (2, 1))

        y.plot(ax=ts_ax)
        ts_ax.set_title('Time Series Analysis Plots')
        smt.graphics.plot_acf(y, lags=lags, ax=acf_ax, alpha=0.5)
        smt.graphics.plot_pacf(y, lags=lags, ax=pacf_ax, alpha=0.5)
        sm.qqplot(y, line='s', ax=qq_ax)
        qq_ax.set_title('QQ Plot')
        scs.probplot(y, sparams=(y.mean(), y.std()), plot=pp_ax)

        plt.tight_layout()
    return 
Example 12
Project: neural-network-animation   Author: miloharper   File: test_tightlayout.py    MIT License 6 votes vote down vote up
def test_tight_layout4():
    'Test tight_layout for subplot2grid'

    fig = plt.figure()

    ax1 = plt.subplot2grid((3, 3), (0, 0))
    ax2 = plt.subplot2grid((3, 3), (0, 1), colspan=2)
    ax3 = plt.subplot2grid((3, 3), (1, 0), colspan=2, rowspan=2)
    ax4 = plt.subplot2grid((3, 3), (1, 2), rowspan=2)

    example_plot(ax1)
    example_plot(ax2)
    example_plot(ax3)
    example_plot(ax4)

    plt.tight_layout() 
Example 13
Project: Stock-Trading-Gym-Reinforcement-Learning   Author: yiz569   File: StockTradingGraph.py    MIT License 6 votes vote down vote up
def __init__(self, df, title=None):
        self.df = df
        self.net_worths = np.zeros(len(df['Date']))

        # Create a figure on screen and set the title
        fig = plt.figure()
        fig.suptitle(title)

        # Create top subplot for net worth axis
        self.net_worth_ax = plt.subplot2grid(
            (6, 1), (0, 0), rowspan=2, colspan=1)

        # Create bottom subplot for shared price/volume axis
        self.price_ax = plt.subplot2grid(
            (6, 1), (2, 0), rowspan=8, colspan=1, sharex=self.net_worth_ax)

        # Create a new axis for volume which shares its x-axis with price
        self.volume_ax = self.price_ax.twinx()

        # Add padding to make graph easier to view
        plt.subplots_adjust(left=0.11, bottom=0.24,
                            right=0.90, top=0.90, wspace=0.2, hspace=0)

        # Show the graph without blocking the rest of the program
        plt.show(block=False) 
Example 14
Project: python3_ios   Author: holzschu   File: test_tightlayout.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_tight_layout4():
    'Test tight_layout for subplot2grid'

    fig = plt.figure()

    ax1 = plt.subplot2grid((3, 3), (0, 0))
    ax2 = plt.subplot2grid((3, 3), (0, 1), colspan=2)
    ax3 = plt.subplot2grid((3, 3), (1, 0), colspan=2, rowspan=2)
    ax4 = plt.subplot2grid((3, 3), (1, 2), rowspan=2)

    example_plot(ax1)
    example_plot(ax2)
    example_plot(ax3)
    example_plot(ax4)

    plt.tight_layout() 
Example 15
Project: Py4Invst   Author: nealchenzhang   File: Stock_Market_Analysis_Basic.py    MIT License 6 votes vote down vote up
def returns_plot(self, start_date='2012-01-01', end_date='2012-12-31'):
        df = self.get_returns_data(start_date, end_date)
        df.reset_index(inplace=True)

        fig = plt.figure(figsize=(12,8))
        fig.suptitle('{}: Returns plot during {} and {}'.format(self.name,
                                                                start_date,
                                                                end_date),
                     fontsize=16)
        ax1 = plt.subplot2grid((2, 2), (0, 0), colspan=2)
        ax2 = plt.subplot2grid((2, 2), (1, 0))
        ax3 = plt.subplot2grid((2, 2), (1, 1))

        df['returns'].plot.hist(bins=50, color='b', ax=ax1, alpha=0.5)
        df['returns'].plot.kde(ax=ax1)
        ax1.set_title('Histogram')

        df['returns'].plot.box(colormap='jet', ax=ax2)
        ax2.set_title('Box Plot')

        ax3.scatter(x=df.index, y=df['returns'], alpha=0.5)
        ax3.set_title('Scatter Plot')

        # fig.savefig("{}_returns_{}_{}.png".format(self.name, start_date, end_date))
        plt.show() 
Example 16
Project: supremm   Author: ubccr   File: datadumper.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def __init__(self, title="Autoperiod", filename='output.pdf', figsize=(4, 3), verbose=False):
        self.title = title
        self.filename = filename
        self.fig = plt.figure()
        self.figsize = figsize
        self.verbose = verbose

        self.timeseries_ax = plt.subplot2grid((3, 10), (0, 0), colspan=9, xlabel='Times', ylabel='Values')

        self.area_ratio_ax = plt.subplot2grid((3, 10), (0, 9), colspan=1, xticks=(1, 2), xticklabels=("on", "off"))
        self.area_ratio_ax.get_yaxis().set_visible(False)

        self.periodogram_ax = plt.subplot2grid((3, 10), (1, 0), colspan=10, xlabel='Period', ylabel='Power')

        self.acf_ax = plt.subplot2grid((3, 10), (2, 0), colspan=10, xlabel='Lag', ylabel='Correlation')

        self.time_threshold = None 
Example 17
Project: linear_neuron   Author: uglyboxer   File: test_tightlayout.py    MIT License 6 votes vote down vote up
def test_tight_layout4():
    'Test tight_layout for subplot2grid'

    fig = plt.figure()

    ax1 = plt.subplot2grid((3, 3), (0, 0))
    ax2 = plt.subplot2grid((3, 3), (0, 1), colspan=2)
    ax3 = plt.subplot2grid((3, 3), (1, 0), colspan=2, rowspan=2)
    ax4 = plt.subplot2grid((3, 3), (1, 2), rowspan=2)

    example_plot(ax1)
    example_plot(ax2)
    example_plot(ax3)
    example_plot(ax4)

    plt.tight_layout() 
Example 18
Project: LiDAR_canopy   Author: DTMilodowski   File: canopy_structure_plots.py    GNU General Public License v3.0 6 votes vote down vote up
def plot_transmittance_ratio(figure_number,figure_name,pts):
    # A figure illustrating transmittance ratio between successive returns
    plt.figure(figure_number, facecolor='White',figsize=[3,3])
    ax = plt.subplot2grid((1,1),(0,0))
    ax.set_xlabel('return number, k')
    ax.set_ylabel(r'$\gamma$')
    for i in range(0,4):
        if i==0:
            ax.plot(1,1,'o',color='#1A2BCE')
        else:
            N_veg = float(np.all((pts[:,3]==i,pts[:,4]==1),axis=0).sum())
            N_i = float((pts[:,3]==i+1).sum())
            ax.plot(i+1,N_i/N_veg,'o',color='#1A2BCE')

    ax.set_ylim(0,1.1)
    ax.set_xlim(0.2,4.8)
    plt.xticks(np.arange(4)+1)
    plt.tight_layout()
    plt.savefig(figure_name)
    #plt.show()
    return 0 
Example 19
Project: pyta   Author: guiyanzhong   File: atr.py    MIT License 6 votes vote down vote up
def test_atr(ohlc):
    """ATR test function."""
    atr_indicator = atr(ohlc)

    # Plot the price series.
    ax1 = plt.subplot2grid((6,4), (0,0), rowspan=4, colspan=4)
    ax1.grid(True)
    ax1.plot(ohlc["close"])
    plt.ylabel("CLOSE")
    plt.title("ATR Chart")

    # Plot ATR.
    ax2 = plt.subplot2grid((6,4), (4,0), sharex=ax1, rowspan=2, colspan=4)
    ax2.grid(True)
    ax2.plot(atr_indicator)
    plt.ylabel("ATR")
    plt.setp(ax1.get_xticklabels(), visible=False)
    plt.show() 
Example 20
Project: pyta   Author: guiyanzhong   File: macd.py    MIT License 6 votes vote down vote up
def test_macd(closes):
    """MACD test function."""
    macd_indicator = macd(closes)
    data = macd_indicator
    # print(data)

    # Plot the price series.
    ax1 = plt.subplot2grid((6,4), (0,0), rowspan=4, colspan=4)
    ax1.grid(True)
    ax1.plot(closes)
    plt.ylabel("CLOSE")
    plt.title("MACD Chart")

    # Plot MACD.
    ax2 = plt.subplot2grid((6,4), (4,0), sharex=ax1, rowspan=2, colspan=4)
    ax2.grid(True)
    ax2.plot(data["macd"])
    ax2.plot(data["signal"])
    ax2.fill_between(data.index, data["divergence"], 0, alpha=0.5)
    plt.ylabel("MACD")
    plt.setp(ax1.get_xticklabels(), visible=False)
    plt.show() 
Example 21
Project: psychrometric-chart-makeover   Author: buds-lab   File: test_tightlayout.py    MIT License 6 votes vote down vote up
def test_tight_layout4():
    'Test tight_layout for subplot2grid'

    fig = plt.figure()

    ax1 = plt.subplot2grid((3, 3), (0, 0))
    ax2 = plt.subplot2grid((3, 3), (0, 1), colspan=2)
    ax3 = plt.subplot2grid((3, 3), (1, 0), colspan=2, rowspan=2)
    ax4 = plt.subplot2grid((3, 3), (1, 2), rowspan=2)

    example_plot(ax1)
    example_plot(ax2)
    example_plot(ax3)
    example_plot(ax4)

    plt.tight_layout() 
Example 22
Project: Stock_Market_Forecast   Author: cuevas1208   File: visualize.py    MIT License 5 votes vote down vote up
def axBarGraph(index,  ax1Data, ax2Data, barData):
        #displaying 100ma vs Adj Close
        ax1 = plt.subplot2grid((6,1), (0,0), rowspan=5, colspan=1)
        ax2 = plt.subplot2grid((6,1), (5,0), rowspan=1, colspan=1, sharex=ax1)
        ax1.xaxis_date()
        ax1.plot(index, ax1Data)
        ax1.plot(index, ax2Data)
        ax2.bar(index,  barData)
        plt.show() 
Example 23
Project: PyMO   Author: omimo   File: viz_tools.py    MIT License 5 votes vote down vote up
def viz_cnn_filter(feature_to_viz, mocap_track, data, gap=25):
    fig = plt.figure(figsize=(16,4))
    ax = plt.subplot2grid((1,8),(0,0))
    ax.imshow(feature_to_viz.T, aspect='auto', interpolation='nearest')
    
    ax = plt.subplot2grid((1,8),(0,1), colspan=7)
    for frame in range(feature_to_viz.shape[0]):
        frame_alpha = 0.2#frame/data.shape[0] * 2 + 0.2

        for joint_i, joint in enumerate(mocap_track.skeleton.keys()):
            children_to_draw = [c for c in mocap_track.skeleton[joint]['children']]

            parent_x = data['%s_Xposition'%joint][frame] + frame * gap
            parent_y = data['%s_Yposition'%joint][frame] 

            ax.scatter(x=parent_x, 
                       y=parent_y,  
                       alpha=0.6,
                       cmap='RdBu',
                       c=feature_to_viz[frame][joint_i] * 10000,
                       marker='o',
                       s = abs(feature_to_viz[frame][joint_i] * 10000))
            plt.axis('off')
            for c in children_to_draw:
                child_x = data['%s_Xposition'%c][frame] + frame * gap
                child_y = data['%s_Yposition'%c][frame] 

                ax.plot([parent_x, child_x], [parent_y, child_y], '-', lw=1, color='gray', alpha=frame_alpha) 
Example 24
Project: nmsat   Author: rcfduarte   File: signals.py    GNU General Public License v2.0 5 votes vote down vote up
def raster_plot(self, with_rate=False, ax=None, dt=1.0, display=True, save=False, **kwargs):
        """
        Plot a simple raster, for a quick check
        """
        if ax is None:
            fig = pl.figure()
            if with_rate:
                ax1 = pl.subplot2grid((30, 1), (0, 0), rowspan=23, colspan=1)
                ax2 = pl.subplot2grid((30, 1), (24, 0), rowspan=5, colspan=1, sharex=ax1)
                ax2.set(xlabel='Time [ms]', ylabel='Rate')
                ax1.set(ylabel='Neuron')
            else:
                ax1 = fig.add_subplot(111)
        else:
            if with_rate:
                assert isinstance(ax, list), "Incompatible properties... (with_rate requires two axes provided or " \
                                             "None)"
                ax1 = ax[0]
                ax2 = ax[1]
            else:
                ax1 = ax

        ax1.plot(self.raw_data()[:, 0], self.raw_data()[:, 1], '.', **kwargs)

        if with_rate:
            time = self.time_axis(dt)[:-1]
            rate = self.firing_rate(dt, average=True)
            ax2.plot(time, rate)
        ax1.set(ylim=[min(self.id_list), max(self.id_list)], xlim=[self.t_start, self.t_stop])

        if save:
            assert isinstance(save, str), "Please provide filename"
            pl.savefig(save)

        if display:
            pl.show(False) 
Example 25
Project: nmsat   Author: rcfduarte   File: visualization.py    GNU General Public License v2.0 5 votes vote down vote up
def plot_input_signal(self, ax=None, save=False, display=True, **kwargs):
        """
        """
        ax_props = {k: v for k, v in kwargs.iteritems() if k in ax.properties()}
        plot_props = {k: v for k, v in kwargs.iteritems() if k not in ax.properties()}

        if (ax is not None) and (not isinstance(ax, mpl.axes.Axes)):
            raise ValueError('ax must be matplotlib.axes.Axes instance.')
        if ax is None:
            fig = pl.figure()
            for ii in range(len(self.input.input_signal)):
                ax = pl.subplot2grid((len(self.input.input_signal), 1), (ii, 0), rowspan=1, colspan=1)
                ax.plot(self.input.time_data, self.input.input_signal[ii].signal, **plot_props)
                ax.set_ylabel(r'$\sigma_{u}$')
                if ii < len(self.input.input_signal) - 1:
                    ax.set_xticklabels('')
                    ax.set_xlim(left=min(self.input.time_data), right=max(self.input.time_data))
                else:
                    ax.set_xlabel('Time [ms]')
                    ax.set_xlim(left=min(self.input.time_data), right=max(self.input.time_data))
                ax.set_ylim([min(self.input.input_signal[ii].signal)-10., max(self.input.input_signal[ii].signal)+10.])
                ax.set(**ax_props)
        else:
            for ii in range(len(self.input.input_signal)):
                ax.plot(self.input.time_data, self.input.input_signal[ii].signal, **plot_props)
                ax.set_xlim([min(self.input.time_data), max(self.input.time_data)])
                ax.set_ylim([min(self.input.input_signal[ii].signal)-10., max(self.input.input_signal[ii].signal)+10.])
                ax.set_xlabel('Time [ms]')
                ax.set_ylabel(r'$\sigma_{u}$')
                ax.set(**ax_props)
        if display:
            pl.show(False)
        if save:
            assert isinstance(save, str), "Please provide filename"
            if not os.path.exists(save+'_InputTimeSeries.pdf'):
                pl.savefig(save+'_InputTimeSeries.pdf')
            else: # cases when the function is called twice
                pl.savefig(save+'_InputTimeSeries2.pdf') 
Example 26
Project: nmsat   Author: rcfduarte   File: visualization.py    GNU General Public License v2.0 5 votes vote down vote up
def plot_noise_component(self, ax=None, save=False, display=True):
        """
        """
        if (ax is not None) and (not isinstance(ax, mpl.axes.Axes)):
            raise ValueError('ax must be matplotlib.axes.Axes instance.')
        if ax is None:
            fig = pl.figure()
            for ii in range(len(self.noise.noise_signal)):
                ax = pl.subplot2grid((len(self.noise.noise_signal), 1), (ii, 0), rowspan=1,
                                     colspan=1)
                ax.plot(self.noise.noise_signal[ii].time_axis(), self.noise.noise_signal[
                    ii].signal)
                ax.set_ylabel(r'$\sigma_{u}$')
                if ii < len(self.noise.noise_signal) - 1:
                    ax.set_xticklabels('')
                    ax.set_xlim(min(self.noise.time_data), max(self.noise.time_data))
                else:
                    ax.set_xlabel('Time [ms]')
                    ax.set_xlim(min(self.noise.time_data), max(self.noise.time_data))
        else:
            for ii in range(len(self.noise.noise_signal)):
                ax.plot(self.noise.noise_signal[ii].time_axis(), self.noise.noise_signal[ii].signal)
            # if self.start and self.stop:
            # 	ax.set_xlim(left=self.start, right=self.stop)
            # else:
            ax.set_xlim(left=min(self.input.time_data), right=max(self.input.time_data))
        if display:
            pl.show(False)
        if save:
            assert isinstance(save, str), "Please provide filename"
            pl.savefig(save+'NoiseTimeSeries.pdf') 
Example 27
Project: CR0FT   Author: dafyddg   File: modggraphics.py    GNU General Public License v3.0 5 votes vote down vote up
def spectrogramplot(duration,fs,y,fr,fc,rn,cn,rs,cs,title):

    if howmanyplots == 'multipleplots':
        fig = plt.figure(1,figsize=(10,3))

    ax5 = plt.subplot2grid((1,1), (0,0),rowspan=2,colspan=1)
#    ax5 = plt.subplot2grid((fr,fc), (rn,cn),rowspan=rs,colspan=cs)
    ax5.set_title("Spectrogram", fontsize=fontsize)
    plt.ylabel('Freq [Hz]',fontsize=fontsize)
    plt.grid(color='b', linestyle='--', linewidth=1)

    specmin = 0
    specmax = 1000
    nykvistspect = int(round(fs/2.0))
    if nykvistspect < 3000:
        specmax = nykvistspect
    specwinfactor = 0.01
    specwin = int(float(65536*specwinfactor))

    NFFT = specwin
    ax5.specgram(y, NFFT=NFFT, Fs=fs)
    plt.axis(ymin=specmin, ymax=specmax)
    ax5.set_xlim(0.0,np.ceil(duration))

    if howmanyplots == 'multipleplots':
        plt.tight_layout()
        webfilename = '/Webtmp/s0ftspectrogram.png'
        localfilename = '/var/www/Webtmp/s0ftspectrogram.png'
        print '<tr align=\"center\"><td><img src='+webfilename+' width=\"100%\"></td></tr>'
        plt.savefig(localfilename)
        plt.close('all')

    return rn+rs, cn

#==================================================================

#==============================================================
# Butterworth filters
# Source: adapted from various internet Q&A sites 
Example 28
Project: ble5-nrf52-mac   Author: tomasero   File: test_tightlayout.py    MIT License 5 votes vote down vote up
def test_badsubplotgrid():
    # test that we get warning for mismatched subplot grids rather
    # than an error
    ax1 = plt.subplot2grid((4, 5), (0, 0))
    # this is the bad entry:
    ax5 = plt.subplot2grid((5, 5), (0, 3), colspan=3, rowspan=5)
    with warnings.catch_warnings(record=True) as w:
        plt.tight_layout()
        assert len(w) == 1 
Example 29
Project: NTM-Keras   Author: SigmaQuan   File: visualization.py    MIT License 5 votes vote down vote up
def update(self, matrix_list, name_list):
        # draw first line
        axes_input = plt.subplot2grid((3, 1), (0, 0), colspan=1)
        axes_input.set_aspect('equal')
        plt.imshow(matrix_list[0], interpolation='none')
        axes_input.set_xticks([])
        axes_input.set_yticks([])

        # draw second line
        axes_output = plt.subplot2grid((3, 1), (1, 0), colspan=1)
        plt.imshow(matrix_list[1], interpolation='none')
        axes_output.set_xticks([])
        axes_output.set_yticks([])

        # draw third line
        axes_predict = plt.subplot2grid((3, 1), (2, 0), colspan=1)
        plt.imshow(matrix_list[2], interpolation='none')
        axes_predict.set_xticks([])
        axes_predict.set_yticks([])

        # # add text
        # plt.text(-2, -19.5, name_list[0], ha='right')
        # plt.text(-2, -7.5, name_list[1], ha='right')
        # plt.text(-2, 4.5, name_list[2], ha='right')
        # plt.text(6, 10, 'Time $\longrightarrow$', ha='right')

        # set tick labels invisible
        make_tick_labels_invisible(plt.gcf())
        # adjust spaces
        plt.subplots_adjust(hspace=0.05, wspace=0.05, bottom=0.1, right=0.8, top=0.9)
        # add color bars
        # *rect* = [left, bottom, width, height]
        cax = plt.axes([0.85, 0.125, 0.015, 0.75])
        plt.colorbar(cax=cax)

        # show figure
        # plt.show()
        plt.draw()
        plt.pause(0.025)
        # plt.pause(15) 
Example 30
Project: PYRO-NN   Author: csyben   File: evaluation.py    Apache License 2.0 5 votes vote down vote up
def evaluation_filter(filter_one, filter_two, filter_three, output, dpi=600):
    fig = plt.figure(figsize=(20,10))

    zoomed_filter = plt.subplot2grid((1, 2), (0, 0))
    filter = plt.subplot2grid((1, 2), (0, 1))
    line_width = 5.0
    zoomed_filter.plot(np.arange(len(filter_one)),filter_one, linestyle='-.', color='#2ca02c',linewidth=line_width)
    zoomed_filter.plot(np.arange(len(filter_two)),filter_two,linestyle=':', color='#1f77b4',linewidth=line_width)
    zoomed_filter.plot(np.arange(len(filter_three)),filter_three,linestyle='--', color='#ff7f0e',linewidth=line_width)
    zoomed_filter.axes.set_xlim([0,len(filter_one)*0.005])
    zoomed_filter.axes.set_ylim([0, 0.005])
    zoomed_filter.tick_params(labelsize=24)
    zoomed_filter.legend(['Ramp', 'Ram-Lak', 'Learned'], loc='upper left',prop={'size': 28})

    shifted_filter_two = np.fft.ifftshift(filter_two, axes=0)
    shifted_filter_three = np.fft.ifftshift(filter_three, axes=0)

    interval = np.arange((-len(filter_one)//2)+1,(len(filter_one)//2)+1,1)
    filter.plot(interval, shifted_filter_two, color='#1f77b4',linewidth=line_width)
    filter.plot(interval, shifted_filter_three, linestyle='--', color='#ff7f0e',linewidth=line_width)
    filter.plot(interval, filter_two-filter_three, color='red',linewidth=line_width)
    filter.legend(['Ram-Lak', 'Learned', 'Diff.'], loc='upper center',prop={'size': 28})
    filter.tick_params(labelsize=24)
    plt.tight_layout()
    plt.savefig(output, dpi=dpi, transparent=False, bbox_inches='tight')
    fig.show() 
Example 31
Project: RPGOne   Author: RTHMaK   File: plot_scaling.py    Apache License 2.0 5 votes vote down vote up
def plot_scaling():
    X, y = make_blobs(n_samples=50, centers=2, random_state=4, cluster_std=1)
    X += 3

    plt.figure(figsize=(15, 8))
    main_ax = plt.subplot2grid((2, 4), (0, 0), rowspan=2, colspan=2)

    main_ax.scatter(X[:, 0], X[:, 1], c=y, cmap=cm2, s=60)
    maxx = np.abs(X[:, 0]).max()
    maxy = np.abs(X[:, 1]).max()

    main_ax.set_xlim(-maxx + 1, maxx + 1)
    main_ax.set_ylim(-maxy + 1, maxy + 1)
    main_ax.set_title("Original Data")
    other_axes = [plt.subplot2grid((2, 4), (i, j)) for j in range(2, 4) for i in range(2)]

    for ax, scaler in zip(other_axes, [StandardScaler(), RobustScaler(),
                                       MinMaxScaler(), Normalizer(norm='l2')]):
        X_ = scaler.fit_transform(X)
        ax.scatter(X_[:, 0], X_[:, 1], c=y, cmap=cm2, s=60)
        ax.set_xlim(-2, 2)
        ax.set_ylim(-2, 2)
        ax.set_title(type(scaler).__name__)

    other_axes.append(main_ax)

    for ax in other_axes:
        ax.spines['left'].set_position('center')
        ax.spines['right'].set_color('none')
        ax.spines['bottom'].set_position('center')
        ax.spines['top'].set_color('none')
        ax.xaxis.set_ticks_position('bottom')
        ax.yaxis.set_ticks_position('left') 
Example 32
Project: python3_ios   Author: holzschu   File: test_tightlayout.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_badsubplotgrid():
    # test that we get warning for mismatched subplot grids rather
    # than an error
    ax1 = plt.subplot2grid((4, 5), (0, 0))
    # this is the bad entry:
    ax5 = plt.subplot2grid((5, 5), (0, 3), colspan=3, rowspan=5)
    with warnings.catch_warnings(record=True) as w:
        plt.tight_layout()
        assert len(w) == 1 
Example 33
Project: mpl_finance_ext   Author: z33pX   File: utils.py    MIT License 5 votes vote down vote up
def head(kwargs):

    fig = kwargs.get('fig', None)
    if fig is None:
        fig, _ = plt.subplots(facecolor=config['colors']['background'])

    ax = kwargs.get('axis', None)
    if ax is None:
        ax = plt.subplot2grid(
            (4, 4), (0, 0),
            rowspan=4, colspan=4,
            facecolor=config['colors']['background']
        )
    return fig, ax 
Example 34
Project: ar-pde-cnn   Author: cics-nd   File: plotMSE.py    MIT License 5 votes vote down vote up
def plotError(tT, mse_errors, mse_errors_bayes):
    '''
    Creates grid of 4 different test cases, plots target, prediction, variance and error for each
    '''
    plt.close("all")
    # Create figure
    mpl.rcParams['font.family'] = ['serif'] # default is sans-serif
    rc('text', usetex=True)

    fig = plt.figure(figsize=(8, 4))
    ax = []
    ax.append(plt.subplot2grid((1, 1), (0, 0), colspan=1))

    ax[0].plot(tT, np.mean(mse_errors, axis=0), '-', c='r', label='AR-DenseED')
    ax[0].plot(tT, np.mean(mse_errors_bayes, axis=0), '--', c='b', label='BAR-DenseED')

    ax[0].set_xlabel('t', fontsize=14)
    ax[0].set_ylabel('MSE', fontsize=14)
    ax[0].legend(loc='upper left')

    file_dir = '.'
    # If directory does not exist create it
    if not os.path.exists(file_dir):
        os.makedirs(file_dir)
    file_name = file_dir+"/ks_MSE"
    plt.savefig(file_name+".png", bbox_inches='tight')
    plt.savefig(file_name+".pdf", bbox_inches='tight')
    plt.show() 
Example 35
Project: ar-pde-cnn   Author: cics-nd   File: plotARContour.py    MIT License 5 votes vote down vote up
def plotPred(t, xT, uPred, uTarget, ncases=3):
    '''
    Plots prediction contour
    '''
    plt.close("all")
    # Create figure
    mpl.rcParams['font.family'] = ['serif'] # default is sans-serif
    rc('text', usetex=True)

    fig = plt.figure(figsize=(16, 10))
    ax = [[] for i in range(ncases)]
    for i in range(ncases):
        ax[i].append(plt.subplot2grid((3, 7*ncases), (0, 7*i), colspan=6))
        ax[i].append(plt.subplot2grid((3, 7*ncases), (1, 7*i), colspan=6))
        ax[i].append(plt.subplot2grid((3, 7*ncases), (2, 7*i), colspan=6))

    ax = np.array(ax).T

    plotTestCase(fig, ax[:,0], t, xT, uPred[0].T, uTarget[0].T, cbar=False)
    plotTestCase(fig, ax[:,1], t, xT, uPred[1].T, uTarget[1].T, cbar=False)
    plotTestCase(fig, ax[:,2], t, xT, uPred[2].T, uTarget[2].T, cbar=True)

    file_dir = '.'
    # If directory does not exist create it
    if not os.path.exists(file_dir):
        os.makedirs(file_dir)

    file_name = file_dir+"/ks_AR_Pred"
    plt.savefig(file_name+".png", bbox_inches='tight')
    plt.savefig(file_name+".pdf", bbox_inches='tight')
    plt.show() 
Example 36
Project: TensorFlow_DCIGN   Author: yselivonchyk   File: video_builder.py    MIT License 5 votes vote down vote up
def _show_image(img, original=True):
  # index = 322 if original else 326
  index = (0, 1) if original else (4, 1)
  # ax = plt.subplot(index)
  ax = plt.subplot2grid((7, 2), index, rowspan=3)
  ax.imshow(img)
  ax.set_title('Original' if original else 'Reconstruction')
  ax.axis('off') 
Example 37
Project: TensorFlow_DCIGN   Author: yselivonchyk   File: video_builder.py    MIT License 5 votes vote down vote up
def animate(cur, enc, img, reco):
  fig = vis.get_figure()

  original = data_to_img(img[cur])
  reconstr = data_to_img(reco[cur])

  _show_image(original)
  _show_image(reconstr, original=False)

  # animation
  ax = plt.subplot2grid((7, 2), (0, 0), rowspan=7, projection='3d')
  ax.set_title('Trajectory')
  ax.axes.get_xaxis().set_ticks([])
  ax.axes.get_yaxis().set_ticks([])
  ax.set_zticks([])

  if enc.shape[1] > 3:
    enc = enc[:, :4]

  # white
  data = enc[cur:]
  ax.scatter(data[:, 0], data[:, 1], data[:, 2], c='w', s=1, zorder=15)
  # old
  tail_len = max(0, cur - TAIL_LENGTH)
  # print(tail_len)
  if tail_len > 0:
    data = enc[:tail_len]
    ax.scatter(data[:, 0], data[:, 1], data[:, 2], c='black', zorder=10, s=1,)
  # recent
  for i in range(0, -TAIL_LENGTH, -1):
    j = i + cur
    if j >= 0:
      # print(cur, i)
      data = enc[j]
      ax.scatter(data[0], data[1], data[2], c='b', s=(i+TAIL_LENGTH)/5, zorder=5)

  plt.show() 
Example 38
Project: retain-keras   Author: Optum   File: retain_evaluation.py    Apache License 2.0 5 votes vote down vote up
def probability_calibration(y_true, y_prob,graph):
    if graph:
        fig_index = 1
        name = 'My pred'
        n_bins = 20
        fig = plt.figure(fig_index, figsize=(10, 10))
        ax1 = plt.subplot2grid((3, 1), (0, 0), rowspan=2)
        ax2 = plt.subplot2grid((3, 1), (2, 0))

        ax1.plot([0, 1], [0, 1], "k:", label="Perfectly calibrated")

        fraction_of_positives, mean_predicted_value = \
            calibration_curve(y_true, y_prob, n_bins=n_bins, normalize=True)

        ax1.plot(mean_predicted_value, fraction_of_positives,
                 label=name)

        ax2.hist(y_prob, range=(0, 1), bins=n_bins, label=name,
                 histtype="step", lw=2)

        ax1.set_ylabel("Fraction of Positives")
        ax1.set_ylim([-0.05, 1.05])
        ax1.legend(loc="lower right")
        ax1.set_title('Calibration Plots  (Reliability Curve)')

        ax2.set_xlabel("Mean predicted value")
        ax2.set_ylabel("Count")
        ax2.legend(loc="upper center", ncol=2)
        print('Probability Calibration Curves saved to calibration.png')
        plt.tight_layout()
        plt.savefig('calibration.png') 
Example 39
Project: Python-Image-Processing   Author: amirfrsd   File: main.py    MIT License 5 votes vote down vote up
def recognitionFunc(filePath):
    recognized=[]
    exampleNumberColors=open('numtext.txt','r').read()
    exampleNumberColors=exampleNumberColors.split('\n')
    i=Image.open(filePath)
    iArray=np.array(i)
    iArrayList=iArray.tolist()
    inquestion=str(iArrayList)
    for examples in exampleNumberColors:
        if(len(examples)>3):
            splitTexts=examples.split('::')
            numberIs=splitTexts[0]
            pixelArrayIs=splitTexts[1]
            eachPixelEx=pixelArrayIs.split('],')
            eachPixelInq=inquestion.split('],')
            a=0
            while(a<len(eachPixelEx)):
                if(eachPixelEx[a]==eachPixelInq[a]):
                    recognized.append(int(numberIs))
                a += 1
    c=Counter(recognized)
    print(c)
    print(max(c.values()))
    xAxis=[]
    yAxis=[]
    for eachNumber in c:
        xAxis.append(eachNumber)
        yAxis.append(c[eachNumber])
    ax1=plot.subplot2grid((4,4),(0,0),rowspan=1,colspan=4)
    ax2=plot.subplot2grid((4,4),(1,0),rowspan=3,colspan=4)
    ax1.imshow(iArray)
    print(xAxis,yAxis)
    ax2.bar(xAxis,yAxis,align="center")
    plot.ylim(350)
    plot.show() 
Example 40
Project: LSDTopoTools_MarshPlatform   Author: LSDtopotools   File: LSDMarshPlatform_Plots.py    GNU General Public License v3.0 5 votes vote down vote up
def Plot_platform_on_hillshade(Input_dir =  "/LSDTopoTools/LSDTopoTools_MarshPlatform/Example_data/", 
            Output_dir = "/LSDTopoTools/LSDTopoTools_MarshPlatform/Example_data/",
            Sites = ["FEL"]):
    """
    This plots the extracted marsh platform on a hillshade
    
    Args:
        Input_dir (str): Name your data input directory
        Output_dir (str): Name your results output directory
        Sites (str list): A list of strings. The file names are modified based on these sites
        
    Author: GCHG
    """
    #Plot 1: Draw the platform on a DEM, superimposed on a hillshade
    for site in Sites:
        fig=plt.figure(1, facecolor='White',figsize=[10,10])
        ax1 = plt.subplot2grid((1,1),(0,0),colspan=1, rowspan=1)

        # Name the axes
        ax1.set_xlabel('x (m)', fontsize = 12)
        ax1.set_ylabel('y (m)', fontsize = 12)

        # Load the relevant data
        HS, post_HS, envidata_HS = ENVI_raster_binary_to_2d_array (Input_dir+"%s_hs.bil" % (site), site)
        DEM, post_DEM, envidata_DEM = ENVI_raster_binary_to_2d_array (Input_dir+"%s.bil" % (site), site)
        Platform, post_Platform, envidata_Platform = ENVI_raster_binary_to_2d_array (Output_dir+"%s_Marsh.bil" % (site), site)


        # Make a mask!
        Platform_mask = np.ma.masked_where(Platform <=0, Platform)
        Platform_mask[Platform_mask>0] = DEM[Platform_mask>0]

        # Make a map!
        #Map_HS = ax1.imshow(HS, interpolation='None', cmap=plt.cm.gist_gray, vmin = 100, vmax = 200)
        Map_DEM = ax1.imshow(DEM, interpolation='None', cmap=plt.cm.gist_gray, vmin = np.amin(DEM[DEM!=Nodata_value]), vmax = np.amax(DEM), alpha = 0.5)
        #Map_Marsh = ax1.imshow(Platform_mask, interpolation='None', cmap=plt.cm.gist_earth, vmin=np.amin(DEM[DEM!=Nodata_value]), vmax=np.amax(DEM), alpha = 0.5)

        plt.savefig(Output_dir+'Platform_DEM_%s.png' % (site)) 
Example 41
Project: LSDTopoTools_MarshPlatform   Author: LSDtopotools   File: LSDMarshPlatform_Plots.py    GNU General Public License v3.0 5 votes vote down vote up
def Plot_confusion_map_on_hillshade(Input_dir =  "/LSDTopoTools/LSDTopoTools_MarshPlatform/Example_data/", 
            Output_dir = "/LSDTopoTools/LSDTopoTools_MarshPlatform/Example_data/",
            Sites = ["FEL"]):
    """
    This draws the marsh reference on a hillshade
    
    Args:
        Input_dir (str): Name your data input directory.
        Output_dir (str): Name your results output directory.
        Sites (str list): A list of strings. The file names are modified based on these sites.
        
    Author: GCHG
    """
    #Plot 4: Draw the confusion map, superimposed on a hillshade
    for site in Sites:
        fig=plt.figure(4, facecolor='White',figsize=[10,10])
        ax1 = plt.subplot2grid((1,1),(0,0),colspan=1, rowspan=1)


        # Name the axes
        ax1.set_xlabel('x (m)', fontsize = 12)
        ax1.set_ylabel('y (m)', fontsize = 12)

        # Load the relevant data
        HS, post_HS, envidata_HS = ENVI_raster_binary_to_2d_array (Input_dir+"%s_DEM_hs.bil" % (site), site)
        Confusion, post_Confusion, envidata_Confusion = ENVI_raster_binary_to_2d_array (Output_dir+"%s_Confusion.bil" % (site), site)


        # Make a mask!
        Confusion_mask = np.ma.masked_where(Confusion == Nodata_value, Confusion)


        # Make a map!
        Map_HS = ax1.imshow(HS, interpolation='None', cmap=plt.cm.gist_gray, vmin = 100, vmax = 200)
        Map_DEM = ax1.imshow(Confusion_mask, interpolation='None', cmap=plt.cm.Spectral, vmin = -2, vmax = 2, alpha = 0.5)


    plt.savefig(Output_dir+'Confusion_%s.png' % (site)) 
Example 42
Project: em_examples   Author: geoscixyz   File: FDEMpipe.py    MIT License 5 votes vote down vote up
def fempipeWidget(alpha, pipedepth):
    respEW, respNS, X, Y = fempipe(alpha, pipedepth)
    fig = plt.figure(figsize = (12, 9))
    ax0 = plt.subplot2grid((2,2), (0,0))
    ax1 = plt.subplot2grid((2,2), (0,1))
    ax2 = plt.subplot2grid((2,2), (1,0), colspan=2)

    dat0 = ax0.imshow(respEW.real*100, extent=[X.min(),X.max(),Y.min(),Y.max()])
    dat1 = ax1.imshow(respNS.real*100, extent=[X.min(),X.max(),Y.min(),Y.max()])
    cb0 = plt.colorbar(dat0, ax = ax0)
    cb1 = plt.colorbar(dat1, ax = ax1)
    ax0.set_title("In-phase EW boom (%)", fontsize = 12)
    ax1.set_title("In-phase NS boom (%)", fontsize = 12)
    ax0.set_xlabel("Easting (m)", fontsize = 12)
    ax1.set_xlabel("Easting (m)", fontsize = 12)
    ax0.set_ylabel("Northing (m)", fontsize = 12)
    ax1.set_ylabel("Northing (m)", fontsize = 12)
    ax0.plot(np.r_[0., 0.], np.r_[-10., 10.], 'k--', lw=2)
    ax1.plot(np.r_[0., 0.], np.r_[-10., 10.], 'k--', lw=2)

    ax2.plot(Y[:,20],respEW[:, 20].real, 'k.-')
    ax2.plot(Y[:,20],respEW[:, 20].imag, 'k--')
    ax2.plot(Y[:,20],respNS[:, 20].real, 'r.-')
    ax2.plot(Y[:,20],respNS[:, 20].imag, 'r--')
    ax2.legend(('In-phase EW boom', 'Out-of-phase EW boom', 'In-phase NS boom', 'Out-of-phase NS boom'),loc=4)
    ax2.grid(True)
    ax2.set_ylabel('Hs/Hp (%)', fontsize = 16)
    ax2.set_xlabel('Northing (m)', fontsize = 16)
    ax2.set_title('Northing profile line at Easting 0 m', fontsize = 16)

    plt.tight_layout()
    plt.show() 
Example 43
Project: gazeGenNet   Author: r-zemblys   File: etdata.py    MIT License 5 votes vote down vote up
def plot(self, spath = None, save=False, show=True, title=None):
        '''Plots trial
        '''
        if show:
            plt.ion()
        else:
            plt.ioff()

        fig = plt.figure(figsize=(10,6))
        ax00 = plt.subplot2grid((2, 2), (0, 0))
        ax10 = plt.subplot2grid((2, 2), (1, 0), sharex=ax00)
        ax01 = plt.subplot2grid((2, 2), (0, 1), rowspan=2)

        ax00.plot(self.data['t'], self.data['x'], '-')
        ax10.plot(self.data['t'], self.data['y'], '-')
        ax01.plot(self.data['x'], self.data['y'], '-')
        for e, c in ETData.evt_color_map.iteritems():
            mask = self.data['evt'] == e
            ax00.plot(self.data['t'][mask], self.data['x'][mask], '.', color = c)
            ax10.plot(self.data['t'][mask], self.data['y'][mask], '.', color = c)
            ax01.plot(self.data['x'][mask], self.data['y'][mask], '.', color = c)

        etdata_extent = np.nanmax([np.abs(self.data['x']), np.abs(self.data['y'])])+1

        ax00.axis([self.data['t'].min(), self.data['t'].max(), -etdata_extent, etdata_extent])
        ax10.axis([self.data['t'].min(), self.data['t'].max(), -etdata_extent, etdata_extent])
        ax01.axis([-etdata_extent, etdata_extent, -etdata_extent, etdata_extent])

        #sns.despine()
        if title is not None:
            plt.suptitle(title)
        plt.tight_layout()

        if save and not(spath is None):
            plt.savefig('%s.png' % (spath))
            plt.close() 
Example 44
Project: pyta   Author: guiyanzhong   File: dchannel.py    MIT License 5 votes vote down vote up
def test_dchannel(ohlc):
    """DCHANNEL test function."""
    dchannel10 = dchannel(ohlc, 10)
    data = pd.concat([ohlc, dchannel10], axis=1)
    # print(data)
    ax1 = plt.subplot2grid((6,4), (0,0), rowspan=6, colspan=6)
    ax1.grid(True)
    candlestick2_ochl(ax1, ohlc["open"], ohlc["close"], ohlc["high"], ohlc["low"], width=0.7, colorup="r", colordown="g")
    ax1.plot(dchannel10)
    plt.title("DCHANNEL Chart")
    plt.show() 
Example 45
Project: psychrometric-chart-makeover   Author: buds-lab   File: test_tightlayout.py    MIT License 5 votes vote down vote up
def test_badsubplotgrid():
    # test that we get warning for mismatched subplot grids rather
    # than an error
    ax1 = plt.subplot2grid((4, 5), (0, 0))
    # this is the bad entry:
    ax5 = plt.subplot2grid((5, 5), (0, 3), colspan=3, rowspan=5)
    with warnings.catch_warnings(record=True) as w:
        plt.tight_layout()
        assert len(w) == 1 
Example 46
Project: bearing-vibration-diagnostics-toolbox   Author: andrek10   File: plt.py    MIT License 4 votes vote down vote up
def figure(nh, nw, width=238.0, height=133.0, axesLoc=None, sharex=False):
    '''
	Makes a new figure with custom columns and rows, and custom size
	
	Parameters
	----------
    nh : int
        Number of ax rows
    nw : int
        Number of ax columns
    width : float, optional
        Width of figure in pixels
    height : float, optional
        Height of figure in pixels
    axesLoc : tupple of tupples
        Wrapper for complete custom axes placement and sizes.
        Each element in the first tupple should contain (position y, position x, size in y, size in x)
        Best explained with an example:

        - axesLoc = ( (1,1,1,2), (2,1,1,2), (1,3,1,1), (2,3,1,1) )
	
	Returns
	-------
	fig : figure object
        Reference to the figure
    axes : axes objects in 1D array
        All axes in a row-major configuration
	'''
    
    fig, ax = plt.subplots(nh, nw, figsize=(width/72.0, height/72.0), frameon=False, sharex=sharex)
    if axesLoc is not None:
        ax = ax.ravel()
        for a in ax:
            a.axis('off')
        ax = []
        for i in range(0, len(axesLoc)):
            t = axesLoc[i]
            ax.append(plt.subplot2grid( (nh,nw), (t[0]-1,t[1]-1), rowspan=t[2], colspan=t[3] ))
        ax = np.array(ax)
    
    if type(ax) == np.ndarray:
        axes = ax.ravel()
    else:
        axes = ax
        
    return fig, axes 
Example 47
Project: nmsat   Author: rcfduarte   File: visualization.py    GNU General Public License v2.0 4 votes vote down vote up
def plot_averaged_time_resolved(results, spike_list, label='', epochs=None, color_map='jet', display=True, save=False):
    """

    :param results:
    :param spike_list:
    :param label:
    :param epochs:
    :param color_map:
    :param display:
    :param save:
    :return:
    """
    # time resolved regularity
    fig5 = pl.figure()
    fig5.suptitle('{0} - Time-resolved regularity'.format(str(label)))
    stats = ['isi_5p_profile', 'cvs_profile', 'cvs_log_profile', 'lvs_profile', 'iR_profile', 'ents_profile']
    cm = get_cmap(len(stats), color_map)

    for idx, n in enumerate(stats):
        ax 			= fig5.add_subplot(len(stats), 1, idx + 1)
        data_mean 	= np.array([results[n][i][0] for i in range(len(results[n]))])
        data_std 	= np.array([results[n][i][1] for i in range(len(results[n]))])
        t_axis 		= np.linspace(spike_list.t_start, spike_list.t_stop, len(data_mean))

        ax.plot(t_axis, data_mean, c=cm(idx), lw=2.5)
        ax.fill_between(t_axis, data_mean - data_std, data_mean + data_std, facecolor=cm(idx), alpha=0.2)
        ax.set_ylabel(n)
        ax.set_xlabel('Time [ms]')
        ax.set_xlim(spike_list.time_parameters())
        if epochs is not None:
            mark_epochs(ax, epochs, color_map)

    # activity plots
    fig6 = pl.figure()
    fig6.suptitle('{0} - Activity Analysis'.format(str(label)))
    ax61 = pl.subplot2grid((25, 1), (0, 0), rowspan=20, colspan=1)
    ax62 = pl.subplot2grid((25, 1), (20, 0), rowspan=5, colspan=1)
    pretty_raster(spike_list, analysis_interval=[spike_list.t_start, spike_list.t_stop], n_total_neurons=1000, ax=ax61)
    # plot_raster(spike_list, 1., ax61, sub_set=100, **{'color': 'k', 'alpha': 0.8, 'marker': '|', 'markersize': 2})
    stats = ['ffs_profile']

    cm = get_cmap(len(stats), color_map)
    for idx, n in enumerate(stats):
        data_mean = np.array([results[n][i][0] for i in range(len(results[n]))])
        data_std = np.array([results[n][i][1] for i in range(len(results[n]))])
        t_axis = np.linspace(spike_list.t_start, spike_list.t_stop, len(data_mean))
        ax62.plot(t_axis, data_mean, c=cm(idx), lw=2.5)
        ax62.fill_between(t_axis, data_mean - data_std, data_mean +
                          data_std, facecolor=cm(idx), alpha=0.2)
        ax62.set_ylabel(r'$\mathrm{FF}$')
        ax62.set_xlabel('Time [ms]')
        ax62.set_xlim(spike_list.time_parameters())
    if epochs is not None:
        mark_epochs(ax61, epochs, color_map)
        mark_epochs(ax62, epochs, color_map)

    if display:
        pl.show(False)
    if save:
        fig5.savefig(save + '{0}_time_resolved_reg.pdf'.format(str(label)))
        fig6.savefig(save + '{0}_activity_analysis.pdf'.format(str(label))) 
Example 48
Project: CR0FT   Author: dafyddg   File: modggraphics.py    GNU General Public License v3.0 4 votes vote down vote up
def waveformplot(duration,fs,signal,fr,fc,rn,cn,rs,cs,title,xlabel,legend, envelopeflag):

    if howmanyplots == 'multipleplots':
        fig = plt.figure(1,figsize=(10,3))

    ax1 = plt.subplot2grid((1,1), (0,0),rowspan=2,colspan=1)
#    ax1 = plt.subplot2grid((fr,fc), (rn,cn),rowspan=rs,colspan=cs)
    ax1.set_title(title,fontsize=fontsize)
    plt.grid(linewidth=2,which='both', axis='x')

    ax1.set_ylabel('Rectified Amplitude')
    y = signal
    y = np.array(y)
    y = abs(y)

    x = [ 1.0*x/fs for x in range(len(y)) ]

    plt.plot(x, y, color='lightblue', linewidth=5)
    ax1.set_yticks([])

    if envelopeflag:
        k = int(round(fs * 0.02))	# peak search window length in samples
        envelope = envelopecalc(y,k)
        ax1.set_ylim(0, max(max(y),max(envelope))*1.05)
        plt.plot(x,envelope,linewidth=6,color='pink')
        plt.plot(x,envelope,linewidth=1,color='r')
    else:
        ax1.set_ylim(-0.1, max(y)*1.05)

    xmin = -0.01
    xmax = np.ceil(x[-1])+0.01

    plt.hlines(0,xmin,xmax)
    ax1.set_xlim(xmin,xmax)

    plt.legend(legend,fontsize=fontsize-3)

    if howmanyplots == 'multipleplots':
        plt.tight_layout()
        webfilename = '/Webtmp/s0ftwaveform.png'
        localfilename = '/var/www/Webtmp/s0ftwaveform.png'
        plt.savefig(localfilename)
        print '<tr align=\"center\"><td><img src='+webfilename+' width=\"100%\"></td></tr>'
        plt.close('all')

    return rn+rs, cn
#============================================================================== 
Example 49
Project: CR0FT   Author: dafyddg   File: modggraphics.py    GNU General Public License v3.0 4 votes vote down vote up
def f0plot(duration,f0vector,z, proctime, fr,fc,rn,cn,rs,cs,comparisonflag,title,xlabel, legend, color, flag):

    if howmanyplots == 'multipleplots':
        fig = plt.figure(1,figsize=(10,3))

    ax3 = plt.subplot2grid((1,1), (0,0),rowspan=2,colspan=1)
#    ax3 = plt.subplot2grid((fr,fc), (rn,cn),rowspan=rs,colspan=cs)
    ax3.set_title(title,fontsize=fontsize)
    ax3.set_xlabel(xlabel + " (processing time: "+proctime+"s)")

    plt.ylabel('Freq [Hz]',fontsize=fontsize)
    plt.grid(color='b', linestyle='--', linewidth=1)

    y = f0vector
    leny = len(y)
    lenz = len(z)

    xaxis = np.linspace(0,np.ceil(duration),leny,endpoint=True,dtype=np.float16)

    ax3.set_xlim(-0.01,np.ceil(duration))
    ax3.set_ylim(f0min,f0max)

    plt.scatter(xaxis,y,s=10,color=color)

    if lenz > 0 and not flag == 's0ftflag':

        if comparisonflag and flag in ['raptflag','pyraptflag','praatflag']:
            z = np.mean(f0max-f0min)+np.array(y - z)

        if comparisonflag or flag == 's0ftpolyflag':
            for xx,yy,pp in zip(xaxis,y,z):
                    if yy > f0clipmin and yy<f0clipmax:
                        plt.scatter(xx,pp,s=10,color='r')

    plt.legend(legend,fontsize=fontsize-3)

    if howmanyplots == 'multipleplots':
        plt.tight_layout()
        webfilename = '/Webtmp/s0ft'+flag+'.png'
        localfilename = '/var/www/Webtmp/s0ft'+flag+'.png'
        plt.savefig(localfilename)
        print '<tr align=\"center\"><td><img src='+webfilename+' width=\"100%\"></td></tr>'
        plt.close('all')

    return rn+rs, cn

#==============================================================================
# Spectrogram plot 
Example 50
Project: Image-Recognition   Author: PythonProgramming   File: imagerec.py    MIT License 4 votes vote down vote up
def whatNumIsThis(filePath):
    matchedAr = []
    loadExamps = open('numArEx.txt','r').read()
    loadExamps = loadExamps.split('\n')

    i = Image.open(filePath)
    iar = np.array(i)
    iarl = iar.tolist()

    inQuestion = str(iarl)

    for eachExample in loadExamps:
        if len(eachExample) > 3:
            splitEx = eachExample.split('::')
            currentNum = splitEx[0]
            currentAr = splitEx[1]

            eachPixEx = currentAr.split('],')

            eachPixInQ = inQuestion.split('],')

            x=0

            while x < len(eachPixEx):
                if eachPixEx[x] == eachPixInQ[x]:
                    matchedAr.append(int(currentNum))

                x += 1

    
    print matchedAr
    x = Counter(matchedAr)
    print x



    graphX = []
    graphY = []

    for eachThing in x:
        print eachThing
        graphX.append(eachThing)
        print x[eachThing]
        graphY.append(x[eachThing])


    fig = plt.figure()
    ax1 = plt.subplot2grid((4,4),(0,0), rowspan=1, colspan=4)
    ax2 = plt.subplot2grid((4,4),(1,0), rowspan=3, colspan=4)

    ax1.imshow(iar)
    ax2.bar(graphX,graphY, align='center')
    plt.ylim(400)

    xloc = plt.MaxNLocator(12)

    ax2.xaxis.set_major_locator(xloc)

    

    plt.show()