def plot_post_disp_decomposition(
        self,
        site,
        cmpt,
        loc=2,
        leg_fs=7,
        marker_for_obs='x',
    ):
        y = self.plot_post_obs_linres(site,
                                      cmpt,
                                      label='obs.',
                                      marker=marker_for_obs)
        y += self.plot_post_disp_pred_added(site, cmpt, label='pred.')
        y += self.plot_R_co(site,
                            cmpt,
                            style='-^',
                            label='Rco',
                            color='orange')
        y += self.plot_E_aslip(site, cmpt, color='green')
        y += self.plot_R_aslip(site, cmpt, color='black')

        plt.grid('on')

        plt.legend(loc=loc, prop={'size': leg_fs})
        plt.ylabel(r'meter')
        plt.gcf().autofmt_xdate()
        plt.title('Postseismic Disp. : {site} - {cmpt}'.format(
            site=get_site_true_name(site_id=site), cmpt=cmpt))
    def plot_cumu_disp_decomposition(self,
                                     site,
                                     cmpt,
                                     loc=2,
                                     leg_fs=7,
                                     if_ylim=False):
        self.plot_cumu_obs_linres(site, cmpt)
        y = self.plot_cumu_disp_pred_added(site, cmpt, label='pred.')
        y += self.plot_R_co(site,
                            cmpt,
                            style='-^',
                            label='Rco',
                            color='orange')
        y += self.plot_E_cumu_slip(site, cmpt, color='green')
        y += self.plot_R_aslip(site, cmpt, color='black')

        plt.grid('on')
        if if_ylim:
            plt.ylim(calculate_lim(y))

        plt.ylabel(r'meter')
        plt.legend(loc=loc, prop={'size': leg_fs})
        plt.gcf().autofmt_xdate()
        plt.title('Cumulative Disp.: {site} - {cmpt}'.format(
            site=get_site_true_name(site_id=site), cmpt=cmpt))
Example #3
0
def plot_cf(cf, color):
    t = cf.data.t
    y0 = cf.data.y0
    plt.plot_date(t+_adj_dates,y0,'x',label=cf.SITE+cf.CMPT,
              color='light'+color)
    plt.plot_date(cf.data._t+_adj_dates,
              cf.data._y0,'x',label=cf.SITE+cf.CMPT,
              color=color)
    t1 = min(t)
    t2 = max(t)
    ls=200
    plot_func(cf.func,linspace(t1,t2,ls))
    plt.title(cf.SITE+'-'+cf.CMPT)
    plt.gcf().autofmt_xdate()
Example #4
0
    def plot2(self,
              figNum,
              time1,
              data1,
              time2,
              data2,
              title='',
              units='',
              options=''):
        plt.figure(figNum)
        #         plt.hold(True);
        plt.grid(True)
        if title:
            self.title = title
        if not units:
            self.units = units

    #     plt.cla()
        if self.preTitle:
            fig = plt.gcf()
            fig.canvas.set_window_title("Figure %d - %s" %
                                        (figNum, self.preTitle))
        plt.title("%s" % (self.title))
        plt.plot(time1, data1, options)
        plt.plot(time2, data2, options)
        plt.ylabel('(%s)' % (self.units))
        plt.xlabel('Time (s)')
        plt.margins(0.04)
Example #5
0
def macdStretagy(companyname, begin):
    end = datetime.date.today()
    #begin=end-pd.DateOffset(365*backtestyear)
    #timestamp format and get apple stock.
    st = dt.strptime(begin, '%Y-%m-%d')
    #st=begin.strftime('%Y-%m-%d')

    ed = end.strftime('%Y-%m-%d')
    symbol = companyname + ".NS"
    datanifty = nift50Indices.objects.filter(Ticker=symbol,
                                             Date__gte=st).values_list(
                                                 'Close', 'Open', 'High',
                                                 'Low')
    #data = pdr.get_data_yahoo(company,st,ed)
    dataframe = pd.DataFrame(list(datanifty),
                             columns=['Close', 'Open', 'High', 'Low'])
    print(dataframe)
    data = dataframe.astype(float)
    #data = pdr.get_data_yahoo('RELIANCE.NS',st,ed)

    #MACD
    data['macd_talib'], data['signal'], data['diff_macd_signal'] = talib.MACD(
        np.asarray(data['Close']),
        fastperiod=12,
        slowperiod=26,
        signalperiod=9)
    graph = data.plot(y=['macd_talib', 'signal', 'diff_macd_signal'],
                      title=companyname + ' MACD')
    graph = plt.gcf()
    fig_html = mpld3.fig_to_html(graph)
    return fig_html
Example #6
0
    def subplotSingle2x(self,
                        figNum,
                        plotNum,
                        numRows,
                        numCols,
                        time,
                        data,
                        title='',
                        units='',
                        options=''):

        print("subplotSingle2x")

        plt.figure(figNum)
        if title:
            self.title = title
        if not units:
            self.units = units
        if self.preTitle:
            fig = plt.gcf()
            fig.canvas.set_window_title("%s" % (figNum, self.preTitle))
        if not figNum in self.sharex.keys():
            self.sharex[figNum] = plt.subplot(numRows, numCols, plotNum)
            plt.plot(time, data, options)

        plt.subplot(numRows, numCols, plotNum, sharex=self.sharex[figNum])
        #         plt.hold(True);
        plt.grid(True)
        plt.title("%s" % (self.title))
        plt.plot(time, data, options)
        plt.ylabel('(%s)' % (self.units))
        plt.margins(0.04)
Example #7
0
def soStretagy(companyname, begin):
    end = datetime.date.today()
    #begin=end-pd.DateOffset(365*backtestyear)
    #timestamp format and get apple stock.
    st = dt.strptime(begin, '%Y-%m-%d')
    #st=begin.strftime('%Y-%m-%d')

    ed = end.strftime('%Y-%m-%d')
    symbol = companyname + ".NS"
    datanifty = nift50Indices.objects.filter(Ticker=symbol,
                                             Date__gte=st).values_list(
                                                 'Close', 'Open', 'High',
                                                 'Low')
    #data = pdr.get_data_yahoo(company,st,ed)
    dataframe = pd.DataFrame(list(datanifty),
                             columns=['Close', 'Open', 'High', 'Low'])
    print(dataframe)
    data = dataframe.astype(float)
    #data = pdr.get_data_yahoo('RELIANCE.NS',st,ed)
    #Stochastic Oscillator
    # stock oversold if below 10 , overbought if greater than 90
    data['slowk'], data['slowd'] = talib.STOCH(np.asarray(data['High']),
                                               np.asarray(data['Low']),
                                               np.asarray(data['Close']),
                                               fastk_period=5,
                                               slowk_period=3,
                                               slowk_matype=0,
                                               slowd_period=3,
                                               slowd_matype=0)

    graph = data.plot(y=['slowk', 'slowd'],
                      title=companyname + ' Stochastic Oscillator')
    graph = plt.gcf()
    fig_html = mpld3.fig_to_html(graph)
    return fig_html
Example #8
0
def rocStretagy(companyname, begin):
    end = datetime.date.today()
    #begin=end-pd.DateOffset(365*backtestyear)
    #timestamp format and get apple stock.
    st = dt.strptime(begin, '%Y-%m-%d')
    #st=begin.strftime('%Y-%m-%d')

    ed = end.strftime('%Y-%m-%d')
    symbol = companyname + ".NS"
    datanifty = nift50Indices.objects.filter(Ticker=symbol,
                                             Date__gte=st).values_list(
                                                 'Close', 'Open', 'High',
                                                 'Low')
    #data = pdr.get_data_yahoo(company,st,ed)
    dataframe = pd.DataFrame(list(datanifty),
                             columns=['Close', 'Open', 'High', 'Low'])
    print(dataframe)
    data = dataframe.astype(float)
    #data = pdr.get_data_yahoo('RELIANCE.NS',st,ed)

    #Rate of change ROC
    data['ROC'] = talib.ROC(np.asarray(data['Close']), 20)
    graph = data.plot(y=['ROC'], title=companyname + ' ROC ')
    graph = plt.gcf()
    fig_html = mpld3.fig_to_html(graph)
    return fig_html
Example #9
0
def plot(site):
    tp = np.loadtxt('../post_offsets/%s.post' % site)

    t = dc.asmjd([ii[0] for ii in tp]) + dc.adjust_mjd_for_plot_date
    e = [ii[1] for ii in tp]
    n = [ii[2] for ii in tp]
    u = [ii[3] for ii in tp]

    plt.plot_date(t, e, 'x-', label='eastings')
    plt.plot(t, n, 'x-', label='northings')
    plt.plot(t, u, 'x-', label='upings')
    plt.gcf().autofmt_xdate()
    plt.legend(loc=0)
    plt.title(site)
    plt.savefig('%s.png' % site)
    #plt.show()
    plt.close()
Example #10
0
def plot(site):
    tp = np.loadtxt('../post_offsets/%s.post'%site)

    t = dc.asmjd([ii[0] for ii in tp]) + dc.adjust_mjd_for_plot_date
    e = [ii[1] for ii in tp]
    n = [ii[2] for ii in tp]
    u = [ii[3] for ii in tp]

    plt.plot_date(t,e,'x-', label = 'eastings')
    plt.plot(t,n,'x-', label = 'northings')
    plt.plot(t,u,'x-', label = 'upings')
    plt.gcf().autofmt_xdate()
    plt.legend(loc=0)
    plt.title(site)
    plt.savefig('%s.png'%site)
    #plt.show()
    plt.close()
def maximize_figure(fig=None):
    if fig is None:
        fig = _plt.gcf()
    mng = _plt.get_current_fig_manager()
    try:
        mng.frame.Maximize(True)
    except AttributrError:
        print("Failed to maximize figure.")
Example #12
0
def maximize_figure(fig=None):
    if fig is None:
        fig = _plt.gcf()
    
    mng = _plt.get_current_fig_manager()
    try:        
        mng.frame.Maximize(True)      
    except AttributeError:
        print "Failed to maximize figure."
Example #13
0
def dynamic_img_show(img,title_str='',fig_size=[14,8],hide_axes=True):
    '''Show image <img>. If called repeatedly within a cycle will dynamically redraw image.
    #DEMO
    import time

    for i in range(10):
        img = np.zeros([50,50])
        img[:i*5]=1
        dynamic_img_show(img,'iter=%s'%i)
        time.sleep(0.1)
    '''
    plt.clf()
    plt.title(title_str)
    plt.imshow(img)
    plt.xticks([]); plt.yticks([]);
    plt.gcf().set_size_inches(fig_size)
    display.display(plt.gcf())
    display.clear_output(wait=True)   
    def plot_vel_decomposition(self, site, cmpt, loc=0, leg_fs=7,
                       if_ylim=False
                       ):
        y = self.plot_pred_vel_added(site, cmpt, label='total')
        y += self.plot_vel_R_co(site, cmpt,
                            style='-^', label='Rco', color='orange')
        y += self.plot_vel_E_cumu_slip(site, cmpt, color='green')
        y += self.plot_vel_R_aslip(site, cmpt, color='black')
        
        plt.grid('on')
        if if_ylim:
            plt.ylim(calculate_lim(y))

        plt.ylabel(r'mm/yr')
        plt.legend(loc=loc, prop={'size':leg_fs})
        plt.gcf().autofmt_xdate()
        plt.title('Cumulative Disp.: {site} - {cmpt}'.format(
            site = get_site_true_name(site_id=site),
            cmpt = cmpt
            ))
    def plot_post_disp_decomposition(self, site, cmpt, loc=2, leg_fs=7,
                       added_label = None,
                       marker_for_obs = 'x',
                       ):
        y = self.plot_post_obs_linres(site,cmpt, label='obs.', marker=marker_for_obs)
        y += self.plot_post_disp_pred_from_result_file(site,cmpt, label='pred.')
        y += self.plot_R_co(site, cmpt,
                            style = '-^', label='Rco', color='orange')
        y += self.plot_E_aslip(site, cmpt, color='green')

        plt.grid('on')

        self.plot_post_disp_pred_added(site, cmpt, label=added_label)
        
        plt.legend(loc=loc, prop={'size':leg_fs})
        plt.ylabel(r'm')
        plt.gcf().autofmt_xdate()
        plt.title('Postseismic Disp. : {site} - {cmpt}'.format(
            site = get_site_true_name(site_id = site),
            cmpt = cmpt
            ))
    def plot_cumu_disp_decomposition(self, site, cmpt, loc=2, leg_fs=7,
                       if_ylim=False,
                       added_label = None,
                       ):        
        self.plot_cumu_obs_linres(site, cmpt)
        y = self.plot_cumu_disp_pred_from_result_file(site, cmpt, label='pred.')
        y += self.plot_R_co(site, cmpt,
                            style='-^', label='Rco', color='orange')
        y += self.plot_E_cumu_slip(site, cmpt, color='green')

        plt.grid('on')
        if if_ylim:
            plt.ylim(calculate_lim(y))

        self.plot_cumu_disp_pred_added(site, cmpt, label=added_label)
        plt.ylabel(r'm')
        plt.legend(loc=loc, prop={'size':leg_fs})
        plt.gcf().autofmt_xdate()
        plt.title('Cumulative Disp.: {site} - {cmpt}'.format(
            site = get_site_true_name(site_id=site),
            cmpt = cmpt
            ))
Example #17
0
    def plotNE(self, figNum, north, east, title='', units='', options=''):

        plt.figure(figNum)
        #     plt.cla()
        #         plt.hold(True);
        plt.grid(True)
        if title:
            self.title = title
        if not units:
            self.units = units
        if self.preTitle:
            fig = plt.gcf()
            fig.canvas.set_window_title("%s" % (self.preTitle))
        plt.title("%s" % (self.title))
        plt.plot(east, north, options)
        plt.xlabel('East (%s)' % (self.units))
        plt.ylabel('North (%s)' % (self.units))
def pca_2component_scatter(data_df,
                           predictors,
                           legend,
                           sav_fig=0,
                           savefname=r'c:\data\temp\ans.png'):
    """
        outlook of data set by decomposing data to only 2 pca components.
        do: scaling --> either maxmin or stdscaler

    """

    print 'PCA plotting'

    data_df[predictors] = StandardScaler().fit_transform(data_df[predictors])

    pca_components = ['PCA1',
                      'PCA2']  #make this exist then insert the fit transform
    pca = PCA(n_components=2)
    for n in pca_components:
        data_df[n] = ''
    data_df[pca_components] = pca.fit_transform(data_df[predictors])

    sns.lmplot('PCA1',
               'PCA2',
               data=data_df,
               fit_reg=False,
               hue=legend,
               scatter_kws={
                   "marker": "D",
                   "s": 100
               })

    fig = plt.gcf()
    if sav_fig:
        plt.savefig(savefname)
    plt.show()
Example #19
0
bulk = double_y(bulk)

## begin to plot


def axhspan_for_viscosity(ax):
    deps = [0, -51, -220, -670, -2000]
    cols = ['.95', '0.83', '0.7', '0.5']
    alpha = .8
    for dep1, dep2, col in zip(deps[0:], deps[1:], cols):
        ax.axhspan(dep2, dep1, color=col, alpha=alpha)


gs = gridspec.GridSpec(1, 3, width_ratios=[1.5, 1.7, 1.1])

fig = plt.gcf()
ax1 = plt.subplot(gs[0])
ax2 = plt.subplot(gs[1], sharey=ax1)
ax3 = plt.subplot(gs[2], sharey=ax1)

# plot ax1 - Maxwell viscosity
axhspan_for_viscosity(ax1)
ax1.tick_params(axis='x', bottom='off', top='off', labelbottom='off')

ax1.text(0.2, -40, s='crust  $H_e=?$', fontsize=12)
ax1.text(0.2, -170, s='asthenosphere \n$ \\eta = ?$', fontsize=12)
ax1.text(0.2,
         -450,
         s='uppermantle \n$ \\eta = 1 \\times 10^{20}$',
         fontsize=12)
ax1.text(0.2,
Example #20
0
from database import session, Datapoint


session.query(Datapoint).all()


def format_timestamp(timestamp):
    real_timestamp = datetime.fromtimestamp(float(timestamp.timestamp))
    now = datetime.now()
    return real_timestamp.replace(year=now.year, day=now.day, month=now.month)


datapoints = [(datapoint.user.name, datapoint.timestamp) for datapoint in session.query(Datapoint)]

grouped_data = defaultdict(int)
for datapoint in session.query(Datapoint):
    if datapoint.status == 2:
        grouped_data[datapoint.timestamp] += 1

print('Here')
x = list(map(format_timestamp, grouped_data.keys()))
plt.plot(x, list(grouped_data.values()), 'go')
formatter = DateFormatter('%H:%M')
plt.gcf().axes[0].xaxis.set_major_formatter(formatter)
plt.show()




Example #21
0
    def mkplots(self):
        # run to make plots of the resulting posteriors. Modified from marginal_plots.py
        # from pymultinest. Produces basename+marg.pdf and basename+marge.png files
        prefix = self.basename

        parameters = json.load(file(prefix + 'params.json'))
        n_params = len(parameters)

        a = pymultinest.Analyzer(n_params=n_params,
                                 outputfiles_basename=prefix)
        s = a.get_stats()

        p = pymultinest.PlotMarginal(a)

        try:
            values = a.get_equal_weighted_posterior()
        except IOError as e:
            print 'Unable to open: %s' % e
            return

        assert n_params == len(s['marginals'])
        modes = s['modes']

        dim2 = os.environ.get('D', '1' if n_params > 20 else '2') == '2'
        nbins = 100 if n_params < 3 else 20
        if dim2:
            plt.figure(figsize=(5.1 * n_params, 5 * n_params))
            for i in range(n_params):
                plt.subplot(n_params, n_params, i + 1)
                plt.xlabel(parameters[i])

                m = s['marginals'][i]
                plt.xlim(m['5sigma'])

                oldax = plt.gca()
                x, w, patches = oldax.hist(values[:, i],
                                           bins=nbins,
                                           edgecolor='grey',
                                           color='grey',
                                           histtype='stepfilled',
                                           alpha=0.2)
                oldax.set_ylim(0, x.max())

                newax = plt.gcf().add_axes(oldax.get_position(),
                                           sharex=oldax,
                                           frameon=False)
                p.plot_marginal(i, ls='-', color='blue', linewidth=3)
                newax.set_ylim(0, 1)

                ylim = newax.get_ylim()
                y = ylim[0] + 0.05 * (ylim[1] - ylim[0])
                center = m['median']
                low1, high1 = m['1sigma']
                print center, low1, high1
                newax.errorbar(x=center,
                               y=y,
                               xerr=np.transpose(
                                   [[center - low1, high1 - center]]),
                               color='blue',
                               linewidth=2,
                               marker='s')
                oldax.set_yticks([])
                #newax.set_yticks([])
                newax.set_ylabel("Probability")
                ylim = oldax.get_ylim()
                newax.set_xlim(m['5sigma'])
                oldax.set_xlim(m['5sigma'])
                #plt.close()

                for j in range(i):
                    plt.subplot(n_params, n_params, n_params * (j + 1) + i + 1)
                    p.plot_conditional(i, j, bins=20, cmap=plt.cm.gray_r)
                    for m in modes:
                        plt.errorbar(x=m['mean'][i],
                                     y=m['mean'][j],
                                     xerr=m['sigma'][i],
                                     yerr=m['sigma'][j])
                    ax = plt.gca()
                    if j == i - 1:
                        plt.xlabel(parameters[i])
                        plt.ylabel(parameters[j])
                        [l.set_rotation(45) for l in ax.get_xticklabels()]
                    else:
                        ax.set_xticklabels([])
                        ax.set_yticklabels([])

                    plt.xlim([
                        m['mean'][i] - 5 * m['sigma'][i],
                        m['mean'][i] + 5 * m['sigma'][i]
                    ])
                    plt.ylim([
                        m['mean'][j] - 5 * m['sigma'][j],
                        m['mean'][j] + 5 * m['sigma'][j]
                    ])
                    #plt.savefig('cond_%s_%s.pdf' % (params[i], params[j]), bbox_tight=True)
                    #plt.close()

            plt.tight_layout()
            plt.savefig(prefix + 'marg.pdf')
            plt.savefig(prefix + 'marg.png')
            plt.close()
        else:
            from matplotlib.backends.backend_pdf import PdfPages
            print '1dimensional only. Set the D environment variable D=2 to force'
            print '2d marginal plots.'
            pp = PdfPages(prefix + 'marg1d.pdf')

            for i in range(n_params):
                plt.figure(figsize=(5, 5))
                plt.xlabel(parameters[i])

                m = s['marginals'][i]
                plt.xlim(m['5sigma'])

                oldax = plt.gca()
                x, w, patches = oldax.hist(values[:, i],
                                           bins=20,
                                           edgecolor='grey',
                                           color='grey',
                                           histtype='stepfilled',
                                           alpha=0.2)
                oldax.set_ylim(0, x.max())

                newax = plt.gcf().add_axes(oldax.get_position(),
                                           sharex=oldax,
                                           frameon=False)
                p.plot_marginal(i, ls='-', color='blue', linewidth=3)
                newax.set_ylim(0, 1)

                ylim = newax.get_ylim()
                y = ylim[0] + 0.05 * (ylim[1] - ylim[0])
                center = m['median']
                low1, high1 = m['1sigma']
                print center, low1, high1
                newax.errorbar(x=center,
                               y=y,
                               xerr=np.transpose(
                                   [[center - low1, high1 - center]]),
                               color='blue',
                               linewidth=2,
                               marker='s')
                oldax.set_yticks([])
                newax.set_ylabel("Probability")
                ylim = oldax.get_ylim()
                newax.set_xlim(m['5sigma'])
                oldax.set_xlim(m['5sigma'])
                plt.savefig(pp, format='pdf', bbox_inches='tight')
                plt.close()
            pp.close()
Example #22
0
    def plot_plotly(self,
                    plotly_filename=None,
                    mpl_type=False,
                    xlim=None,
                    ylim=None,
                    title=None,
                    figsize=None,
                    xlabel=None,
                    ylabel=None,
                    fontsize=None,
                    show_legend=True,
                    grid=False):
        """
        Plot data using plotly library in IPython

        :param plotly_filename: name for resulting plot file on server (use unique name, else the same plot will be showen)
        :type plotly_filename: None or str
        :param bool mpl_type: use or not plotly converter from matplotlib (experimental parameter)
        :param xlim: x-axis range
        :param ylim: y-axis range
        :type xlim: None or tuple(x_min, x_max)
        :type ylim: None or tuple(y_min, y_max)
        :param title: title
        :type title: None or str
        :param figsize: figure size
        :type figsize: None or tuple(weight, height)
        :param xlabel: x-axis name
        :type xlabel: None or str
        :param ylabel: y-axis name
        :type ylabel: None or str
        :param fontsize: font size
        :type fontsize: None or int
        :param bool show_legend: show or not labels for plots
        :param bool grid: show grid or not
        """
        import plotly.plotly as py
        from plotly import graph_objs
        from IPython.kernel import connect

        plotly_filename = self.plotly_filename if plotly_filename is None else plotly_filename
        connection_file_path = connect.get_connection_file()
        connection_file = os.path.basename(connection_file_path)
        if '-' in connection_file:
            kernel_id = connection_file.split('-', 1)[1].split('.')[0]
        else:
            kernel_id = connection_file.split('.')[0]
        PLOTLY_API_USER, PLOTLY_API_KEY, PLOTLY_USER = self._plotly_config()
        save_name = '{user}_{id}:{name}'.format(user=PLOTLY_USER,
                                                id=kernel_id,
                                                name=plotly_filename)
        py.sign_in(PLOTLY_API_USER, PLOTLY_API_KEY)

        if mpl_type:
            self.plot(new_plot=True,
                      xlim=xlim,
                      ylim=ylim,
                      title=title,
                      figsize=figsize,
                      xlabel=xlabel,
                      ylabel=ylabel,
                      fontsize=fontsize,
                      grid=grid)
            mpl_fig = plt.gcf()
            update = dict(layout=dict(showlegend=show_legend),
                          data=[dict(name=leg) for leg in mpl_fig.legends])

            return py.iplot_mpl(mpl_fig,
                                width=self.figsize[0] * 60,
                                update=update,
                                height=self.figsize[1] * 60,
                                filename=save_name,
                                fileopt='overwrite')

        xlabel = self.xlabel if xlabel is None else xlabel
        ylabel = self.ylabel if ylabel is None else ylabel
        title = self.title if title is None else title
        figsize = self.figsize if figsize is None else figsize
        fontsize = self.fontsize if fontsize is None else fontsize

        layout = graph_objs.Layout(yaxis={
            'title': ylabel,
            'ticks': ''
        },
                                   xaxis={
                                       'title': xlabel,
                                       'ticks': ''
                                   },
                                   showlegend=show_legend,
                                   title=title,
                                   font=graph_objs.Font(
                                       family='Courier New, monospace',
                                       size=fontsize),
                                   width=figsize[0] * self.PLOTLY_RESIZE,
                                   height=figsize[1] * self.PLOTLY_RESIZE)

        fig = self._plot_plotly(layout)

        return py.iplot(fig,
                        width=figsize[0] * self.PLOTLY_RESIZE,
                        height=figsize[1] * self.PLOTLY_RESIZE,
                        filename=save_name)
Example #23
0
from datetime import date

import numpy as np
from pylab import plt

import viscojapan as vj

site = 'J550'
cmpt = 'e'

tp = np.loadtxt('../../tsana/pre_fit/linres/{site}.{cmpt}.lres'.\
           format(site=site, cmpt=cmpt))

days = tp[:,0]
yres = tp[:,2]

plt.plot_date(days + vj.adjust_mjd_for_plot_date, yres, 'x')
plt.grid('on')

plt.axvline(date(2011,3,11),color='r', ls='--')

plt.ylim([-1, 7])
plt.xlim((date(2010,1,1), date(2015,1,1)))

plt.gcf().autofmt_xdate()

plt.ylabel('m')
plt.title('%s - %s'%(site, cmpt))
plt.savefig('%s_%s.pdf'%(site, cmpt))
plt.show()
def multiple_subplots(attribute_list,
                      group,
                      dataset,
                      plot_type='hist',
                      row_category_split=0,
                      row_category_split_col='dummy',
                      sav_fig=0,
                      savefname=r'c:\data\temp\ans.png',
                      **kwargs):
    """ Create multiple subplots within a figure ( currently box, hist) based on the attribute list. May purpose is to ensure y-axis auto scaling for each subplot and does not share y axis.
        By default, it create n by column (default 3) number of subplot within a single figure. n is based on len(attribute_list)/column.

        Args:
            attribute_list (list): (row_category_split = 0)list of column names to plot. Each column name is put under one plot
                                   (row_category_split = 1)list of sub category to plot. Each sub cat is put under one plot
            group ('str'):          category option within a plot. Only avaliable for box plot. where the x-axis is group.
            dataset ('dataframe'):  attribute_list items, group and row_category_split_col must be present in the dataset.

        Kwargs:
            plot_type(str): hist (histogram) or box (boxplot) option.
            row_category_split: default 0. Applicable for boxplot. allow sub plot by splitting the plots based on target row (row_category_split_col)
            sav_fig (bool): default 0, if sav_fg = 1, will save figure beside showing it, will use savefname  as the save filename.

        Additional parameters:
            column_default (int): default 3. change the layout of the figure.
            
        Normally for box plot each plot is based on each column group by "group" (if row_category_split = 0)
        if row_category_split = 1 

   
    """
    if kwargs.has_key('column_default'):
        column_default = float(kwargs['column_default'])
    else:
        column_default = 3.0

    num_rows = int(math.ceil(len(attribute_list) / column_default))
    gs = gridspec.GridSpec(num_rows, int(column_default))

    row_index = 0
    temp_col = 0
    for n in attribute_list:
        ax = plt.subplot(gs[row_index, temp_col])

        if plot_type == 'hist':
            dataset[n].hist(ax=ax)  #may need to add title
            ax.set_title(n)

        if plot_type == 'box':
            if not row_category_split:
                dataset[[n, group]].boxplot(
                    by=group, sym='k.', vert=True, whis=1.5,
                    ax=ax)  #symbol is as a result of seaborn with pylab issue
            else:
                dataset[dataset[row_category_split_col] == n].boxplot(
                    by=group, sym='k.', vert=True, whis=1.5,
                    ax=ax)  #symbol is as a result of seaborn with pylab issue
                ax.set_title(n)

        temp_col = temp_col + 1
        if temp_col == 3:
            row_index = row_index + 1
            temp_col = 0

    fig = plt.gcf()
    fig.set_size_inches(18.5, 10.5)
    plt.tight_layout()
    if sav_fig:
        plt.savefig(savefname)
    plt.show()
Example #25
0
    def plot_plotly(self, plotly_filename=None, mpl_type=False, xlim=None, ylim=None, title=None, figsize=None,
                    xlabel=None, ylabel=None, fontsize=None, show_legend=True, grid=False):
        """
        Plot data using plotly library in IPython

        :param plotly_filename: name for resulting plot file on server (use unique name, else the same plot will be showen)
        :type plotly_filename: None or str
        :param bool mpl_type: use or not plotly converter from matplotlib (experimental parameter)
        :param xlim: x-axis range
        :param ylim: y-axis range
        :type xlim: None or tuple(x_min, x_max)
        :type ylim: None or tuple(y_min, y_max)
        :param title: title
        :type title: None or str
        :param figsize: figure size
        :type figsize: None or tuple(weight, height)
        :param xlabel: x-axis name
        :type xlabel: None or str
        :param ylabel: y-axis name
        :type ylabel: None or str
        :param fontsize: font size
        :type fontsize: None or int
        :param bool show_legend: show or not labels for plots
        :param bool grid: show grid or not
        """
        import plotly.plotly as py
        from plotly import graph_objs
        from IPython.kernel import connect

        plotly_filename = self.plotly_filename if plotly_filename is None else plotly_filename
        connection_file_path = connect.get_connection_file()
        connection_file = os.path.basename(connection_file_path)
        if '-' in connection_file:
            kernel_id = connection_file.split('-', 1)[1].split('.')[0]
        else:
            kernel_id = connection_file.split('.')[0]
        PLOTLY_API_USER, PLOTLY_API_KEY, PLOTLY_USER = self._plotly_config()
        save_name = '{user}_{id}:{name}'.format(user=PLOTLY_USER, id=kernel_id, name=plotly_filename)
        py.sign_in(PLOTLY_API_USER, PLOTLY_API_KEY)

        if mpl_type:
            self.plot(new_plot=True, xlim=xlim, ylim=ylim, title=title, figsize=figsize, xlabel=xlabel, ylabel=ylabel,
                      fontsize=fontsize, grid=grid)
            mpl_fig = plt.gcf()
            update = dict(
                layout=dict(
                    showlegend=show_legend
                ),
                data=[dict(name=leg) for leg in mpl_fig.legends]
            )

            return py.iplot_mpl(mpl_fig, width=self.figsize[0] * 60,
                                update=update,
                                height=self.figsize[1] * 60,
                                filename=save_name,
                                fileopt='overwrite')

        xlabel = self.xlabel if xlabel is None else xlabel
        ylabel = self.ylabel if ylabel is None else ylabel
        title = self.title if title is None else title
        figsize = self.figsize if figsize is None else figsize
        fontsize = self.fontsize if fontsize is None else fontsize

        layout = graph_objs.Layout(yaxis={'title': ylabel, 'ticks': ''}, xaxis={'title': xlabel, 'ticks': ''},
                                   showlegend=show_legend, title=title,
                                   font=graph_objs.Font(family='Courier New, monospace', size=fontsize),
                                   width=figsize[0] * self.PLOTLY_RESIZE,
                                   height=figsize[1] * self.PLOTLY_RESIZE
        )

        fig = self._plot_plotly(layout)

        return py.iplot(fig, width=figsize[0] * self.PLOTLY_RESIZE, height=figsize[1] * self.PLOTLY_RESIZE,
                        filename=save_name)
Example #26
0
    def mkplots(self):
        # run to make plots of the resulting posteriors. Modified from marginal_plots.py
        # from pymultinest. Produces basename+marg.pdf and basename+marge.png files
        prefix = self.basename
        
        parameters = json.load(file(prefix + 'params.json'))
        n_params = len(parameters)
        
        a = pymultinest.Analyzer(n_params = n_params, outputfiles_basename = prefix)
        s = a.get_stats()
        
        p = pymultinest.PlotMarginal(a)
        
        try:
            values = a.get_equal_weighted_posterior()
        except IOError as e:
            print 'Unable to open: %s' % e
            return
            
        assert n_params == len(s['marginals'])
        modes = s['modes']

        dim2 = os.environ.get('D', '1' if n_params > 20 else '2') == '2'
        nbins = 100 if n_params < 3 else 20
        if dim2:
                plt.figure(figsize=(5.1*n_params, 5*n_params))
                for i in range(n_params):
                        plt.subplot(n_params, n_params, i + 1)
                        plt.xlabel(parameters[i])

                        m = s['marginals'][i]
                        plt.xlim(m['5sigma'])

                        oldax = plt.gca()
                        x,w,patches = oldax.hist(values[:,i], bins=nbins, edgecolor='grey', color='grey', histtype='stepfilled', alpha=0.2)
                        oldax.set_ylim(0, x.max())

                        newax = plt.gcf().add_axes(oldax.get_position(), sharex=oldax, frameon=False)
                        p.plot_marginal(i, ls='-', color='blue', linewidth=3)
                        newax.set_ylim(0, 1)

                        ylim = newax.get_ylim()
                        y = ylim[0] + 0.05*(ylim[1] - ylim[0])
                        center = m['median']
                        low1, high1 = m['1sigma']
                        print center, low1, high1
                        newax.errorbar(x=center, y=y,
                                xerr=np.transpose([[center - low1, high1 - center]]), 
                                color='blue', linewidth=2, marker='s')
                        oldax.set_yticks([])
                        #newax.set_yticks([])
                        newax.set_ylabel("Probability")
                        ylim = oldax.get_ylim()
                        newax.set_xlim(m['5sigma'])
                        oldax.set_xlim(m['5sigma'])
                        #plt.close()

                        for j in range(i):
                                plt.subplot(n_params, n_params, n_params * (j + 1) + i + 1)
                                p.plot_conditional(i, j, bins=20, cmap = plt.cm.gray_r)
                                for m in modes:
                                        plt.errorbar(x=m['mean'][i], y=m['mean'][j], xerr=m['sigma'][i], yerr=m['sigma'][j])
                                ax = plt.gca()
                                if j == i-1:
                                    plt.xlabel(parameters[i])
                                    plt.ylabel(parameters[j])
                                    [l.set_rotation(45) for l in ax.get_xticklabels()]
                                else:
                                    ax.set_xticklabels([])
                                    ax.set_yticklabels([])


                                plt.xlim([m['mean'][i]-5*m['sigma'][i],m['mean'][i]+5*m['sigma'][i]])
                                plt.ylim([m['mean'][j]-5*m['sigma'][j],m['mean'][j]+5*m['sigma'][j]])
                                #plt.savefig('cond_%s_%s.pdf' % (params[i], params[j]), bbox_tight=True)
                                #plt.close()

                plt.tight_layout()
                plt.savefig(prefix + 'marg.pdf')
                plt.savefig(prefix + 'marg.png')
                plt.close()
        else:
        	from matplotlib.backends.backend_pdf import PdfPages
        	print '1dimensional only. Set the D environment variable D=2 to force'
        	print '2d marginal plots.'
        	pp = PdfPages(prefix + 'marg1d.pdf')
        	
        	for i in range(n_params):
        		plt.figure(figsize=(5, 5))
        		plt.xlabel(parameters[i])
        		
        		m = s['marginals'][i]
        		plt.xlim(m['5sigma'])
        	
        		oldax = plt.gca()
        		x,w,patches = oldax.hist(values[:,i], bins=20, edgecolor='grey', color='grey', histtype='stepfilled', alpha=0.2)
        		oldax.set_ylim(0, x.max())
        	
        		newax = plt.gcf().add_axes(oldax.get_position(), sharex=oldax, frameon=False)
        		p.plot_marginal(i, ls='-', color='blue', linewidth=3)
        		newax.set_ylim(0, 1)
        	
        		ylim = newax.get_ylim()
        		y = ylim[0] + 0.05*(ylim[1] - ylim[0])
        		center = m['median']
        		low1, high1 = m['1sigma']
        		print center, low1, high1
        		newax.errorbar(x=center, y=y,
        			xerr=np.transpose([[center - low1, high1 - center]]), 
        			color='blue', linewidth=2, marker='s')
        		oldax.set_yticks([])
        		newax.set_ylabel("Probability")
        		ylim = oldax.get_ylim()
        		newax.set_xlim(m['5sigma'])
        		oldax.set_xlim(m['5sigma'])
        		plt.savefig(pp, format='pdf', bbox_inches='tight')
        		plt.close()
        	pp.close()
Example #27
0
def main(filename, ylim = (0,15), xlim = (-40,20)):
    # construct experiment from header
    import spk2_mp
    conds, stims, mps, cells = spk2_mp.main(filename)
    
    conds = on_off_evnts(conds['name'], conds['times'])
    stims = on_off_evnts(stims['name'], stims['times'])

    prtrct = on_off_evnts('prtrct', mps['prtrct'])
    retrct = on_off_evnts('retrct', mps['retrct'])
    mps = motor_programs(prtrct, retrct)

    expt = experiment()
    expt.add_motor_programs(mps)
    expt.add_cbi2_stims(stims)
    expt.add_condition(conds)
    
    for cell_name in cells.keys():
        tmpcell = ap_cell(cell_name)
        tmpcell.add_spk_times(cells[cell_name])
        expt.add_cell(tmpcell)

    # now getting into plotting and the like, have to split this off somehow.
    # figure out max num prgs in any one condition
    max_prgs = max([cnd._num_prgs for cnd in expt])
    import matplotlib.gridspec as gridspec
    nrow = max_prgs
    ncol = 3
    plt_counter = 0
    gs = gridspec.GridSpec(nrow,ncol)

    # plot b48
    # save the bottom row for the averages (row-1)
    from pylab import plt
    for col_num, cond in enumerate(expt):
        if col_num == 0: left_most = True
        else: left_most = False
        for row_num, prog in enumerate(cond):
            if row_num == (cond._num_prgs - 1): bottom_most = True
            else: bottom_most = False
            ax = plt.subplot(gs[row_num,col_num])
            quick_plot(expt, prog, 'b48', ax,
                       left_most = left_most, bottom_most = bottom_most,
                       ylim = ylim, xlim = xlim)
            if row_num == nrow - 1:
                break
    expt.b48_fig = plt.gcf()
    expt.b48_fig.set_size_inches((7.5,10))
    
    # plot both b48 and b8
    # save the bottom row for the averages (row-1)
    for col_num, cond in enumerate(expt):
        if col_num == 0: left_most = True
        else: left_most = False
        for row_num, prog in enumerate(cond):
            if row_num == (cond._num_prgs - 1): bottom_most = True
            else: bottom_most = False
            ax = plt.subplot(gs[row_num,col_num])
            quick_plot(expt, prog, 'b48', ax,
                       left_most = left_most, bottom_most = bottom_most,
                       ylim = ylim, xlim = xlim)
            quick_plot(expt, prog, 'b8', ax,
                       left_most = left_most, bottom_most = bottom_most,
                       ylim = ylim, xlim = xlim)
            # if row_num == nrow:
            #     break
    expt.b8_b48_fig = plt.gcf()
    expt.b8_b48_fig.set_size_inches((7.5,10))
    return (expt)
Example #28
0
bulk = double_y(bulk)

## begin to plot

def axhspan_for_viscosity(ax):
    deps = [0,-51,-220,-670,-2000]
    cols = ['.95', '0.83', '0.7', '0.5']
    alpha = .8
    for dep1, dep2, col in zip(deps[0:], deps[1:], cols):
        ax.axhspan(dep2, dep1, color=col, alpha=alpha)

gs = gridspec.GridSpec(1, 3,
                       width_ratios=[1.5,1.7,1.1]
                       )

fig = plt.gcf()
ax1 = plt.subplot(gs[0])
ax2 = plt.subplot(gs[1], sharey=ax1)
ax3 = plt.subplot(gs[2], sharey=ax1)


# plot ax1 - Maxwell viscosity
axhspan_for_viscosity(ax1)
ax1.tick_params(axis='x', bottom='off', top='off', labelbottom='off')

ax1.text(0.2, -40,
         s='crust  $H_e=?$',
         fontsize=12)
ax1.text(0.2, -170,
         s='asthenosphere \n$ \\eta = ?$',
         fontsize=12)