Example #1
0
def make_colorbar(fig,orientation='horizontal',label=''):

#    plt.subplots_adjust(left=0.2, right=0.8, top=0.8, bottom=0.2)
    if orientation == 'horizontal':
        cbar_ax = fig['fig_handle'].add_axes([0.2, 0,0.6,1])
        axins = inset_axes(cbar_ax,
               width="100%", # width = 10% of parent_bbox width
               height="5%", # height : 50%
               loc=10,
               bbox_to_anchor=(0, -0.01, 1 , 0.15),
               bbox_transform=cbar_ax.transAxes,
               borderpad=0,
               )
    else:
        cbar_ax = fig['fig_handle'].add_axes([0, 0.2,1,0.6])
        axins = inset_axes(cbar_ax,
               width="5%", # width = 10% of parent_bbox width
               height="100%", # height : 50%
               loc=6,
               bbox_to_anchor=(1.01, 0, 0.15, 1),
               bbox_transform=cbar_ax.transAxes,
               borderpad=0,
               )
    cbar_ax.get_xaxis().tick_bottom()
    cbar_ax.axes.get_yaxis().set_visible(False)
    cbar_ax.axes.get_xaxis().set_visible(False)
    cbar_ax.set_frame_on(False)       
    
    cbar=plt.colorbar(cax=axins, orientation=orientation,label=label)

    levels = fig['cont_handle'].levels
    cbar.set_ticks(levels)
    cbar.set_ticklabels(format_ticks(levels,decimals=2))
    return cbar
def chickling_pd_zoom(shotno, date=time.strftime("%Y%m%d")):
	
	fname, data = file_finder(shotno,date)
	
	data_1550 = data[0]['phasediff_co2'][100:]
	plot_time = np.linspace(0,1,data_1550.size)

	
	fig, ax = plt.subplots()
	ax.plot(plot_time, data_1550)
	ax.set_ybound(max(data_1550)+0.6, min(data_1550)-0.01)
	
	plt.title("Phase Difference for shot " + str(shotno) + " Date " +  str(date))
	plt.xlabel("Time, s")
	plt.ylabel("Phase Difference, Radians") 	
	
	x_zoom_bot = int(data_1550.size*(10/100))
	x_zoom_top = int(data_1550.size*(15/100))
	

	x1, x2, y1, y2 = 0.1, 0.15, max(data_1550[x_zoom_bot:x_zoom_top])+0.01, min(data_1550[x_zoom_bot:x_zoom_top])-0.01
	
	axins = inset_axes(ax, 4.3,1, loc=9)
	axins.plot(plot_time[x_zoom_bot:x_zoom_top], data_1550[x_zoom_bot:x_zoom_top])

	axins.set_xlim(x1, x2)
	if y1 < y2:
		axins.set_ylim(y1, y2)
	else:
		axins.set_ylim(y2, y1)

	mark_inset(ax, axins, loc1=2, loc2=4, fc="none", ec="0.5",lw=2)
	
	plt.show()
Example #3
0
def pl_inset_title_box(ax,title,bwidth="20%",location=1):
    """
    Function that puts title of subplot in a box
    
    :ax:    Name of matplotlib axis to add inset title text box too
    :title: 'string to put inside text box'
    :returns: @todo
    """
    import matplotlib.pyplot as plt
    #for inset axes
    #hacked from:
    #http://matplotlib.org/examples/axes_grid/inset_locator_demo.html
    from mpl_toolkits.axes_grid1.inset_locator import inset_axes, zoomed_inset_axes
    from mpl_toolkits.axes_grid1.anchored_artists import AnchoredSizeBar

    axins = inset_axes(ax,
                       width=bwidth, # width = 30% of parent_bbox
                       height=.30, # height : 1 inch
                       loc=location)

    plt.setp(axins.get_xticklabels(), visible=False)
    plt.setp(axins.get_yticklabels(), visible=False)
    axins.set_xticks([])
    axins.set_yticks([])

    axins.text(0.5,0.3,title,
            horizontalalignment='center',
            transform=axins.transAxes,size=10)
Example #4
0
    def plot_some_profile(self, data_attr, integration,
                          spatial=None, ax=None, scale=False,
                          log=False, spa_average=False, title=None,
                          **kwargs):
        plot_hist = kwargs.pop('plot_hist', False)
        savename = kwargs.pop('savename', False)
        spec = self.get_integration(data_attr, integration)
        if 'dark' in data_attr:
            nints = self.n_darks
        else:
            nints = self.n_integrations
        if scale:
            spec = spec / self.scaling_factor
        if spatial is None:
            # if no spatial bin given, take the middle one
            spatial = self.spatial_size // 2

        if title is None:
            if not spa_average:
                title = ("Profile of {} at spatial: {}, integration {} of {}"
                         .format(data_attr, spatial, integration, nints))
            else:
                title = ("Profile of {}, spatial mean. Integration {} of {}"
                         .format(data_attr, integration, nints))
        if ax is None:
            fig, ax = plt.subplots()
            fig.suptitle(self.plottitle, fontsize=12)
        if log:
            func = ax.semilogy
        else:
            func = ax.plot

        if spa_average:
            data = spec.mean(axis=0)
        else:
            data = spec[spatial]

        func(self.wavelengths[spatial], data, **kwargs)

        ax.set_xlim((self.wavelengths[spatial][0],
                     self.wavelengths[spatial][-1]))
        ax.set_title(title, fontsize=11)
        ax.set_xlabel("Wavelength [nm]")
        if log:
            ax.set_ylabel("log(DN/s)")
        else:
            ax.set_ylabel('DN/s')

        if plot_hist:
            in_axes = inset_axes(ax, width="20%", height="20%",
                                 loc=2)
            in_axes.hist(spec.ravel(), bins=20, normed=True, log=True)
            plt.setp(in_axes.get_xticklabels(), visible=False)
            plt.setp(in_axes.get_yticklabels(), visible=False)
            in_axes.grid('off')

        if savename:
            ax.get_figure().savefig(savename, dpi=100)

        return ax
Example #5
0
    def plot_vp_vs_profile(
         self, nsamp_per_layer=10, depth=False, crust_zoom_depth_km=None,
         vlim_crust=(2.5, 8.), title=None, show=True,
         inset_axes_kwargs={'width': '30%', 'height': '30%', 'loc': 3}):

        figure, ax = plt.subplots()
        colormap = {'VP': 'k', 'VS': 'r'}

        if crust_zoom_depth_km:
            from mpl_toolkits.axes_grid1.inset_locator import inset_axes
            axins = inset_axes(ax, **inset_axes_kwargs)
            axins.yaxis.tick_right()
            axins.xaxis.tick_top()

        for param in ['VP', 'VS']:
            p = np.zeros((self.nregions, nsamp_per_layer))
            x = np.zeros((self.nregions, nsamp_per_layer))
            for iregion in range(self.nregions):
                x[iregion, :] = np.linspace(
                    self.discontinuities[iregion],
                    self.discontinuities[iregion+1], nsamp_per_layer)
                centroid = np.ones(nsamp_per_layer) * \
                    np.mean(self.discontinuities[iregion:iregion+2])
                p[iregion, :] = self.get_elastic_parameter(
                    param, x[iregion, :], centroid)

            if depth:
                xx = (1 - x.flatten()) * self.scale / 1e3
            else:
                xx = x.flatten() * self.scale / 1e3

            ax.plot(p.flatten() / 1e3, xx, label='%s' % (param,),
                    color=colormap[param])

            if crust_zoom_depth_km:
                axins.plot(p.flatten() / 1e3, xx, color=colormap[param])

            ax.legend(loc='best')

        ax.set_xlabel('velocity / [km / s]')
        ax.set_title(title if title is not None else self.name)

        if crust_zoom_depth_km:
            axins.set_xlim(*vlim_crust)
            axins.set_ylim(0, crust_zoom_depth_km)
            if depth:
                axins.invert_yaxis()

        if depth:
            ax.set_ylim(0., self.scale / 1e3)
            ax.invert_yaxis()
            ax.set_ylabel('Depth / km')
        else:
            ax.set_ylim(0., self.scale / 1e3 * 1.01)
            ax.set_ylabel('Radius / km')

        if show:  # pragma: no cover
            plt.show()
        else:
            return figure
def setup_axes(fig, header):

    gh = pywcsgrid2.GridHelper(wcs=header)
    gh.locator_params(nbins=3)

    g = axes_grid.ImageGrid(
        fig,
        111,
        nrows_ncols=(5, 4),
        ngrids=None,
        direction="row",
        axes_pad=0.02,
        add_all=True,
        share_all=True,
        aspect=True,
        label_mode="L",
        cbar_mode=None,
        axes_class=(pywcsgrid2.Axes, dict(grid_helper=gh)),
    )

    # make colorbar
    ax = g[-1]
    cax = inset_axes(
        ax,
        width="8%",  # width = 10% of parent_bbox width
        height="100%",  # height : 50%
        loc=3,
        bbox_to_anchor=(1.01, 0, 1, 1),
        bbox_transform=ax.transAxes,
        borderpad=0.0,
    )

    return g, cax
Example #7
0
    def lax(self):
        """
        Returns the legend axes, creating it only on demand by creating a 2"
        by 2" inset axes that has no grid, ticks, spines or face frame (e.g
        is mostly invisible). The legend can then be drawn on this axes.
        """
        if inset_locator is None:
            raise YellowbrickValueError((
                "intercluster distance map legend requires matplotlib 2.0.2 or greater "
                "please upgrade matplotlib or set legend=False on the visualizer"
            ))

        lax = inset_locator.inset_axes(
            self.ax, width=self.legend_size, height=self.legend_size, loc=self.legend_loc
        )

        lax.set_frame_on(False)
        lax.set_facecolor("none")
        lax.grid(False)
        lax.set_xlim(-1.4,1.4)
        lax.set_ylim(-1.4,1.4)
        lax.set_xticks([])
        lax.set_yticks([])

        for name in lax.spines:
            lax.spines[name].set_visible(False)

        return lax
Example #8
0
    def initialize_subplots(self, overview=False):
        ## p = AlignmentPlot(self.figure, 212, aln=self.aln)
        p = AlignmentPlot(self.figure, 111, aln=self.aln, app=self)
        self.detail = self.figure.add_subplot(p)
        self.detail.plot_aln()
        if overview:
            self.overview = inset_axes(
                self.detail, width="30%", height="20%", loc=1
                )
            self.overview.xaxis.set_major_locator(NullLocator())
            self.overview.yaxis.set_major_locator(NullLocator())
            self.overview.imshow(
                self.detail.array, interpolation='nearest', aspect='auto',
                origin='lower'
                )
            rect = UpdatingRect(
                [0,0], 0, 0, facecolor='black', edgecolor='cyan', alpha=0.5
                )
            self.overview.zoomrect = rect
            rect.target = self.detail
            self.detail.callbacks.connect('xlim_changed', rect)
            self.detail.callbacks.connect('ylim_changed', rect)
            self.overview.add_patch(rect)
            rect(self.overview)

        else:
            self.overview = None
Example #9
0
def insertStruct(ax,**args):
  import matplotlib.pyplot as plt
  colors = ['r','g','b']
  #if not os.path.exists('struct.png'):
  generateStructPNG(**args)
  image = plt.imread('struct.png') 
  
  from mpl_toolkits.axes_grid1.inset_locator import inset_axes
  axin = inset_axes(ax,
                     width=args['width'],  # width = 30% of parent_bbox
                     height=args['height'],  # height : 1 inch
                     loc=args['loc'])
  im = axin.imshow(image)
  axin.axis('off')  
  #axins.axis('equal')  
  #axins.axis('tight')
  #axins.set_xticks([])
  #axins.set_yticks([])
  
  axin.annotate(s='',xy=(0.4,0),xytext=(0,0),xycoords='axes fraction',
                arrowprops=dict(width=2.0,color=colors[0])) 
                
  axin.text(0.45,-0.02,'x',fontsize='xx-large',transform=axin.transAxes)
  axin.text(0,0.45,'y',fontsize='xx-large',transform=axin.transAxes)
  axin.text(0.22,0.22,'z',fontsize='xx-large',transform=axin.transAxes)
   
  axin.annotate(s='',xy=(0,0.4),xytext=(0,0),xycoords='axes fraction',
                arrowprops=dict(width=2.0,color=colors[1]))  
  axin.annotate(s='',xy=(0.2,0.2),xytext=(0,0),xycoords='axes fraction',
          arrowprops=dict(width=2.0,color=colors[2])) 
  return axin, im  
Example #10
0
def QQplot(obs, Q, pos, color=None, ax=None, axins=True):
        if not color:
            color='blue'

        if ax is None:
            ax = plt.gca()

        mean = np.mean(obs, axis=0)
        # obs = np.random.multivariate_normal(mean, S, 3000)

        md2 = np.diag(np.dot(np.dot(obs - mean, Q), (obs -mean).T))
        sorted_md2 = np.sort(md2)
        v = (np.arange(1, obs.shape[0] + 1) - 0.375) / (obs.shape[0] + 0.25)
        quantiles = scipy.stats.chi2.ppf(v, df=obs.shape[1])

        # axins = inset_axes(ax, width="60%", height=1., loc=2)
        if axins:
            axins = inset_axes(ax, width="60%", height=1., loc=2)
            axins.axis(pos)

            axins.get_xaxis().tick_bottom()
            axins.get_yaxis().tick_left()
            # Remove the tick marks; they are unnecessary with the tick lines we just plotted.
            axins.tick_params(axis="both", which="both", bottom="off", top="off", labelbottom="off", left="off", right="off", labelleft="off")
            mark_inset(ax, axins, loc1=2, loc2=4, fc="none", ec="0.5")
            axins.xaxis.set_major_locator(MaxNLocator(nbins=1, prune='lower'))
            axins.scatter(quantiles, sorted_md2, color=colorscheme[color], alpha=0.3)
            axins.plot(quantiles, quantiles, color=colorscheme['green'], lw=2.5)


        ax.scatter(quantiles, sorted_md2, color=colorscheme[color], alpha=0.3)
        ax.plot(quantiles, quantiles, color=colorscheme['green'], lw=2.5)
        _clean_axes(ax)
Example #11
0
def plot_hist(ax, spec):
    in_axes = inset_axes(ax, width="20%", height="20%",
                         loc=2)
    in_axes.hist(spec.ravel(), bins=20, normed=True)
    plt.setp(in_axes.get_xticklabels(), visible=False)
    plt.setp(in_axes.get_yticklabels(), visible=False)
    in_axes.grid('off')
Example #12
0
def setup_axes(fig, header):
    
    gh = pywcsgrid2.GridHelper(wcs=header)
    gh.locator_params(nbins=3)

    g = axes_grid.ImageGrid(fig, 111, 
            nrows_ncols=(2,3), 
            ngrids=None, direction='row', 
            axes_pad=0.02, 
            add_all=True, 
            share_all=True, 
            aspect=True, 
            label_mode='L', 
            cbar_mode=None, 
            axes_class=(pywcsgrid2.Axes, dict(grid_helper=gh)))

    #make colorbar
    ax = g[-1]
    cax = inset_axes(ax, 
            width="8%", 
            height="200%", 
            loc=3,
            bbox_to_anchor=(1.02,0,1,1),
            bbox_transform=ax.transAxes,
            borderpad=0.
            )


    return g, cax
def setup_axes02(fig, rect, zoom=0.35, loc=4, axes_class=None, axes_kwargs=None):
    """
    ax2 is an inset axes, but shares the x- and y-axis with ax1.
    """

    from mpl_toolkits.axes_grid1.axes_grid import ImageGrid, CbarAxes
    import mpl_toolkits.axes_grid1.inset_locator as inset_locator

    grid = ImageGrid(fig, rect,
                     nrows_ncols=(1,1),
                     share_all=True, aspect=True,
                     label_mode='L', cbar_mode="each",
                     cbar_location='top', cbar_pad=None, cbar_size='5%',
                     axes_class=(axes_class, axes_kwargs))

    ax1 = grid[0]

    kwargs = dict(zoom=zoom, loc=loc)
    ax2 = inset_locator.zoomed_inset_axes(ax1,
                                          axes_class=axes_class,
                                          axes_kwargs=axes_kwargs,
                                          **kwargs
                                          )


    cax = inset_locator.inset_axes(ax2, "100%", 0.05, loc=3,
                                   borderpad=0.,
                                   bbox_to_anchor=(0, 0, 1, 0),
                                   bbox_transform=ax2.transAxes,
                                   axes_class=CbarAxes,
                                   axes_kwargs=dict(orientation="top"),
                                   )

    ax2.cax = cax
    return grid[0], ax2
Example #14
0
def compare_matrices(matrix1, matrix2, logplot=False):
    """Make a plot comparing two matrices"""
    fig = plt.figure(1, [6, 3])

    # first subplot
    subplot1 = fig.add_subplot(121)
    from mpl_toolkits.axes_grid1.inset_locator import inset_axes

    axins1 = inset_axes(subplot1,
                        width="50%",
                        height="5%",
                        loc=1)

    if (logplot == True):
        image1 = subplot1.imshow(np.log10(matrix1))
    else:
        image1 = subplot1.imshow(matrix1)

    plt.colorbar(image1, cax=axins1, orientation="horizontal",
                 ticks=[1, 2, 3])
    axins1.xaxis.set_ticks_position("bottom")

    # second subplot
    subplot2 = fig.add_subplot(122)

    axins = inset_axes(subplot2,
                       width="5%",
                       height="50%",
                       loc=3,
                       bbox_to_anchor=(1.05, 0., 1, 1),
                       bbox_transform=subplot2.transAxes,
                       borderpad=0,
                       )

    # Controlling the placement of the inset axes is basically same as that
    # of the legend.  you may want to play with the borderpad value and
    # the bbox_to_anchor coordinate.

    if (logplot == True):
        image2 = subplot2.imshow(np.log10(matrix2))
    else:
        image2 = subplot2.imshow(matrix2)
    plt.colorbar(image2, cax=axins, ticks=[1, 2, 3])

    plt.draw()
    plt.show()
Example #15
0
def plotBinned(cls_in,dcls_in,l_out,bins,output_prefix,title=None,theory=None,dtheory=None,delta=None,cosmic=None):
	fig=plt.figure(1)
	plt.clf()
        ax=fig.add_subplot(111)
        good_l=np.logical_and( l_out > 25 , l_out <= 250)

	if not (theory is None) :
		ax.plot(l_out,theory,'r-')
	if not (cosmic is None) :
		ax.fill_between(l_out,(theory-cosmic),(theory+cosmic),alpha=.5,facecolor='red')
		#plt.fill_between(l_out,(theory-dtheory),(theory+dtheory),alpha=.5,facecolor='red')
	if not (dtheory is None) :
		ax.errorbar(l_out,theory,yerr=dtheory,color='red')
	ax.errorbar(l_out,cls_in,yerr=dcls_in,color='black',fmt='k.',linestyle='None')
	if not (delta is None) :
		ax.fill_between(l_out,cls_in-delta,cls_in+delta,color='gray',alpha=0.5)
	#plt.xlim([0,np.max(l_out+bins)])
	#plt.ylim([np.min(b_cl['llcl']-b_dcl['llcl']),np.max(b_cl['llcl']+b_dcl['llcl'])])
	ax.set_xlabel('$\ell$')
	ax.set_ylabel('$\\frac{\ell(\ell+1)}{2\pi}C_{\ell}\ \\frac{\mu K^{2}}{m^{4}}$')
        #ax.set_xlim([0,np.max(l_out+bins)])
#        ax.autoscale(axis='y',tight=True)

	if title:
		ax.set_title(title)
	else:
		ax.set_title('Binned Cls {:02d}'.format(bins))

        axins = inset_axes(ax,width="50%",height="30%",loc=9)

	if not (theory is None) :
		axins.plot(l_out[good_l],theory[good_l],'r-')
	if not (cosmic is None) :
		axins.fill_between(l_out[good_l],(theory-cosmic)[good_l],(theory+cosmic)[good_l],alpha=.5,facecolor='red')
		#plt.fill_between(l_out,(theory-dtheory),(theory+dtheory),alpha=.5,facecolor='red')
	if not (dtheory is None) :
		axins.errorbar(l_out[good_l],theory[good_l],yerr=dtheory[good_l],color='red')
	axins.errorbar(l_out[good_l],cls_in[good_l],yerr=dcls_in[good_l],color='black',fmt='k.',linestyle='None')
	if not (delta is None) :
		axins.fill_between(l_out[good_l],(cls_in-delta)[good_l],(cls_in+delta)[good_l],color='gray',alpha=0.5)
        axins.set_xlim(25,255)
        axins.set_yscale('log')
        #axins.set_ylim(ymax=1e5)
        #axins.set_ylim(-1e5,1e5)

        mark_inset(ax,axins,loc1=2,loc2=4,fc='none',ec='0.1')
        #axins.set_xlim([25,250])
        axins.autoscale('y',tight=True)


        plt.draw()
        #plt.show(block=True)
	fig.savefig(output_prefix+'_linear_{:02d}.eps'.format(bins),format='eps')
	fig.savefig(output_prefix+'_linear_{:02d}.png'.format(bins),format='png')
        ax.set_yscale('log')
	fig.savefig(output_prefix+'_log_{:02d}.eps'.format(bins),format='eps')
	fig.savefig(output_prefix+'_log_{:02d}.png'.format(bins),format='png')
Example #16
0
def reliability_diagram(rel_objs, obj_labels, colors, markers, filename, figsize=(8, 8), xlabel="Forecast Probability",
                        ylabel="Observed Relative Frequency", ticks=np.arange(0, 1.05, 0.05), dpi=300, inset_size=1.5,
                        title="Reliability Diagram", legend_params=None, bootstrap_sets=None, ci=(2.5, 97.5)):
    """
    Plot reliability curves against a 1:1 diagonal to determine if probability forecasts are consistent with their
    observed relative frequency.

    Args:
        rel_objs (list): List of DistributedReliability objects.
        obj_labels (list): List of labels describing the forecast model associated with each curve.
        colors (list): List of colors for each line
        markers (list): List of line markers
        filename (str): Where to save the figure.
        figsize (tuple): (Width, height) of the figure in inches.
        xlabel (str): X-axis label
        ylabel (str): Y-axis label
        ticks (array): Tick value labels for the x and y axes.
        dpi (int): resolution of the saved figure in dots per inch.
        inset_size (float): Size of inset
        title (str): Title of figure
        legend_params (dict): Keyword arguments for the plot legend.
        bootstrap_sets (list): A list of arrays of bootstrapped DistributedROC objects. If not None,
            confidence regions will be plotted.
        ci (tuple): tuple of bootstrap confidence interval percentiles
    """
    if legend_params is None:
        legend_params = dict(loc=4, fontsize=10, framealpha=1, frameon=True)
    fig, ax = plt.subplots(figsize=figsize)
    plt.plot(ticks, ticks, "k--")
    inset_hist = inset_axes(ax, width=inset_size, height=inset_size, loc=2)
    if bootstrap_sets is not None:
        for b, b_set in enumerate(bootstrap_sets):
            brel_curves = np.dstack([b_rel.reliability_curve().values for b_rel in b_set])
            bin_range = np.percentile(brel_curves[:,0], ci, axis=1)
            rel_range = np.percentile(brel_curves[:, 3], ci, axis=1)
            bin_poly = np.concatenate((bin_range[1], bin_range[0, ::-1]))
            rel_poly = np.concatenate((rel_range[1], rel_range[0, ::-1]))
            bin_poly[np.isnan(bin_poly)] = 0
            rel_poly[np.isnan(rel_poly)] = 0
            plt.fill(bin_poly, rel_poly, alpha=0.5, color=colors[b])
    for r, rel_obj in enumerate(rel_objs):
        rel_curve = rel_obj.reliability_curve()
        ax.plot(rel_curve["Bin_Start"], rel_curve["Positive_Relative_Freq"], color=colors[r], marker=markers[r],
                 label=obj_labels[r])
        inset_hist.semilogy(rel_curve["Bin_Start"], rel_curve["Total_Relative_Freq"], color=colors[r],
                            marker=markers[r])
        inset_hist.set_xlabel("Forecast Probability")
        inset_hist.set_ylabel("Forecast Relative Frequency")
    ax.set_xlabel(xlabel)
    ax.set_ylabel(ylabel)
    ax.set_xticks(ticks)
    ax.set_yticks(ticks)
    ax.legend(**legend_params)
    ax.set_title(title)
    plt.savefig(filename, dpi=dpi, bbox_inches="tight")
    plt.close()
Example #17
0
def plot_sounding(date, station):
    p, T, Td, u, v, windspeed = get_sounding_data(date, station)

    lcl_pressure, lcl_temperature = mpcalc.lcl(p[0], T[0], Td[0])
    lfc_pressure, lfc_temperature = mpcalc.lfc(p, T, Td)
    parcel_path = mpcalc.parcel_profile(p, T[0], Td[0]).to('degC')

    # Create a new figure. The dimensions here give a good aspect ratio
    fig = plt.figure(figsize=(8, 8))
    skew = SkewT(fig)

    # Plot the data
    temperature_line, = skew.plot(p, T, color='tab:red')
    dewpoint_line, = skew.plot(p, Td, color='blue')
    cursor = mplcursors.cursor([temperature_line, dewpoint_line])

    # Plot thermodynamic parameters and parcel path
    skew.plot(p, parcel_path, color='black')

    if lcl_pressure:
        skew.ax.axhline(lcl_pressure, color='black')

    if lfc_pressure:
        skew.ax.axhline(lfc_pressure, color='0.7')

    # Add the relevant special lines
    skew.ax.axvline(0, color='c', linestyle='--', linewidth=2)
    skew.plot_dry_adiabats()
    skew.plot_moist_adiabats()
    skew.plot_mixing_lines()

    # Shade areas representing CAPE and CIN
    skew.shade_cin(p, T, parcel_path)
    skew.shade_cape(p, T, parcel_path)

    # Add wind barbs
    skew.plot_barbs(p, u, v)

    # Add an axes to the plot
    ax_hod = inset_axes(skew.ax, '30%', '30%', loc=1, borderpad=3)

    # Plot the hodograph
    h = Hodograph(ax_hod, component_range=100.)

    # Grid the hodograph
    h.add_grid(increment=20)

    # Plot the data on the hodograph
    mask = (p >= 100 * units.mbar)
    h.plot_colormapped(u[mask], v[mask], windspeed[mask])  # Plot a line colored by wind speed

    # Set some sensible axis limits
    skew.ax.set_ylim(1000, 100)
    skew.ax.set_xlim(-40, 60)

    return fig, skew
Example #18
0
def plot(subplot, data, title='', *args, **kwargs):
     mgr = plt.get_current_fig_manager()
     a,b = 0.75, 1.0
     chessboard = np.array(([a,b]*16 + [b,a]*16)*16)
     chessboard.shape = 32,32
     if isinstance(data, Group):
         group = data #.base
         data = data[data.keys[0]]
     else:
         group = data
         data = data
     plt.imshow(chessboard, cmap=plt.cm.gray, interpolation='nearest',
                extent=[0,group.shape[1],0,group.shape[0]],
                vmin=0, vmax=1)
     plt.hold(True)
     if hasattr(group, 'mask'):
         D = np.where(group.mask,data,np.NaN)
     else:
         D = data
     axis = plt.imshow(D, interpolation='nearest',
                       #cmap=plt.cm.bone,
                       #cmap= plt.cm.PuOr_r,
                       #vmin=-1, vmax=1,
                       origin='lower',
                       extent=[0,group.shape[1],0,group.shape[0]],
                       *args, **kwargs)

     subplot.format_coord = partial(format_coord, axis)
     subplot.group = group
     plt.xticks([]), plt.yticks([])
     x,y,w,h = axis.get_axes().bbox.bounds
     dw = 0*float(group.shape[1]-1)/w
     dh = 0*float(group.shape[0]-1)/h
     plt.axis([-dw,group.shape[1]+dw,-dh,group.shape[0]+dh])

     if title:
         t = plt.title(title, position=(0,1.01),
                       verticalalignment = 'baseline',
                       horizontalalignment = 'left')

     axins = inset_axes(subplot, width="35%", height="2.5%", loc=2,
                        bbox_to_anchor=(0.65, 0.05, 1, 1),
                        bbox_transform=subplot.transAxes, borderpad = 0)
     cb = plt.colorbar(axis, cax=axins, orientation="horizontal", format='%.2f', ticks=[])
     vmin,vmax = cb.get_clim()
     cb.set_ticks([vmin,vmax])
     cb.original_cmap = cb.get_cmap()
     cb.original_clim = vmin,vmax
     axins.xaxis.set_ticks_position('top')
     for label in cb.ax.get_xticklabels():
         label.set_fontsize('x-small')
     if not hasattr(mgr, 'subplots'):
         mgr.subplots = []
     mgr.subplots.append((axis,group,data,cb,subplot))
Example #19
0
def graph(data_, j_size, title=None):
    fig, ax = plt.subplots()
    data = pd.read_csv(data_, index_col = 0)
    jitter_ = jitter(-j_size, j_size, len(list(data.iterrows())[0][1]))
    max_1 = 0
    max_2 = 0
    for i, d in enumerate(data.iterrows()):
        if max(list(d[1])) > max_1 and i > 2:
            max_1 = max(list(d[1]))
        elif max(list(d[1])) > max_2 and i < 3:
            max_2 = max(list(d[1]))
        plt.scatter(x = np.array([i]*len(jitter_)+jitter_), y = list(d[1]))
    plt.xlim(-0.1, 5.1) # apply the x-limits
    c1 = 1
    while max_1/(c1*10) > 1:
        c1 *= 10
    c2 = 1
    while max_2/(c2*10) > 1:
        c2 *= 10
    cb = max(c1,c2)
    cs = min(c1,c2)
    max1 = max(max_1, max_2)
    max2 = min(max_1, max_2)
    plt.ylim(-cb, (max1/cb+2)*cb)
    from mpl_toolkits.axes_grid1.inset_locator import inset_axes
    if c2 > c1:
        axins = inset_axes(ax, 4,3, loc=5)
    else:
        axins = inset_axes(ax, 4,3, loc=6)        
        axins.yaxis.tick_right()
    for i, d in enumerate(data.iterrows()):
        plt.scatter(x = np.array([i]*len(jitter_)+jitter_), y = list(d[1]))
    if c2 > c1:
        axins.set_xlim(2.9, 5.1) # apply the x-limits
    else:
        axins.set_xlim(-0.1, 2.1)
    plt.ylim(-cs, (max2/cs+2)*cs)
    from mpl_toolkits.axes_grid1.inset_locator import mark_inset
    mark_inset(ax, axins, loc1=2, loc2=4, fc="none", ec="0.5")
    plt.show()        
Example #20
0
def test_inset_axes_without_transform_should_use_parent_axes():
    # creating our figure
    fig = plt.figure(dpi=150)

    # gca method gets current axes of the figure
    ax = plt.gca()
    ax.plot([0.0, 0.25, 0.50, 1.0], [0.1, 0.2, 0.4, 0.9], color='b')

    # creating our inset_axes. without a bbox_transform parameter
    ax_ins = inset_axes(ax, width=1., height=1., bbox_to_anchor=(1, 1))
    ax_ins.plot([0.0, 0.25, 0.50, 1.0], [0.9, 0.4, 0.2, 0.1], color='r')

    assert ax.transAxes == ax_ins.transAxes
def generate_coverage_and_quality_graph(bam_readcount_output, mapping_qual_cutoff=20,coverage_cutoff=15):
    fh = open(bam_readcount_output, "r")
    x=list()
    y=list()
    colors = list()
    max_coverage = 0
    max_quality = 0
    passing_sites = 0
    while(True):
        line = fh.readline()
        if not line:
            break
        fields = line.split()
        coverage = fields[3] # bam readcount format: chr pos base depth [per base counts]
        if(max_coverage < int(coverage)):
            max_coverage = int(coverage)
        average_mapping_quality = calculate_average_mapping_quality(fields[-5:])
        color_value = calculate_color(fields)
        if(average_mapping_quality > max_quality):
            max_quality=average_mapping_quality
        if(average_mapping_quality > mapping_qual_cutoff and int(coverage) > coverage_cutoff):
            passing_sites+=1
        x.append(int(coverage))
        y.append(average_mapping_quality)
        colors.append(color_value)
    fig = plt.figure(figsize=(10,7.5), dpi=80)
    plt.scatter(x, y, color=colors, marker=".")
    plt.axhline(y=20, color="red")
    plt.axvline(x=15, color="red")
    plt.xscale('log')
    (axis_positions, axis_labels) = xlabel_ticks(max_coverage+10, 4)
    plt.xticks(axis_positions, axis_labels)
    plt.xlim(0, max_coverage+10)
    plt.ylim(0, max_quality+5)
    plt.xlabel("Coverage (log scale)")
    plt.ylabel("Average Mapping Quality")
    plt.suptitle("Gold SNP missed sites: Mapping Quality vs Coverage")
    plt.text(15, max_quality+2, "Coverage Cutoff:%s" % coverage_cutoff, color="red", fontsize="10")
    plt.text(max_coverage-100, 21, "Quality Cutoff:%s" % mapping_qual_cutoff, color="red", fontsize="10", horizontalalignment="right")
    ax = plt.gca()
    plt.text(.8, .8, "HQ sites missed:%s" % passing_sites, horizontalalignment="right", color="red", transform=ax.transAxes)
    #plt.show()
    scalar_colormap = plt.cm.ScalarMappable(cmap="RdYlGn")
    scalar_colormap.set_array(colors)
   # axins = inset_axes(ax, width ="2.5%", height="50%", loc=3, bbox_to_anchor=(1.02, 0., 1,1), bbox_transform=ax.transAxes, borderpad=0)
    axins = inset_axes(ax, width ="2.5%", height="30%", loc=2)
    cbar = fig.colorbar(scalar_colormap, cax=axins, ticks=[0, .5,1])
    cbar.ax.set_yticklabels(["100% Variant", "50% Ref", "100% Ref"])
    for label in cbar.ax.get_yticklabels():
        label.set_fontsize(8)
    plt.savefig("test.png")
Example #22
0
def insetVDF(ax, XmeshXY,YmeshXY, pass_maps):
    # pass_maps is a list of numpy arrays, not used here.
    from mpl_toolkits.axes_grid1.inset_locator import inset_axes

    # 'upper right'  : 1,
    # 'upper left'   : 2,
    # 'lower left'   : 3,
    # 'lower right'  : 4,
    # 'right'        : 5,
    # 'center left'  : 6,
    # 'center right' : 7,
    # 'lower center' : 8,
    # 'upper center' : 9,
    # 'center'       : 10

    # Generate inset axes for VDF #1
    VDFcoord = [10.8,0,-5]
    VDFax = inset_axes(ax, width="25%", height="25%", loc=2, bbox_transform=ax.transAxes)
    pt.plot.plot_vdf(filename=fileLocation+bulkname,coordre=VDFcoord,box=[-2.5e6,2.5e6,-2.5e6,2.5e6], fmin=1e-14, fmax=2e-8,slicethick=0,axes=VDFax, unit=6,nocb=1,title='',noxlabels=1,noylabels=1)
    # Add dot at VDF location
    ax.scatter(VDFcoord[0], VDFcoord[2], color='black',marker='o',s=20)
    ax.scatter(VDFcoord[0], VDFcoord[2], color='gray',marker='o',s=2)

    # Generate inset axes for VDF #2
    VDFcoord = [10.8,0,-15]
    VDFax = inset_axes(ax, width="25%", height="25%", loc=6, bbox_transform=ax.transAxes)
    pt.plot.plot_vdf(filename=fileLocation+bulkname,coordre=VDFcoord,box=[-2.5e6,2.5e6,-2.5e6,2.5e6], fmin=1e-14, fmax=2e-8,slicethick=0,axes=VDFax, unit=6,nocb=1,title='',noxlabels=1,noylabels=1)
    # Add dot at VDF location
    ax.scatter(VDFcoord[0], VDFcoord[2], color='black',marker='o',s=20)
    ax.scatter(VDFcoord[0], VDFcoord[2], color='gray',marker='o',s=2)

    # Generate inset axes for VDF #3
    VDFcoord = [10.8,0,-25]
    VDFax = inset_axes(ax, width="25%", height="25%", loc=3, bbox_transform=ax.transAxes)
    pt.plot.plot_vdf(filename=fileLocation+bulkname,coordre=VDFcoord,box=[-2.5e6,2.5e6,-2.5e6,2.5e6], fmin=1e-14, fmax=2e-8,slicethick=0,axes=VDFax, unit=6,nocb=1,title='',noxlabels=1,noylabels=1)
    # Add dot at VDF location
    ax.scatter(VDFcoord[0], VDFcoord[2], color='black',marker='o',s=20)
    ax.scatter(VDFcoord[0], VDFcoord[2], color='gray',marker='o',s=2)
Example #23
0
    def plot(self, fontsize=12, **kwargs):
        """
        Plot the convergence of the Wannierise cycle.

        Args:
            fontsize: legend and label fontsize.

        Returns: |matplotlib-Figure|
        """
        if self._parse_iterations() != 0:
            print("Wout files does not contain Wannierization cycles. Returning None")
            return None

        items = ["delta_spread", "rms_gradient", "spread"]
        if self.use_disentangle:
            items += ["omegaI_i"]

        # Build grid of plots.
        num_plots, ncols, nrows = len(items), 1, 1
        if num_plots > 1:
            ncols = 2
            nrows = (num_plots // ncols) + (num_plots % ncols)

        ax_list, fig, plt = get_axarray_fig_plt(None, nrows=nrows, ncols=ncols,
                                                sharex=True, sharey=False, squeeze=False)
        ax_list = ax_list.ravel()

        # Don't show the last ax if num_plots is odd.
        if num_plots % ncols != 0: ax_list[-1].axis("off")

        marker = "."
        for ax, item in zip(ax_list, items):
            ax.grid(True)
            ax.set_xlabel("Iteration Step")
            ax.set_ylabel(item)
            s = 1
            if item == "omegaI_i":
                # Plot Disentanglement cycles
                ax.plot(self.dis_df.iter[s:], self.dis_df[item][s:], marker=marker)
                from mpl_toolkits.axes_grid1.inset_locator import inset_axes
                ax2 = inset_axes(ax, width="60%", height="40%", loc="upper right")
                ax2.grid(True)
                ax2.set_title("delta_frac", fontsize=8)
                ax2.plot(self.dis_df.iter[s:], self.dis_df["delta_frac"][s:], marker=marker)

            else:
                ax.plot(self.conv_df.iter[s:], self.conv_df[item][s:], marker=marker)

        return fig
Example #24
0
def test_inset_axes():
    def get_demo_image():
        from matplotlib.cbook import get_sample_data
        import numpy as np
        f = get_sample_data("axes_grid/bivariate_normal.npy", asfileobj=False)
        z = np.load(f)
        # z is a numpy array of 15x15
        return z, (-3, 4, -4, 3)

    fig, ax = plt.subplots(figsize=[5, 4])

    # prepare the demo image
    Z, extent = get_demo_image()
    Z2 = np.zeros([150, 150], dtype="d")
    ny, nx = Z.shape
    Z2[30:30 + ny, 30:30 + nx] = Z

    # extent = [-3, 4, -4, 3]
    ax.imshow(Z2, extent=extent, interpolation="nearest",
              origin="lower")

    # creating our inset axes with a bbox_transform parameter
    axins = inset_axes(ax, width=1., height=1., bbox_to_anchor=(1, 1),
                       bbox_transform=ax.transAxes)

    axins.imshow(Z2, extent=extent, interpolation="nearest",
                 origin="lower")
    axins.yaxis.get_major_locator().set_params(nbins=7)
    axins.xaxis.get_major_locator().set_params(nbins=7)
    # sub region of the original image
    x1, x2, y1, y2 = -1.5, -0.9, -2.5, -1.9
    axins.set_xlim(x1, x2)
    axins.set_ylim(y1, y2)

    plt.xticks(visible=False)
    plt.yticks(visible=False)

    # draw a bbox of the region of the inset axes in the parent axes and
    # connecting lines between the bbox and the inset axes area
    mark_inset(ax, axins, loc1=2, loc2=4, fc="none", ec="0.5")

    asb = AnchoredSizeBar(ax.transData,
                          0.5,
                          '0.5',
                          loc='lower center',
                          pad=0.1, borderpad=0.5, sep=5,
                          frameon=False)
    ax.add_artist(asb)
Example #25
0
def make_colorbar(fig, ax, im, zlims):
    """
    """
    pdf_adjust = 0.01  # Dealing with some pdf crap...
    cax = inset_axes(ax, width="3%", height="100%", loc=3,
                     bbox_to_anchor=(1.01, 0.0, 1.05, 1.00),
                     bbox_transform=ax.transAxes,
                     borderpad=0.)
    cbar = fig.colorbar(im, cax, ticks=np.arange(zlims[0], zlims[-1]))
    xy = cbar.outline.xy
    xy[0:, 0] *= 1 - 5 * pdf_adjust
    xy[0:, 1] *= 1 - pdf_adjust
    cbar.outline.set_xy(xy)
    cax.invert_yaxis()
    cax.axis['right'].toggle(ticks=True, ticklabels=True, label=True)
    cax.set_ylabel(r"$\Delta \log \mathcal{L}$")
    return cax, cbar
Example #26
0
def _make_axes_inset(ax, location='right', **kwargs):
    from mpl_toolkits.axes_grid1.inset_locator import inset_axes

    location = location.lower()

    inset_kw = {
        'axes_class': _get_axes_class(ax),
        'bbox_transform': ax.transAxes,
        'borderpad': 0.,
    }

    # get orientation based on location
    if location.lower() in ('left', 'right'):
        pad = kwargs.pop('pad', _scale_width(.1, ax))
        kwargs.setdefault('orientation', 'vertical')
    elif location.lower() in ('top', 'bottom'):
        pad = kwargs.pop('pad', _scale_height(.1, ax))
        kwargs.setdefault('orientation', 'horizontal')
    orientation = kwargs.get('orientation')

    # set params for orientation
    if orientation == 'vertical':
        inset_kw['width'] = .12
        inset_kw['height'] = '100%'
    else:
        inset_kw['width'] = '100%'
        inset_kw['height'] = .12

    # set location and anchor position based on location name
    # NOTE: matplotlib-1.2 requres a location code, and fails on a string
    #       we can move back to just using strings when we drop mpl-1.2
    inset_kw['loc'], inset_kw['bbox_to_anchor'] = {
        'left': (LOC_CODES['lower right'], (-pad, 0., 1., 1.)),
        'right': (LOC_CODES['lower left'], (1+pad, 0., 1., 1.)),
        'bottom': (LOC_CODES['upper left'], (0., -pad,  1., 1.)),
        'top': (LOC_CODES['lower left'], (0., 1+pad, 1., 1.)),
    }[location]

    # allow user overrides
    for key in filter(inset_kw.__contains__, kwargs):
        inset_kw[key] = kwargs.pop(key)

    return inset_axes(ax, **inset_kw), kwargs
 def plot_figure(self, ax, xaxis, yaxis, title='', legend='', 
         drawline=True, legend_outside=False, marker=None, 
         linestyle=None, xlabel='', ylabel='', xlog=False, ylog=False, 
         zoom=False, zoom_ax=None, zoom_xaxis=[], zoom_yaxis=[], 
         legend_pos='best', xlabel_format=0, xlimit=0, ylimit=0, legend_markscale=1.0):
     if drawline:
         ax.plot(xaxis, yaxis, marker=marker if marker else '+', ls=linestyle if linestyle else '-', label=legend)
     else: #draw dots 
         ax.plot(xaxis, yaxis, marker=marker if marker else 'o', markerfacecolor='r', ms=4, ls='None', label=legend)
         #ax.vlines(xaxis, [0], yaxis)
     if xlog:
         ax.set_xscale('log')
     if ylog:
         ax.set_yscale('log')
     if xlimit > 0:
         ax.set_xlim(0, ax.get_xlim()[1] if ax.get_xlim()[1]<xlimit else xlimit)
     if ylimit > 0:
         ax.set_ylim(0, ax.get_ylim()[1] if ax.get_ylim()[1]<ylimit else ylimit)
     ax.set_title(title)
     ax.legend(loc=legend_pos, markerscale=legend_markscale)
     ax.set_xlabel(xlabel)
     ax.set_ylabel(ylabel)
     ax.ticklabel_format(axis='y', style='sci', scilimits=(0,0))
     # zoom
     if zoom:
         new_zoom_ax = False
         if zoom_ax is None:
             new_zoom_ax = True  
             zoom_ax = inset_axes(ax,
                    width="70%",  # width = 50% of parent_bbox
                    height="70%",  # height : 1 inch
                    loc=7) # center right
         if drawline:
             zoom_ax.plot(zoom_xaxis, zoom_yaxis, marker=marker if marker else '+', ls=linestyle if linestyle else '-')
         else: #draw dots 
             zoom_ax.plot(zoom_xaxis, zoom_yaxis, marker=marker if marker else 'o', markerfacecolor='r', ms=4, ls='None')
             #zoom_ax.vlines(zoom_xaxis, [0], zoom_yaxis)
         if new_zoom_ax:
             zoom_ax.ticklabel_format(axis='y', style='sci', scilimits=(0,0))
             mark_inset(ax, zoom_ax, loc1=2, loc2=4, fc="none", ec="0.5")
     return ax, zoom_ax
Example #28
0
def imshow(letter, text, figref, Z):
    interpolation = 'bicubic'
    cmap = plt.cm.hot
    axis = plt.gca()
    vmin, vmax = 0, 1

    im = plt.imshow(Z, extent = [0,1,0,1],
                    interpolation=interpolation, cmap=cmap, vmin=0,vmax=1)
    ins = inset_axes(axis, width="35%", height="5%",  loc=4, borderpad=.5)
    cbar = plt.colorbar(cax=ins, orientation="horizontal",ticks=[vmin, vmax])
    ins.xaxis.set_ticks_position("top")
    cbar.ax.set_xticklabels(['0', '1'], fontsize=8, color='w', weight='bold')

    CS = axis.contour(Z, [0.05], origin='upper',
                      linewidths=1, colors='w', extent=(0,1,0,1))

    axis.set_xlim(0,1)
    axis.set_ylim(0,1)

    axis.xaxis.set_major_locator(MultipleLocator(0.2))
    #axis.xaxis.set_minor_locator(MultipleLocator(0.01))
    axis.yaxis.set_major_locator(MultipleLocator(0.2))
    #axis.yaxis.set_minor_locator(MultipleLocator(0.01))
    axis.get_xaxis().tick_bottom()
    axis.get_yaxis().tick_left()
    axis.set_xlabel('(mm)')
    axis.set_ylabel('(mm)')

    rect = Rectangle((.25,.25), .5, .5, facecolor='None', edgecolor='w', ls='dashed', lw=.75)
    axis.add_patch(rect)
    #t = axis.text(.26,.74, "RoI", ha='left', va='top', zorder=1,
    #               weight='bold', color='w', fontsize=16, alpha=.5)
    #t.set_path_effects([PathEffects.withStroke(linewidth=.75,foreground="k",alpha=.25)])
    axis.text(1,1.01,text, ha='right', va='bottom', weight='bold')
    axis.text(0,1.01,letter, ha='left', va='bottom', color='k')

    axis.text(0.05,0.95,figref, ha='left', va='top', color='w',  weight='bold', fontsize=16)


    return im
Example #29
0
def test_inset_axes_complete():
    dpi = 100
    figsize = (6, 5)
    fig, ax = plt.subplots(figsize=figsize, dpi=dpi)
    fig.subplots_adjust(.1, .1, .9, .9)

    ins = inset_axes(ax, width=2., height=2., borderpad=0)
    fig.canvas.draw()
    assert_array_almost_equal(
            ins.get_position().extents,
            np.array(((0.9*figsize[0]-2.)/figsize[0],
                      (0.9*figsize[1]-2.)/figsize[1], 0.9, 0.9)))

    ins = inset_axes(ax, width="40%", height="30%", borderpad=0)
    fig.canvas.draw()
    assert_array_almost_equal(
            ins.get_position().extents,
            np.array((.9-.8*.4, .9-.8*.3, 0.9, 0.9)))

    ins = inset_axes(ax, width=1., height=1.2, bbox_to_anchor=(200, 100),
                     loc=3, borderpad=0)
    fig.canvas.draw()
    assert_array_almost_equal(
            ins.get_position().extents,
            np.array((200./dpi/figsize[0], 100./dpi/figsize[1],
                     (200./dpi+1)/figsize[0], (100./dpi+1.2)/figsize[1])))

    ins1 = inset_axes(ax, width="35%", height="60%", loc=3, borderpad=1)
    ins2 = inset_axes(ax, width="100%", height="100%",
                      bbox_to_anchor=(0, 0, .35, .60),
                      bbox_transform=ax.transAxes, loc=3, borderpad=1)
    fig.canvas.draw()
    assert_array_equal(ins1.get_position().extents,
                       ins2.get_position().extents)

    with pytest.raises(ValueError):
        ins = inset_axes(ax, width="40%", height="30%",
                         bbox_to_anchor=(0.4, 0.5))

    with pytest.warns(UserWarning):
        ins = inset_axes(ax, width="40%", height="30%",
                         bbox_transform=ax.transAxes)
Example #30
0
def inset_title_box(ax,title,bwidth="20%",location=1):
    """
    Function that puts title of subplot in a box
    
    :ax:    Name of matplotlib axis to add inset title text box too
    :title: 'string to put inside text box'
    :returns: @todo
    """

    axins = inset_axes(ax,
                       width=bwidth, # width = 30% of parent_bbox
                       height=.30, # height : 1 inch
                       loc=location)

    plt.setp(axins.get_xticklabels(), visible=False)
    plt.setp(axins.get_yticklabels(), visible=False)
    axins.set_xticks([])
    axins.set_yticks([])

    axins.text(0.5,0.3,title,
            horizontalalignment='center',
            transform=axins.transAxes,size=10)
                                    3,
                                    figsize=(11, 8),
                                    dpi=300,
                                    sharey=True,
                                    gridspec_kw={
                                        'wspace': 0,
                                        'hspace': 0
                                    })

plot_b = pisco_p.plot(ax=ax0,
                      cmap='viridis_r',
                      add_colorbar=False,
                      levels=[0, 10, 50, 100, 200, 900])
axin = inset_axes(ax0,
                  width='4%',
                  height='35%',
                  loc='lower left',
                  bbox_to_anchor=(0.05, 0.025, 1, 1),
                  bbox_transform=ax0.transAxes)
cb = plt.colorbar(plot_b, cax=axin, orientation="vertical", aspect=5)
cb.ax.set_ylabel('Precipitación ($mm$)', labelpad=-30, size=6)
cb.ax.tick_params(labelsize=6, pad=0)

#shp_drainages.geometry.boundary.plot(ax = ax0, edgecolor = "black", linewidth = .75)
shp_SA.geometry.boundary.plot(ax=ax0, edgecolor="black", linewidth=.5)
shp_dep.geometry.boundary.plot(ax=ax0, edgecolor="black", linewidth=.25)
shp_lks.plot(ax=ax0, edgecolor="deepskyblue", color="deepskyblue")

ax0.set_ylim(-18.5, 0.5)
ax0.set_xlim(-81.75, -68)
ax0.set_ylabel("")
ax0.set_xlabel("")
Example #32
0
            x, y = [self.vmin, self.midpoint, self.vmax], [0, 0.5, 1]
            return np.ma.masked_array(np.interp(value, x, y))
##end for norm colorbar####

#### header data ####

    data = sdf.read("./0012_laser.sdf", dict=True)
    header = data['Header']
    time = header['time']
    x = data['Grid/Grid_mid'].data[0] / 1.0e-6
    print('ok')
    y = data['Grid/Grid_mid'].data[1] / 1.0e-6
    X, Y = np.meshgrid(x, y)

    ax = plt.subplot(2, 1, 1)
    axin1 = inset_axes(ax, width='20%', height='5%', loc='upper left')
    ex = data['Electric Field/Ex'].data / exunit
    #   ex[ex > 8]=8
    #   ex[ex < -8]=-8
    eee = np.max([-np.min(ex.T), np.max(ex.T)])
    levels = np.linspace(-2, 2, 64)
    image = ax.contourf(X,
                        Y,
                        ex.T,
                        levels=levels,
                        norm=mcolors.Normalize(vmin=-2.0, vmax=2.0),
                        cmap=cm.jet)
    line_x = np.linspace(5, 200, 1001)
    R_length = 3.14 * 4**2 / 1.0
    line_y1 = 4.0 * (1 + ((line_x - 5.0) / R_length)**2.0)**0.5
    line_y2 = -4.0 * (1 + ((line_x - 5.0) / R_length)**2.0)**0.5
Example #33
0
ax4.tick_params(axis='x', direction='in', length=6, width=1.1, which='major', colors='black',
                grid_color='black', grid_alpha=0.4)
ax4.tick_params(which='minor', length=4, color='black', direction='in')
ax4.tick_params(axis='y', which='minor', length=4, color='black', direction='in')
ax4.tick_params(axis='y', which='major', direction='in', length=6, width=0.9, colors='black',
                grid_color='black', grid_alpha=0.4)

ax4.set_xlim(tmin, tmax)
# ax4.vlines(12,0,1)
# ax4.vlines(10,0,1)
# ax4.vlines(8,0,1)

# axins = inset_axes(ax4, width=1.855, height=1.1)
axins = inset_axes(ax4, width="31.42%", height="50%",
                   bbox_to_anchor=(.5456, .46, .885, .9),
                   bbox_transform=ax4.transAxes, loc=3)
axins.tick_params(direction='in')  #, labelbottom=False
axins.plot(times_Gyr(tree_sat3['z']), (tree_sat3['ssfr'] * 1e11), '-r')
axins.set_xlim(8.5, 12)
axins.set_ylim(-0.02 * 10 ** (-11) * 1e11, 2 * 10 ** (-11) * 1e11)
axins.vlines(t_quench3, min(tree_sat3['ssfr']), max(tree_sat3['ssfr'] + 0.5), colors='black', linestyles='--', lw=1,
             zorder=10)
axins.hlines(10 ** (-10.93) * 1e11, tmin, tmax, colors='black', linestyles='--', lw=1, zorder=10)
axins.tick_params(axis='x', direction='in', length=6, width=1.2, which='major', colors='black',
                  grid_color='black', grid_alpha=0.4)
axins.tick_params(axis='y', which='major', direction='in', length=6, width=0.9, colors='black',
                  grid_color='black', grid_alpha=0.4)

axins.text(10.95, +1.45 * 10 ** (-11) * 1e11, r'$ \mathtt{SSFRcut}  $',
           rotation=0,
Example #34
0
def create_figure(
        reference_shape="ellipsoid",
        temp_files_path=".",
        show_progress=False,
        length_max=8.0,
        l_shear_max=1500.0,
        dx=4.0,
        xlim=(-0.01, 0.25),
        ylim=(-0.01, 0.55),
        aspect=0.5,
        figsize=(5, 5),
):
    if reference_shape == "ellipsoid":
        x_pos_shape = 1.2
        y_pos_shape = 0.3
    else:
        x_pos_shape = 0.8
        y_pos_shape = 0.5

    temp_files_path = Path(temp_files_path).expanduser()

    temp_files_path.mkdir(exist_ok=True, parents=True)
    fig, ax = plt.subplots(figsize=figsize)
    ax.set_aspect(1)
    reference_lines = plot_fp_ref(
        ax=ax,
        shape=reference_shape,
        lm_range=slice(1.0 / 4.0, 9),
        calc_kwargs=dict(N_points=400),
        reference_data_path=temp_files_path,
        include_shape_diagram="at_reference_points",
        marker="shape",
        x_pos=x_pos_shape,
        y_pos=y_pos_shape,
    )

    ds_study = xr.Dataset(coords=dict(
        h=[1000.0],
        length=np.arange(2.0, length_max, 1.0),
        l_shear=np.arange(0.0, l_shear_max, 500.0),
        dx=[
            dx,
        ],
        shape=["thermal"],
    ))

    def format_length(v):
        if v == np.inf:
            return r"$\infty$"
        else:
            return r"{}m".format(v)

    # create a new flattened index
    ds_flat = ds_study.stack(i=ds_study.dims).reset_index("i")

    if show_progress:
        iterator = tqdm.tqdm
    else:
        iterator = lambda v: v  # noqa

    datasets = []
    for i in iterator(range(len(ds_flat.i))):
        ds_params = ds_flat.isel(i=i)

        img = _get_mask_image(ds_params=ds_params, output_path=temp_files_path)
        ds_scales = _calc_scales(ds_params=ds_params,
                                 output_path=temp_files_path)
        ds_scales = ds_scales.assign_coords(object_id=[i])

        lx, ly = 0.04, 0.04
        extent = np.array([
            ds_scales.planarity - lx / 2.0,
            ds_scales.planarity + lx / 2.0,
            ds_scales.filamentarity - ly / 2.0,
            ds_scales.filamentarity + ly / 2.0,
        ]).T[0]
        ax.imshow(img, extent=extent)
        datasets.append(xr.merge([ds_scales, ds_params]))

    ax.set_xlim(*xlim)
    ax.set_ylim(*ylim)
    ax.set_aspect(aspect)
    sns.despine()

    ax_inset = inset_axes(
        parent_axes=ax,
        width="100%",
        height="100%",
        bbox_to_anchor=(0.47, ylim[0], 0.16, 0.25),
        bbox_transform=ax.transData,
        borderpad=0,
        axes_kwargs=dict(facecolor="none"),
    )
    _add_text_fp_diagram(ax=ax_inset)

    return ax, xr.concat(datasets, dim="object_id"), reference_lines
Example #35
0
handles = plot_labelled_filled_contours(ds.U, ax=ax[0], label='a)')

# Set a common title
plt.suptitle("A common title", fontsize=16, y=0.94)

# Contour-plot V data
plot_labelled_filled_contours(ds.V, ax=ax[1], label='b)')

# Contour-plot U data again but in the bottom axes
plot_labelled_filled_contours(ds.U, ax=ax[2], label='c)')

# Create inset axes for colorbar
cax = inset_axes(ax[2],
                 width='100%',
                 height='7%',
                 loc='lower left',
                 bbox_to_anchor=(0, -0.25, 1, 1),
                 bbox_transform=ax[2].transAxes,
                 borderpad=0)
# Add horizontal colorbar
cbar = plt.colorbar(handles["filled"],
                    cax=cax,
                    orientation="horizontal",
                    ticks=levels[:-1],
                    drawedges=True,
                    aspect=30,
                    extendrect=True,
                    extendfrac='auto',
                    shrink=0.8)
cbar.ax.tick_params(labelsize=10)
Example #36
0
    def state(self, slice_num, tmin, tmax, use_colormap, width, height):
        fig_matrix = [6, 1]
        fig, gs, axes = self.configure(fig_matrix, width, height)
        delay_length = self.delay_length

        in_state = self.data[:, :self.in_state_size]
        out_state = self.data[:, self.in_state_size:self.in_state_size * 2]

        var_state = self.data[:, self.in_state_size * 2:self.in_state_size *
                              3] + 0.00001
        c_state = np.tanh(
            self.data[:, self.in_state_size * 3:self.in_state_size * 3 +
                      self.neuron_num])
        pb_state = np.tanh(self.data[:, self.in_state_size * 3 +
                                     self.neuron_num:])

        error = (in_state[delay_length:, :] - out_state[:-delay_length, :]) * (
            in_state[delay_length:, :] - out_state[:-delay_length, :]) / 2.0

        likelihood = 0.5 * np.log(
            2 * np.pi * var_state[:-delay_length, :]) + 0.5 * (
                in_state[delay_length:, :] - out_state[:-delay_length, :]
            ) * (in_state[delay_length:, :] -
                 out_state[:-delay_length, :]) / var_state[:-delay_length, :]

        axes[0].plot(in_state[:, :8])

        self.add_info(axes[0], None, (0, in_state.shape[0]), (-1, 1), None,
                      "Predicted" + "\nJoint")

        axes[1].plot(in_state[:, 8], "g")
        axes[1].plot(in_state[:, 9], "r")

        self.add_info(axes[1], None, (0, in_state.shape[0]), (-1, 1), None,
                      "Input" + "\nVision")

        axes[2].plot(var_state[:, 8], "g")
        axes[2].plot(var_state[:, 9], "r")

        self.add_info(axes[2], None, (0, var_state.shape[0]),
                      (10**(-6), 10**1), None, "Variance")

        axes[2].set_yscale("log")

        if use_colormap:

            range = [-1, 1]
            im = self.plot_colormap(axes[3], c_state[:, :], range)
            im_pb = self.plot_colormap(axes[4], pb_state[:, :], range)

            self.add_info(axes[3], None, None, None, None, "Index of\ncontext")

            self.add_info(axes[4], None, None, None, None, "Index of\n pb")

            if c_state.shape[1] is 1:
                self.set_no_yticks(axes[3])

            if pb_state.shape[1] is 1:
                self.set_no_yticks(axes[4])

            axins = inset_axes(
                axes[3],
                width="5%",  # width = 5% of parent_bbox width
                height="100%",  # height : 100%
                loc=3,
                bbox_to_anchor=(1.05, 0, 1, 1),
                bbox_transform=axes[3].transAxes,
                borderpad=0,
            )
            axins_pb = inset_axes(
                axes[4],
                width="5%",
                height="100%",  # height = "100%"
                loc=3,
                bbox_to_anchor=(1.05, 0, 1, 1),
                bbox_transform=axes[4].transAxes,
                borderpad=0,
            )

            plt.colorbar(im, cax=axins, ticks=(-1, 0, 1))
            plt.colorbar(im_pb, cax=axins_pb, ticks=(-1, 0, 1))
            gs.tight_layout(fig, rect=[0, 0, 0.95,
                                       1])  # left, bottom, right, top

        else:
            axes[3].plot(c_state[:, 0:50])
            axes[4].plot(pb_state[:, :])
            self.add_info(axes[3], None, (0, c_state.shape[0]), (-1.2, 1.2),
                          None, "Context")
            self.add_info(axes[4], None, (0, pb_state.shape[0]), (-1.2, 1.2),
                          None, "PB")

            gs.tight_layout(fig, rect=[0, 0, 1, 1])  # left, bottom, right, top

        axes[5].plot(likelihood[:, ::slice_num])
        self.add_info(axes[5], None, (0, in_state.shape[0]), None, "Time step",
                      "- log likelihood")

        for ax in axes:
            ax.set_xlim(tmin, tmax)

        fig.savefig(self.figure_name)
        fig.show()
            xytext=xy_inset_high,
            arrowprops=dict(arrowstyle="-", alpha=0.9, linewidth=0.8),
            xycoords='axes fraction')

#Mark-up

ax.set_xlabel(thyrago)
ax.set_ylabel(co2con)
ax.invert_xaxis()
ax.yaxis.tick_right()
ax.tick_params(axis='both', which='major', labelsize=14)
ax.yaxis.set_label_position("right")
ax.set_facecolor((0.94, 0.94, 0.94))

#Inset figure
axins = inset_axes(ax, 3.7, 0.7, bbox_to_anchor=(360, 250))
axins.plot(df_lawdome_all['yr'], df_lawdome_all['CO2'], 'C2', linewidth=2.2)
axins.plot(co2matrix[:, 0], co2matrix[:, 1], 'k', linewidth=2.2)

axins.set_xlabel(year, fontsize=13, labelpad=-0.2)
axins.tick_params(labelsize=13, direction='in')

# sub region of the original image
x1, x2, y1, y2 = 1000, 2025, 260, 420
axins.set_xlim(x1, x2)
axins.set_ylim(y1, y2)

# fix the number of ticks on the inset axes
axins.yaxis.get_major_locator().set_params(nbins=4)
axins.xaxis.get_major_locator().set_params(nbins=5)
Example #38
0
# Colorbar positon (right,left,top,bottom)
cbpos = "right"
if (cbpos == "right") or (cbpos == "left"):
    cbor = 'vertical'
    rotation = 270
if (cbpos == "top") or (cbpos == "bottom"):
    cbor = 'horizontal'
    rotation = 0

#divider = make_axes_locatable(ax)
#cax = divider.append_axes(cbpos,size="5%",pad=0.05)
cax = inset_axes(ax,
                 width="5%",
                 height="45%",
                 loc='upper right',
                 bbox_to_anchor=(0.06, -0.01, 1, 1),
                 bbox_transform=ax.transAxes,
                 borderpad=0)
cbarn = fig.colorbar(cn, orientation=cbor, cax=cax)
cbarn.set_label(r'$\log(\rho/\rho_\infty)$',
                rotation=rotation,
                fontsize=fontsize,
                labelpad=15)
if (cbpos == "right") or (cbpos == "left"):
    cax.yaxis.set_ticks_position(cbpos)
    cax.yaxis.set_label_position(cbpos)
if (cbpos == "top") or (cbpos == "bottom"):
    cax.xaxis.set_ticks_position(cbpos)
    cax.xaxis.set_label_position(cbpos)
def pp_conf_matrix(classifier,X_y_dict,expl_lables,savefig_dir=None):
    """ pp_conf_matrix - display confusion matrix, accuracy, recall, precision and f1 score to evaluate the accuracy of a classification. 
    
    Keyword arguments:
    classifier -- dateframe with classes to display
    X_y_dict -- dictionary type: {dataset name: (X column, y column)}
    expl_lables -- dictionary for explaining class labels    
    savefig_dir -- A path to save the current figure (default None)
    
    """
    
    
    figsize=max(10,2*len(expl_lables))
    list_keys=list(X_y_dict.keys())
    fig,axs=plt.subplots(nrows=1, ncols=len(list_keys),figsize=(figsize,figsize), constrained_layout=True)
    
    if len(expl_lables)==2:
        average='binary'
    else:
        average='macro'
    
    for key in list_keys:
        X_test=X_y_dict[key][0]
        y_pred=classifier.predict(X_test)
        y_test=X_y_dict[key][1]
        confmat = confusion_matrix(y_true=y_test, y_pred=y_pred)
        
        ax=axs[list_keys.index(key)]
        
        im=ax.matshow(confmat, cmap=plt.cm.prism, alpha=0.3)
        for i in range(confmat.shape[0]):
            for j in range(confmat.shape[1]):
                ax.text(x=j, y=i,s=confmat[i, j],va='center', ha='center')
        
       
        text='{0}\nТочність: {1}\nRecall score: {2}\nPrecision_score: {3}\nF1 score(macro): {4}'.format(key,
                                                                                  classifier.score(X_test,y_test),
                                                                                  recall_score(y_true=y_test, y_pred=y_pred,average=average),
                                                                                  precision_score(y_true=y_test, y_pred=y_pred,average=average),
                                                                                  f1_score(y_true=y_test, y_pred=y_pred,average=average))
        ax.text(0.5, -0.33*10/figsize, text,
         horizontalalignment='center',
         fontsize=11,
         transform = ax.transAxes)
                
        ax.set_xticklabels(['']+list(expl_lables.values()),rotation=90)
        ax.set_yticklabels(['']+list(expl_lables.values()))  
        
        axins = inset_axes(ax,
                   width="10%",  
                   height="100%", 
                   loc='lower left',
                   bbox_to_anchor=(1.05, 0., 1, 1),
                   bbox_transform=ax.transAxes,
                   borderpad=0,
                   )
        fig.colorbar(im,cax=axins,ax=axs[list_keys.index(key)])
        fig.set_constrained_layout_pads(w_pad=2./72., h_pad=2./72.,
        hspace=0.2, wspace=0.2)
        ax.set_xlabel('Розпізнані мітки' )
        ax.set_ylabel('Вірні мітки')
    if savefig_dir!=None:
        plt.savefig(savefig_dir)
    plt.show()   
     
    'random': random_sample,
    'gamma': gamma_sample
})
plt.figure()
# create a boxplot of the normal data, assign the output to a variable to supress output
_ = plt.boxplot(df['normal'], whis='range')
# clear the current figure
plt.clf()
# plot boxplots for all three of df's columns
_ = plt.boxplot([df['normal'], df['random'], df['gamma']], whis='range')
plt.figure()
_ = plt.hist(df['gamma'], bins=100)
plt.figure()
plt.boxplot([df['normal'], df['random'], df['gamma']], whis='range')
# overlay axis on top of another
ax2 = mpl_il.inset_axes(plt.gca(), width='60%', height='40%', loc=2)
ax2.hist(df['gamma'], bins=100)
ax2.margins(x=0.5)
# switch the y axis ticks for ax2 to the right side
ax2.yaxis.tick_right()
# if `whis` argument isn't passed, boxplot defaults to showing 1.5*interquartile (IQR) whiskers with outliers
plt.figure()
_ = plt.boxplot([df['normal'], df['random'], df['gamma']])
sns.factorplot('TotalComments', 'TotalVotes', data=yourkernels)
plt.show()
plt.figure()

Y = np.random.normal(loc=0.0, scale=1.0, size=10000)
X = np.random.random(size=10000)
_ = plt.hist2d(X, Y, bins=25)
plt.figure()
Example #41
0
def make_pdf_plot(args):
    res, hd, mc_samples, analysis, var, baseline_weight, weight_xs, int_lumi, outdir, datataking_year, groups, extra_kwargs = args
    import matplotlib
    matplotlib.use("Agg")
    import matplotlib.pyplot as plt

    if np.sum(hd.contents) == 0:
        print("ERROR: Histogram {0} was empty, skipping".format(var))
        return

    hist_template = copy.deepcopy(hd)
    hist_template.contents[:] = 0
    hist_template.contents_w2[:] = 0

    hmc = {}

    for mc_samp in mc_samples:
        h = res[mc_samp][baseline_weight]
        h = h * weight_xs[mc_samp]
        h.label = "{0} ({1:.1E})".format(mc_samp, np.sum(h.contents))
        hmc[mc_samp] = h
    
    hmc_g = group_samples(hmc, groups)

    for k, v in hmc_g.items():
        if k in colors.keys():
            v.color = colors[k][0]/255.0, colors[k][1]/255.0, colors[k][2]/255.0
    hmc = [hmc_g[k[0]] for k in groups]

        
    htot_nominal = sum(hmc, hist_template)
    htot_variated = {}
    hdelta_quadrature = np.zeros_like(hist_template.contents)
    
    for sdir in ["__up", "__down"]:
        for unc in shape_systematics:
            if (unc + sdir) in res[mc_samp]:
                htot_variated[unc + sdir] = sum([
                    res[mc_samp][unc + sdir]* weight_xs[mc_samp] for mc_samp in mc_samples
                ], hist_template)
                hdelta_quadrature += (htot_nominal.contents - htot_variated[unc+sdir].contents)**2
            
    hdelta_quadrature_stat = np.sqrt(htot_nominal.contents_w2)
    hdelta_quadrature_stat_syst = np.sqrt(hdelta_quadrature_stat**2 + hdelta_quadrature)
    hd.label = "data ({0:.1E})".format(np.sum(hd.contents))

    figure = plt.figure(figsize=(5,5), dpi=100)
    a1, a2 = plot_hist_ratio(
        hmc, hd,
        total_err_stat=hdelta_quadrature_stat,
        total_err_stat_syst=hdelta_quadrature_stat_syst,
        figure=figure, **extra_kwargs)
    
    colorlist = [h.color for h in hmc]
    a1inset = inset_axes(a1, width=1.0, height=0.1, loc=2)
    pct_barh(a1inset, [np.sum(h.contents) for h in hmc], colorlist)
    #a2.grid(which="both", linewidth=0.5)
    
    # Ratio axis ticks
    #ts = a2.set_yticks([0.5, 1.0, 1.5], minor=False)
    #ts = a2.set_yticks(np.arange(0,2,0.2), minor=True)
    #ts = a2.set_xticklabels([])

    a1.text(0.03,0.95, "CMS internal\n" +
        r"$L = {0:.1f}\ fb^{{-1}}$".format(int_lumi/1000.0) + 
        "\nd/mc={0:.2f}".format(np.sum(hd.contents)/np.sum(htot_nominal.contents)) + 
        "\nwd={0:.2E}".format(wasserstein_distance(htot_nominal.contents/np.sum(htot_nominal.contents), hd.contents/np.sum(hd.contents))) +
        "\nks={0:.2E}".format(kolmogorov_smirnov(
            htot_nominal.contents, hd.contents,
            variances1=htot_nominal.contents_w2,
            variances2=hd.contents_w2
        )),
        horizontalalignment='left',
        verticalalignment='top',
        transform=a1.transAxes,
        fontsize=10
    )
    handles, labels = a1.get_legend_handles_labels()
    a1.legend(handles[::-1], labels[::-1], frameon=False, fontsize=10, loc=1, ncol=2)
    
    varname, catname = assign_plot_title_label(var)
    
    a1.set_title(catname + " ({0})".format(analysis_names[analysis][datataking_year]))
    a2.set_xlabel(varname)
    
    binwidth = np.diff(hd.edges)[0]
    a1.set_ylabel("events / bin [{0:.1f}]".format(binwidth))
    try:
        os.makedirs(outdir + "/png")
    except Exception as e:
        pass
    try:
        os.makedirs(outdir + "/pdf")
    except Exception as e:
        pass

    plt.savefig(outdir + "/pdf/{0}_{1}_{2}.pdf".format(analysis, var, baseline_weight), bbox_inches="tight")
    plt.savefig(outdir + "/png/{0}_{1}_{2}.png".format(analysis, var, baseline_weight), bbox_inches="tight", dpi=100)
    plt.close(figure)
    del figure
 
    return
Example #42
0
def draw_map(*lonlats,
             scale=0.2,
             world=False,
             us=True,
             eu=False,
             labels=[],
             ax=None,
             gray=False,
             res='i',
             **scatter_kws):
    PLOT_WIDTH = 8
    PLOT_HEIGHT = 6

    WORLD_MAP = {'cyl': [-90, 85, -180, 180]}
    US_MAP = {
        'cyl': [24, 49, -126, -65],
        'lcc': [23, 48, -121, -64],
    }
    EU_MAP = {
        'cyl': [34, 65, -12, 40],
        'lcc': [30.5, 64, -10, 40],
    }

    def mark_inset(ax, ax2, m, m2, MAP, loc1=(1, 2), loc2=(3, 4), **kwargs):
        """
	    https://stackoverflow.com/questions/41610834/basemap-projection-geos-controlling-mark-inset-location
	    Patched mark_inset to work with Basemap.
	    Reason: Basemap converts Geographic (lon/lat) to Map Projection (x/y) coordinates

	    Additionally: set connector locations separately for both axes:
	        loc1 & loc2: tuple defining start and end-locations of connector 1 & 2
	    """
        axzoom_geoLims = (MAP['cyl'][2:], MAP['cyl'][:2])
        rect = TransformedBbox(Bbox(np.array(m(*axzoom_geoLims)).T),
                               ax.transData)
        pp = BboxPatch(rect, fill=False, **kwargs)
        ax.add_patch(pp)
        p1 = BboxConnector(ax2.bbox,
                           rect,
                           loc1=loc1[0],
                           loc2=loc1[1],
                           **kwargs)
        ax2.add_patch(p1)
        p1.set_clip_on(False)
        p2 = BboxConnector(ax2.bbox,
                           rect,
                           loc1=loc2[0],
                           loc2=loc2[1],
                           **kwargs)
        ax2.add_patch(p2)
        p2.set_clip_on(False)
        return pp, p1, p2

    if world:
        MAP = WORLD_MAP
        kwargs = {'projection': 'cyl', 'resolution': res}
    elif us:
        MAP = US_MAP
        kwargs = {
            'projection': 'lcc',
            'lat_0': 30,
            'lon_0': -98,
            'resolution': res
        }  #, 'epsg':4269}
    elif eu:
        MAP = EU_MAP
        kwargs = {
            'projection': 'lcc',
            'lat_0': 48,
            'lon_0': 27,
            'resolution': res
        }
    else:
        raise Exception('Must plot world, US, or EU')

    kwargs.update(
        dict(
            zip(['llcrnrlat', 'urcrnrlat', 'llcrnrlon', 'urcrnrlon'],
                MAP['lcc' if 'lcc' in MAP else 'cyl'])))
    if ax is None:
        f = plt.figure(figsize=(PLOT_WIDTH, PLOT_HEIGHT), edgecolor='w')
    m = Basemap(ax=ax, **kwargs)
    ax = m.ax if m.ax is not None else plt.gca()

    if not world:
        m.readshapefile(Path(__file__).parent.joinpath('map_files',
                                                       'st99_d00').as_posix(),
                        name='states',
                        drawbounds=True,
                        color='k',
                        linewidth=0.5,
                        zorder=11)
        m.fillcontinents(color=(0, 0, 0, 0), lake_color='#9abee0', zorder=9)
        if not gray:
            m.drawrivers(linewidth=0.2, color='blue', zorder=9)
        m.drawcountries(color='k', linewidth=0.5)
    else:
        m.drawcountries(color='w')
    # m.bluemarble()
    if not gray:
        if us or eu: m.shadedrelief(scale=0.3 if world else 1)
        else:
            # m.arcgisimage(service='ESRI_Imagery_World_2D', xpixels = 2000, verbose= True)
            m.arcgisimage(service='World_Imagery', xpixels=2000, verbose=True)
    else:
        pass
    # lats = m.drawparallels(np.linspace(MAP[0], MAP[1], 13))
    # lons = m.drawmeridians(np.linspace(MAP[2], MAP[3], 13))

    # lat_lines = chain(*(tup[1][0] for tup in lats.items()))
    # lon_lines = chain(*(tup[1][0] for tup in lons.items()))
    # all_lines = chain(lat_lines, lon_lines)

    # for line in all_lines:
    # 	line.set(linestyle='-', alpha=0.0, color='w')

    if labels:
        colors = [
            'aqua',
            'orangered',
            'xkcd:tangerine',
            'xkcd:fresh green',
            'xkcd:clay',
            'magenta',
            'xkcd:sky blue',
            'xkcd:greyish blue',
            'xkcd:goldenrod',
        ]
        markers = [
            'o',
            '^',
            's',
            '*',
            'v',
            'X',
            '.',
            'x',
        ]
        mod_cr = False
        assert (len(labels) == len(lonlats)), [len(labels), len(lonlats)]
        for i, (label, lonlat) in enumerate(zip(labels, lonlats)):
            lonlat = np.atleast_2d(lonlat)
            if 'color' not in scatter_kws or mod_cr:
                scatter_kws['color'] = colors[i]
                scatter_kws['marker'] = markers[i]
                mod_cr = True
            ax.scatter(*m(lonlat[:, 0], lonlat[:, 1]),
                       label=label,
                       zorder=12,
                       **scatter_kws)
        ax.legend(loc='lower left', prop={
            'weight': 'bold',
            'size': 8
        }).set_zorder(20)

    else:
        for lonlat in lonlats:
            if len(lonlat):
                lonlat = np.atleast_2d(lonlat)
                s = ax.scatter(*m(lonlat[:, 0], lonlat[:, 1]),
                               zorder=12,
                               **scatter_kws)
                # plt.colorbar(s, ax=ax)
    hide_kwargs = {'axis': 'both', 'which': 'both'}
    hide_kwargs.update(
        dict([(k, False) for k in
              ['bottom', 'top', 'left', 'right', 'labelleft', 'labelbottom']]))
    ax.tick_params(**hide_kwargs)

    for axis in ['top', 'bottom', 'left', 'right']:
        ax.spines[axis].set_linewidth(1.5)
        ax.spines[axis].set_zorder(50)
    # plt.axis('off')

    if world:
        size = 0.35
        if us:
            loc = (0.25, -0.1) if eu else (0.35, -0.01)
            ax_ins = inset_axes(ax,
                                width=PLOT_WIDTH * size,
                                height=PLOT_HEIGHT * size,
                                loc='center',
                                bbox_to_anchor=loc,
                                bbox_transform=ax.transAxes,
                                axes_kwargs={'zorder': 5})

            scatter_kws.update({'s': 6})
            m2 = draw_map(*lonlats, labels=labels, ax=ax_ins, **scatter_kws)

            mark_inset(ax,
                       ax_ins,
                       m,
                       m2,
                       US_MAP,
                       loc1=(1, 1),
                       loc2=(2, 2),
                       edgecolor='grey',
                       zorder=3)
            mark_inset(ax,
                       ax_ins,
                       m,
                       m2,
                       US_MAP,
                       loc1=[3, 3],
                       loc2=[4, 4],
                       edgecolor='grey',
                       zorder=0)

        if eu:
            ax_ins = inset_axes(ax,
                                width=PLOT_WIDTH * size,
                                height=PLOT_HEIGHT * size,
                                loc='center',
                                bbox_to_anchor=(0.75, -0.05),
                                bbox_transform=ax.transAxes,
                                axes_kwargs={'zorder': 5})

            scatter_kws.update({'s': 6})
            m2 = draw_map(*lonlats,
                          us=False,
                          eu=True,
                          labels=labels,
                          ax=ax_ins,
                          **scatter_kws)

            mark_inset(ax,
                       ax_ins,
                       m,
                       m2,
                       EU_MAP,
                       loc1=(1, 1),
                       loc2=(2, 2),
                       edgecolor='grey',
                       zorder=3)
            mark_inset(ax,
                       ax_ins,
                       m,
                       m2,
                       EU_MAP,
                       loc1=[3, 3],
                       loc2=[4, 4],
                       edgecolor='grey',
                       zorder=0)

    return m
Example #43
0
            map0.pcolormesh(xx,
                            yy,
                            T_var_decades[:, :, i + 1] -
                            T_var_decades[:, :, 0],
                            cmap=my_cmap,
                            norm=divnorm,
                            ax=ax)
            map0.drawcoastlines(ax=ax)
            title = decaden[i + 1] + ' from ' + decaden[0]
            ax.set_title(title)

        axins = inset_axes(
            ax,
            width='100%',
            height='5%',
            loc='lower center',
            bbox_to_anchor=(-0.52, -0.1, 1, 1),
            bbox_transform=ax.transAxes,
            borderpad=0,
        )
        sm = plt.cm.ScalarMappable(cmap=my_cmap, norm=divnorm)
        cbar = fig.colorbar(sm, cax=axins, orientation='horizontal')
        cbar.set_ticks([vmin, vmin / 2, 0, vmax / 2, vmax])
        labels = [
            str(vmin) + degree_sign + 'C',
            str(vmin / 2) + degree_sign + 'C', '0' + degree_sign + 'C',
            str(vmax / 2) + degree_sign + 'C',
            str(vmax) + degree_sign + 'C'
        ]
        cbar.set_ticklabels(labels)
        plt.savefig('decade_plots/' + ssp + '/' + 'T_var_decades_' + ssp +
Example #44
0
freqaxes.append(plt.subplot(gs[0, 2], sharex=freqaxes[0], sharey=freqaxes[0]))
freqaxes.append(plt.subplot(gs[0, 4], sharex=freqaxes[0], sharey=freqaxes[0]))

distanceaxes.append(plt.subplot(gs[1, 0]))
distanceaxes.append(
    plt.subplot(gs[1, 2], sharex=distanceaxes[0], sharey=distanceaxes[0]))
distanceaxes.append(
    plt.subplot(gs[1, 4], sharex=distanceaxes[0], sharey=distanceaxes[0]))

saxes.append(plt.subplot(gs[2, 0]))
saxes.append(plt.subplot(gs[2, 2], sharex=saxes[0], sharey=saxes[0]))
saxes.append(plt.subplot(gs[2, 4], sharex=saxes[0], sharey=saxes[0]))

for i in range(len(saxes)):
    saxes_inset.append(
        inset_axes(saxes[i], width="50%", height=0.5, loc='upper right'))

# Axes for non-fixations
freqaxes_notfixed = []
distanceaxes_notfixed = []
saxes_notfixed = []
freqaxes_notfixed.append(plt.subplot(gs[0, 1], sharey=freqaxes[0]))
freqaxes_notfixed.append(
    plt.subplot(gs[0, 3], sharex=freqaxes[0], sharey=freqaxes[0]))
freqaxes_notfixed.append(
    plt.subplot(gs[0, 5], sharex=freqaxes[0], sharey=freqaxes[0]))

distanceaxes_notfixed.append(plt.subplot(gs[1, 1], sharey=distanceaxes[0]))
distanceaxes_notfixed.append(
    plt.subplot(gs[1, 3], sharex=distanceaxes[0], sharey=distanceaxes[0]))
distanceaxes_notfixed.append(
Example #45
0
                linestyle="--",label="Simulation runs" if j==0 else "")

        # simulations - nearest neighbors
    for j in range(n_neighbors):
        axs[i].plot(h_dense,np.transpose(y_sim_dense)[:,R_nearest_sim_design[j,i]],\
                    linestyle="--",\
                    color=colors[j],label="Nearest Sim {}".format(j+1))

    # true data curve and "real data points"
    axs[i].plot(h_dense, y_field_dense[i, :], 'k', label="Reality")
    axs[i].plot(h_field, y_field[i, ], 'ks', label="Field data")

    axs[i].legend(loc="lower right")

    # imbed sim_designign point subplot
    inset_ax = inset_axes(axs[i],width="30%",height="30%",loc="upper left",\
                          borderpad=2.5)
    inset_ax.set_xlabel("R sim_designign values", fontsize=7, labelpad=1)
    inset_ax.set_ylabel("C sim_designign values", fontsize=7)
    inset_ax.xaxis.set_ticks(R)
    inset_ax.yaxis.set_ticks(np.arange(0, .251, .05))
    inset_ax.tick_params(axis='both', which='major', labelsize=7, pad=-5)
    inset_ax.scatter(R_sim, C_sim, s=15, facecolors='none', edgecolors='grey')
    inset_ax.scatter(R_sim[R_nearest_sim_design[:,i]],C_sim[R_nearest_sim_design[:,i]],s=15,\
                     color=colors)
    inset_ax.axvline(x=R[i], ymin=0, ymax=1, color='k', linewidth=.5)
plt.savefig('data/plotAll.png', dpi=300)
plt.show()

#%% #==================== Write data ===========================#
# write the h-t pairs into files
Example #46
0
          linewidth=1.8,
          color=[0.4660, 0.6740, 0.1880],
          label="Frequenza di risonanza teorica")
 plt.plot([rlc.f_ris_regressione, rlc.f_ris_regressione],
          [min(rlc._amp_teo), max(rlc._amp_teo)],
          '--',
          linewidth=1.8,
          color=[0, 0.4470, 0.7410],
          label="Frequenza di risonanza per regressione")
 plt.grid(which='both')
 primary_ax = plt.gca()
 # Zoom ampiezza (differenzio tra alcuni grafici dalle dimensioni diverse)
 if (idx == 2):
     zoom = inset_axes(primary_ax,
                       loc='lower right',
                       borderpad=3,
                       width="40%",
                       height="45%")
 else:
     zoom = inset_axes(primary_ax,
                       loc='upper left',
                       borderpad=3,
                       width="40%",
                       height="45%")
 plt.sca(zoom)
 rlc.plot_teorica_amp(axislabel=False)
 plt.errorbar(rlc.freq,
              20 * np.log10(rlc.Vout / rlc.Vin),
              rlc.sigma_amp_dB,
              rlc.sigmaFreq,
              '.',
Example #47
0
_ = plt.boxplot(df["normal"], whis="range") # whis tells boxplot what to set whiskers to represent, in this case 'range' means all the way up to max/min.
# Use dummy variables to throw away unwanted return values. Need this so that the output of a million artists is not printed either, at least in the Jupyter notebook.

plt.clf() # Clears the CURRENT figure.
plt.boxplot([df["normal"], df["random"], df["gamma"]], whis="range") # Pass in multiple datasets as list of lists.

# Looking at gamma using histogram
plt.figure() 
plt.hist(df["gamma"], bins=100)

# To get overlay of graphs on top of each other, use import mpl_toolkits.axes_grid1.inset_locator as mpl_il
import mpl_toolkits.axes_grid1.inset_locator as mpl_il

plt.figure()
plt.boxplot([ df["normal"], df["random"], df["gamma"] ]) # If we don't specify whis, only goes out halfway from interquartile range. Can be used to detect outliers (shown as points)
ax2 = mpl_il.inset_axes(plt.gca(), width="60%", height="40%", loc=2) # Put smaller axis within larger one, specify its dimensions, then specify its location.
ax2.hist(df["gamma"], bins=100)
ax2.margins(x=0.5) # Set autoscaling margin so that the xrange covers a larger area
# Not as flexible as gridspec; location of smaller graph limited by where the larger graph displays its data.
ax2.yaxis.tick_right() # Will display ticks on right side of smaller graph.

"""
HEATMAPS: Used to visualize 3-Dimensional data, and takes advantage of spatial proximity.
    -good heatmap e.g. = weather maps (lattitude, longitude, temp/rainfall amounts [use color to indicate intensity])
    - e.g. Australian heatmap of Malaysian Airlines missing flight.
    
* Don't use heatmaps for categorical data. Misleads viewer to look for patterns & ordering thru spatial proximity.

In Matplotlib, heatmaps = 2-D histogram where x & y indicate potential points, and color indicates frequency off observation.
"""
Example #48
0
def plot_context():
    sc = 'mms1'
    mode = 'srvy'
    level = 'l2'
    starttime = dt.datetime(2019, 10, 17)

    # Find SROI
    start_date, end_date = gls_get_sroi(starttime)

    # Grab selections
    abs_files = sdc.sitl_selections('abs_selections',
                                    start_date=start_date,
                                    end_date=end_date)
    sitl_files = sdc.sitl_selections('sitl_selections',
                                     start_date=start_date,
                                     end_date=end_date)
    gls_files = sdc.sitl_selections('gls_selections',
                                    gls_type='mp-dl-unh',
                                    start_date=start_date,
                                    end_date=end_date)

    # Read the files
    abs_data = sdc.read_eva_fom_structure(abs_files[0])
    sitl_data = sdc.read_eva_fom_structure(sitl_files[0])
    gls_data = sdc.read_gls_csv(gls_files)

    # SITL data time series
    t_abs = []
    x_abs = []
    for tstart, tstop, fom in zip(abs_data['tstart'], abs_data['tstop'],
                                  abs_data['fom']):
        t_abs.extend([tstart, tstart, tstop, tstop])
        x_abs.extend([0, fom, fom, 0])

    t_sitl = []
    x_sitl = []
    for tstart, tstop, fom in zip(sitl_data['tstart'], sitl_data['tstop'],
                                  sitl_data['fom']):
        t_sitl.extend([tstart, tstart, tstop, tstop])
        x_sitl.extend([0, fom, fom, 0])

    t_gls = []
    x_gls = []
    for tstart, tstop, fom in zip(gls_data['tstart'], gls_data['tstop'],
                                  gls_data['fom']):
        t_gls.extend([tstart, tstart, tstop, tstop])
        x_gls.extend([0, fom, fom, 0])

    # FGM
    tepoch = epochs.CDFepoch()
    t_vname = 'Epoch'
    b_vname = '_'.join((sc, 'fgm', 'b', 'gse', mode, level))
    api = sdc.MrMMS_SDC_API(sc,
                            'fgm',
                            mode,
                            level,
                            start_date=start_date,
                            end_date=end_date)
    files = api.download_files()
    t_fgm = np.empty(0, dtype='datetime64')
    b_fgm = np.empty((0, 4), dtype='float')
    for file in files:
        cdf = cdfread.CDF(file)
        time = cdf.varget(t_vname)
        t_fgm = np.append(t_fgm, tepoch.to_datetime(time, to_np=True), 0)
        b_fgm = np.append(b_fgm, cdf.varget(b_vname), 0)

    # FPI DIS
    fpi_mode = 'fast'
    api = sdc.MrMMS_SDC_API(sc,
                            'fpi',
                            fpi_mode,
                            level,
                            optdesc='dis-moms',
                            start_date=start_date,
                            end_date=end_date)
    files = api.download_files()
    ti = np.empty(0, dtype='datetime64')
    ni = np.empty(0)
    espec_i = np.empty((0, 32))
    Ei = np.empty((0, 32))
    ti = np.empty(0)
    t_vname = 'Epoch'
    ni_vname = '_'.join((sc, 'dis', 'numberdensity', fpi_mode))
    espec_i_vname = '_'.join((sc, 'dis', 'energyspectr', 'omni', fpi_mode))
    Ei_vname = '_'.join((sc, 'dis', 'energy', fpi_mode))
    for file in files:
        cdf = cdfread.CDF(file)
        #        tepoch = epochs.CDFepoch()
        time = cdf.varget(t_vname)
        ti = np.append(ti, tepoch.to_datetime(time, to_np=True), 0)
        ni = np.append(ni, cdf.varget(ni_vname), 0)
        espec_i = np.append(espec_i, cdf.varget(espec_i_vname), 0)
        Ei = np.append(Ei, cdf.varget(Ei_vname), 0)

    # FPI DES
    fpi_mode = 'fast'
    api.optdesc = 'des-moms'
    files = api.download_files()
    te = np.empty(0, dtype='datetime64')
    ne = np.empty(0)
    espec_e = np.empty((0, 32))
    Ee = np.empty((0, 32))
    te = np.empty(0)
    t_vname = 'Epoch'
    ne_vname = '_'.join((sc, 'des', 'numberdensity', fpi_mode))
    espec_e_vname = '_'.join((sc, 'des', 'energyspectr', 'omni', fpi_mode))
    Ee_vname = '_'.join((sc, 'des', 'energy', fpi_mode))
    for file in files:
        cdf = cdfread.CDF(file)
        #        tepoch = epochs.CDFepoch()
        time = cdf.varget(t_vname)
        te = np.append(te, tepoch.to_datetime(time, to_np=True), 0)
        ne = np.append(ne, cdf.varget(ne_vname), 0)
        espec_e = np.append(espec_e, cdf.varget(espec_e_vname), 0)
        Ee = np.append(Ee, cdf.varget(Ee_vname), 0)
        cdf.close()

    # Create the figure
    fig, axes = plt.subplots(ncols=1, nrows=7, figsize=(8, 9), sharex=True)

    # Inset axes for colorbar
    axins1 = inset_axes(axes[0],
                        width="5%",
                        height="80%",
                        loc='right',
                        bbox_to_anchor=(1.05, 0, 1, 1))
    axins2 = inset_axes(axes[1],
                        width="5%",
                        height="80%",
                        loc='right',
                        bbox_to_anchor=(1.05, 0, 1, 1))

    # FFT parameters -- resolve the oxygen gyrofrequency
    im1 = axes[0].pcolormesh(np.tile(ti, (32, 1)).T,
                             Ei,
                             np.log10(espec_i),
                             cmap='nipy_spectral')
    axes[0].set_xticklabels([])
    axes[0].set_ylabel('ion E\n(eV)')
    axes[0].set_yscale('log')
    cbar1 = fig.colorbar(im1, cax=axins1)
    cbar1.set_label('Flux')
    axes[0].set_title('{} SITL Selections'.format(sc.upper()))

    im2 = axes[1].pcolormesh(np.tile(te, (32, 1)).T,
                             Ee,
                             np.log10(espec_e),
                             cmap='nipy_spectral')
    axes[1].set_xticklabels([])
    axes[1].set_ylabel('elec E\n(ev)')
    axes[1].set_yscale('log')
    cbar2 = fig.colorbar(im2, ax=axins2)
    cbar2.set_label('Flux')

    axes[2].plot(ti, ni, color='blue', label='Ni')
    axes[2].plot(te, ne, color='red', label='Ne')
    axes[2].set_xticklabels([])
    axes[2].set_ylabel('N\n(cm^3)')

    axes[3].plot(t_fgm, b_fgm, label=['Bx', 'By', 'Bz', '|B|'])
    axes[3].set_xticklabels([])
    axes[3].set_ylabel('B\n(nT)')
    #    L_items = axes[3].get_legend().get_texts()
    #    L_items[0].set_text('Bx')
    #    L_items[1].set_text('By')
    #    L_items[2].set_text('Bz')
    #    L_items[3].set_text('|B|')

    axes[4].plot(t_abs, x_abs)
    axes[4].set_xticklabels([])
    axes[4].set_ylabel('ABS')

    axes[5].plot(t_sitl, x_sitl)
    axes[5].set_xticklabels([])
    axes[5].set_ylabel('SITL')

    axes[6].plot(t_gls, x_gls)
    axes[6].set_ylabel('GLS')

    plt.setp(axes[6].xaxis.get_majorticklabels(), rotation=45)

    plt.show()

    pdb.set_trace()

    return
Example #49
0
                  labelpad=0.1,
                  truths=medians)

    for i in range(ndim):
        axe = axes[i, i]
        axe.axvline(medians[i])

        axe.axvline(medians[i] - quants[i][0], linestyle='--')
        axe.axvline(medians[i] + quants[i][1], linestyle='--')

    fig, ax = plt.subplots(figsize=(15, 10))
    t = np.linspace(np.min(time), np.max(time), 1000)
    ax.errorbar(time, flux, yerr=err, fmt='.k', label='Data')
    ax.plot(t,
            transit_model(t, medians[0], medians[1], medians[2]),
            linewidth=3.0,
            label='Median Model')
    ax.set_xlabel("Time from Transit Center (days)")
    ax.set_ylabel("Normalized Flux")
    ax.legend(loc='upper right')

    #inset residual plot

    axin = inset_axes(ax, width="25%", height="15%", loc='lower right')
    axin.hist((flux - transit_model(time, medians[0], medians[1], medians[2])))
    axin.tick_params(labelleft=False, labelbottom=False)
    axin.axvline(0.0, linestyle='--', color='black')
    axin.set_title("Residuals", loc='left')

    plt.show()
def plot_and_save_predictions(hyperp, run_options, file_paths, fig_size):
    ###############################################################################
    #                     Form Fenics Domain and Load Predictions                 #
    ###############################################################################
    #=== Form Fenics Domain ===#
    if run_options.fin_dimensions_2D == 1:
        V, _ = get_space_2D(40)
    if run_options.fin_dimensions_3D == 1:
        V, mesh = get_space_3D(40)

    solver = Fin(V)

    #=== Load Observation Indices, Test and Predicted Parameters and State ===#
    df_obs_indices = pd.read_csv(file_paths.observation_indices_savefilepath +
                                 '.csv')
    obs_indices = df_obs_indices.to_numpy()

    df_parameter_test = pd.read_csv(file_paths.savefile_name_parameter_test +
                                    '.csv')
    parameter_test = df_parameter_test.to_numpy()

    if run_options.forward_mapping == 1:
        df_state_pred = pd.read_csv(file_paths.savefile_name_state_pred +
                                    '.csv')
        state_pred = df_state_pred.to_numpy()

    if run_options.inverse_mapping == 1:
        df_parameter_pred = pd.read_csv(
            file_paths.savefile_name_parameter_pred + '.csv')
        parameter_pred = df_parameter_pred.to_numpy()

###############################################################################
#                     Form Fenics Domain and Load Predictions                 #
###############################################################################
#=== Form Fenics Domain ===#
    if run_options.fin_dimensions_2D == 1:
        V, _ = get_space_2D(40)
    if run_options.fin_dimensions_3D == 1:
        V, mesh = get_space_3D(40)

    solver = Fin(V)

    #=== Load Observation Indices, Test and Predicted Parameters and State ===#
    df_obs_indices = pd.read_csv(file_paths.observation_indices_savefilepath +
                                 '.csv')
    obs_indices = df_obs_indices.to_numpy()

    df_parameter_test = pd.read_csv(file_paths.savefile_name_parameter_test +
                                    '.csv')
    parameter_test = df_parameter_test.to_numpy()

    if run_options.forward_mapping == 1:
        df_state_pred = pd.read_csv(file_paths.savefile_name_state_pred +
                                    '.csv')
        state_pred = df_state_pred.to_numpy()

    if run_options.inverse_mapping == 1:
        df_parameter_pred = pd.read_csv(
            file_paths.savefile_name_parameter_pred + '.csv')
        parameter_pred = df_parameter_pred.to_numpy()

###############################################################################
#                             Plotting Predictions                            #
###############################################################################
#=== Converting Test Parameter Into Dolfin Object and Computed State Observation ===#
    if run_options.data_thermal_fin_nine == 1:
        parameter_test_dl = solver.nine_param_to_function(parameter_test)
        if run_options.fin_dimensions_3D == 1:  # Interpolation messes up sometimes and makes some values equal 0
            parameter_values = parameter_test_dl.vector().get_local()
            zero_indices = np.where(parameter_values == 0)[0]
            for ind in zero_indices:
                parameter_values[ind] = parameter_values[ind - 1]
            parameter_test_dl = convert_array_to_dolfin_function(
                V, parameter_values)
    if run_options.data_thermal_fin_vary == 1:
        parameter_test_dl = convert_array_to_dolfin_function(V, parameter_test)

    state_test_dl, _ = solver.forward(
        parameter_test_dl)  # generate true state for comparison
    state_test = state_test_dl.vector().get_local()
    if hyperp.data_type == 'bnd':
        state_test = state_test[obs_indices].flatten()

    #=== Plotting Test Parameter and Test State ===#
    if run_options.fin_dimensions_2D == 1:
        p_test_fig, ax = plot_2D(parameter_test_dl, 'True Parameter', fig_size)
        divider = make_axes_locatable(ax)
        cax = divider.append_axes("right", size="5%", pad=0.05)
        plt.colorbar(p_test_fig, cax=cax)
    if run_options.fin_dimensions_3D == 1:
        p_test_fig, ax = plot_3D(parameter_test_dl,
                                 'True Parameter',
                                 angle_1=90,
                                 angle_2=270,
                                 fig_size=fig_size)
        caxis = inset_axes(ax, width="5%", height="60%", loc='right')
        plt.colorbar(p_test_fig,
                     cax=caxis,
                     ticks=[0.5, 1.0, 1.5, 2.0, 2.5, 3.0])
    plt.savefig(file_paths.figures_savefile_name_parameter_test,
                dpi=300,
                bbox_inches='tight',
                pad_inches=0)
    print('Figure saved to ' + file_paths.figures_savefile_name_parameter_test)
    plt.show()

    if hyperp.data_type == 'full':  # No state prediction for bnd only data
        if run_options.fin_dimensions_2D == 1:
            s_test_fig, ax = plot_2D(state_test_dl, 'True State', fig_size)
            divider = make_axes_locatable(ax)
            cax = divider.append_axes("right", size="5%", pad=0.05)
            plt.colorbar(s_test_fig, cax=cax)
        if run_options.fin_dimensions_3D == 1:
            s_test_fig, ax = plot_3D(state_test_dl,
                                     'True State',
                                     angle_1=90,
                                     angle_2=270,
                                     fig_size=fig_size)
            caxis = inset_axes(ax, width="5%", height="60%", loc='right')
            plt.colorbar(s_test_fig,
                         cax=caxis,
                         ticks=[0.0, 0.2, 0.4, 0.6, 0.8, 1.0, 1.2,
                                1.4])  # piecewise constant
            #plt.colorbar(s_test_fig, cax=caxis, ticks=[0.0,0.2,0.4,0.6,0.8,1.0]) # spatially varying
        plt.savefig(file_paths.figures_savefile_name_state_test,
                    dpi=300,
                    bbox_inches='tight',
                    pad_inches=0)
        print('Figure saved to ' + file_paths.figures_savefile_name_state_test)
        plt.show()

    #=== Converting Predicted Parameter into Dolfin Object ===#
    if run_options.inverse_mapping == 1:
        if run_options.data_thermal_fin_nine == 1:
            parameter_pred_dl = solver.nine_param_to_function(parameter_pred)
            if run_options.fin_dimensions_3D == 1:  # Interpolation messes up sometimes and makes some values equal 0
                parameter_values = parameter_pred_dl.vector().get_local()
                zero_indices = np.where(parameter_values == 0)[0]
                for ind in zero_indices:
                    parameter_values[ind] = parameter_values[ind - 1]
                parameter_pred_dl = convert_array_to_dolfin_function(
                    V, parameter_values)
        if run_options.data_thermal_fin_vary == 1:
            parameter_pred_dl = convert_array_to_dolfin_function(
                V, parameter_pred)

    #=== Plotting Predicted Parameter and State ===#
    if run_options.inverse_mapping == 1:
        if run_options.fin_dimensions_2D == 1:
            p_pred_fig, ax = plot_2D(parameter_pred_dl,
                                     'Inverse Estimation of True Parameter',
                                     fig_size)
            divider = make_axes_locatable(ax)
            cax = divider.append_axes("right", size="5%", pad=0.05)
            plt.colorbar(p_test_fig, cax=cax)
        if run_options.fin_dimensions_3D == 1:
            p_pred_fig, ax = plot_3D(parameter_pred_dl,
                                     'Inverse Estimation of True Parameter',
                                     angle_1=90,
                                     angle_2=270,
                                     fig_size=fig_size)
            caxis = inset_axes(ax, width="5%", height="60%", loc='right')
            plt.colorbar(p_test_fig,
                         cax=caxis,
                         ticks=[0.5, 1.0, 1.5, 2.0, 2.5, 3.0])
        plt.savefig(file_paths.figures_savefile_name_parameter_pred,
                    dpi=300,
                    bbox_inches='tight',
                    pad_inches=0)
        print('Figure saved to ' +
              file_paths.figures_savefile_name_parameter_pred)
        plt.show()
        parameter_pred_error = np.linalg.norm(parameter_pred - parameter_test,
                                              2) / np.linalg.norm(
                                                  parameter_test, 2)
        print('Parameter prediction relative error: %.7f' %
              parameter_pred_error)

    if run_options.forward_mapping == 1:
        if hyperp.data_type == 'full':  # No visualization of state prediction if the truncation layer only consists of the boundary observations
            state_pred_dl = convert_array_to_dolfin_function(V, state_pred)
            if run_options.fin_dimensions_2D == 1:
                s_pred_fig, ax = plot_2D(state_pred_dl,
                                         'Forward Estimation of True State',
                                         fig_size)
                divider = make_axes_locatable(ax)
                cax = divider.append_axes("right", size="5%", pad=0.05)
                plt.colorbar(s_test_fig, cax=cax)
            if run_options.fin_dimensions_3D == 1:
                s_pred_fig, ax = plot_3D(state_pred_dl,
                                         'Forward Estimation of True State',
                                         angle_1=90,
                                         angle_2=270,
                                         fig_size=fig_size)
                caxis = inset_axes(ax, width="5%", height="60%", loc='right')
                plt.colorbar(s_test_fig,
                             cax=caxis,
                             ticks=[0.0, 0.2, 0.4, 0.6, 0.8, 1.0, 1.2,
                                    1.4])  # piecewise constant
                #plt.colorbar(s_test_fig, cax=caxis, ticks=[0.0,0.2,0.4,0.6,0.8,1.0]) # spatially varying
            plt.savefig(file_paths.figures_savefile_name_state_pred,
                        dpi=300,
                        bbox_inches='tight',
                        pad_inches=0)
            print('Figure saved to ' +
                  file_paths.figures_savefile_name_state_pred)
            plt.show()
        state_pred_error = np.linalg.norm(state_pred - state_test,
                                          2) / np.linalg.norm(state_test, 2)
        print('State observation prediction relative error: %.7f' %
              state_pred_error)

###############################################################################
#                               Plotting Metrics                              #
###############################################################################
    plt.ioff()  # Turn interactive plotting off
    first_trainable_hidden_layer_index = 2
    marker_list = ['+', '*', 'x', 'D', 'o', '.', 'h']

    ############
    #   Loss   #
    ############
    #=== Plot and Save Losses===#
    fig_loss = plt.figure()
    x_axis = np.linspace(1,
                         hyperp.num_epochs - 1,
                         hyperp.num_epochs - 1,
                         endpoint=True)
    for l in range(first_trainable_hidden_layer_index,
                   hyperp.max_hidden_layers):
        #=== Load Metrics and Plot ===#
        print('Loading Metrics for Hidden Layer %d' % (l))
        df_metrics = pd.read_csv(file_paths.NN_savefile_name + "_metrics_hl" +
                                 str(l) + '.csv')
        array_metrics = df_metrics.to_numpy()
        storage_loss_array = array_metrics[2:, 0]
        plt.plot(x_axis,
                 np.log(storage_loss_array),
                 label='hl' + str(l),
                 marker=marker_list[l - 2])

    #=== Figure Properties ===#
    plt.title('Training Log-Loss')
    #plt.title(file_paths.filename)
    plt.xlabel('Epochs')
    plt.ylabel('Log-Loss')
    #plt.axis([0,30,1.5,3])
    plt.legend()

    #=== Saving Figure ===#
    figures_savefile_name = file_paths.figures_savefile_directory + '/' + 'loss' + '_all_layers_' + file_paths.filename + '.png'
    plt.savefig(figures_savefile_name)
    plt.close(fig_loss)

    ################
    #   Accuracy   #
    ################
    fig_accuracy = plt.figure()
    x_axis = np.linspace(1,
                         hyperp.num_epochs - 1,
                         hyperp.num_epochs - 1,
                         endpoint=True)
    for l in range(first_trainable_hidden_layer_index,
                   hyperp.max_hidden_layers):
        #=== Load Metrics and Plot ===#
        print('Loading Metrics for Hidden Layer %d' % (l))
        df_metrics = pd.read_csv(file_paths.NN_savefile_name + "_metrics_hl" +
                                 str(l) + '.csv')
        array_metrics = df_metrics.to_numpy()
        storage_accuracy_array = array_metrics[2:, 1]
        plt.plot(x_axis,
                 storage_accuracy_array,
                 label='hl' + str(l),
                 marker=marker_list[l - 2])

    #=== Figure Properties ===#
    plt.title('Testing Relative Errors')
    #plt.title(file_paths.filename)
    plt.xlabel('Epochs')
    plt.ylabel('Accuracy')
    #plt.axis([0,30,0.9,1])
    plt.legend()

    #=== Saving Figure ===#
    figures_savefile_name = file_paths.figures_savefile_directory + '/' + 'accuracy' + '_all_layers_' + file_paths.filename + '.png'
    plt.savefig(figures_savefile_name)
    plt.close(fig_accuracy)

    ################################
    #   Relative Number of Zeros   #
    ################################
    #=== Load Metrics and Plot ===#
    print('Loading relative number of zeros .csv file')
    try:
        df_rel_zeros = pd.read_csv(file_paths.NN_savefile_name + "_relzeros" +
                                   '.csv')
        rel_zeros_array = df_rel_zeros.to_numpy()
        rel_zeros_array = rel_zeros_array.flatten()
    except:
        print('No relative number of zeros .csv file!')
    rel_zeros_array_exists = 'rel_zeros_array' in locals(
    ) or 'rel_zeros_array' in globals()

    if rel_zeros_array_exists:
        #=== Figure Properties ===#
        fig_accuracy = plt.figure()
        x_axis = np.linspace(2,
                             hyperp.max_hidden_layers - 1,
                             hyperp.max_hidden_layers - 2,
                             endpoint=True)
        plt.plot(x_axis, rel_zeros_array, label='relative # of 0s')
        plt.title('Relative Number of Zeros')
        plt.xlabel('Layer Number')
        plt.ylabel('Relative Number of Zeros')
        plt.legend()

        #=== Saving Figure ===#
        figures_savefile_name = file_paths.figures_savefile_directory + '/' + 'rel_num_zeros_' + file_paths.filename + '.png'
        plt.savefig(figures_savefile_name)
        plt.close(fig_accuracy)
Example #51
0
    sorted_true = [x[0] for x in sorted_data]
    sorted_pred = [float(x[1]) for x in sorted_data]

    error = [sorted_pred[i] - sorted_true[i] for i in range(len(sorted_true))]

    ax.scatter(x=range(len(sorted_pred)),
               y=sorted_pred,
               s=4,
               alpha=0.3,
               color='#1f78b3',
               label='Predicted Cscore data',
               zorder=5)
    ax.plot(sorted_true, color='#fe7f02', label='True Cscore data', zorder=10)
    with plt.style.context('bmh'):
        axins = inset_axes(ax, width='30%', height='30%', loc=2)
        axins.plot([x / 10 for x in range(-50, 51)],
                   [plot_training[i](x / 10) for x in range(-50, 51)],
                   color='red')
        axins.set_xticks([x for x in range(-5, 6)])
        axins.set_yticks([y for y in range(-5, 6)])
        axins.set_xticklabels([])
        axins.set_yticklabels([])
        axins.set_xlim(-5, 5)
        axins.set_ylim(-5, 5)
        axins.axhline(y=0, color='black')
        axins.axvline(x=0, color='black')
    ax.set_xticklabels([])
    ax.set_xlabel('Sorted Validation Data')
    ax.set_ylabel('Scaled Cscore')
Example #52
0
# Grid for plots
skew = SkewT(fig, rotation=45)

# Plot the data using normal plotting functions, in this case using
# log scaling in Y, as dictated by the typical meteorological plot
skew.plot(p, T, 'r')
skew.plot(p, Td, 'g')
skew.plot_barbs(p, u, v)
skew.ax.set_ylim(1000, 100)

# Add the relevant special lines
skew.plot_dry_adiabats()
skew.plot_moist_adiabats()
skew.plot_mixing_lines()

# Good bounds for aspect ratio
skew.ax.set_xlim(-50, 60)

# Create a hodograph
ax_hod = inset_axes(skew.ax, '40%', '40%', loc=1)
h = Hodograph(ax_hod, component_range=80.)
h.add_grid(increment=20)
h.plot_colormapped(u, v, np.hypot(u, v))

# Add metpy logo
add_metpy_logo()

# Show the plot
plt.show()
Example #53
0
def sunbrust(pie_data,
             ax,
             hue=None,
             hue_portion=0.5,
             cmap='viridis',
             colorbar=True,
             colorbar_kws=None,
             inner_radius=0.25,
             outer_radius=1,
             anno_col=None,
             text_anno='text',
             anno_layer_size=0.05,
             col_color_dict=None,
             startangle=0,
             anno_ang_min=5,
             anno_border=1.2,
             text_expend=1.05,
             uniform_section=False,
             order_dict=None):
    """
    Parameters
    ----------
    pie_data
        Tidy dataframe
    ax
    hue
    hue_portion
    cmap
    colorbar
    colorbar_kws
    inner_radius
    outer_radius
    anno_col
    text_anno
    anno_layer_size
    col_color_dict
    startangle
    anno_ang_min
    anno_border
    text_expend
    uniform_section
    order_dict

    Returns
    -------

    """
    return_axes = [ax]
    if order_dict is None:
        order_dict = {}

    # prepare hue colormap
    if hue is not None:
        if isinstance(hue, str):
            hue_data = pie_data.pop(hue)
        elif isinstance(hue, pd.Series):
            hue_data = hue
        else:
            hue_data = pd.Series(hue, index=pie_data.index)
        if not isinstance(cmap, colors.Colormap):
            cmap = plt.get_cmap(cmap)
        cmap.set_bad('gray')

        vmin, vmax = tight_hue_range(hue_data, hue_portion)
        norm = colors.Normalize(vmin=vmin, vmax=vmax, clip=True)
        mapper = cm.ScalarMappable(norm=norm, cmap=cmap)
        col_color_dict = {}
        for col_name, col in pie_data.iteritems():
            reduce_col_data = hue_data.groupby(col).mean()
            col_color_dict[col_name] = {
                k: mapper.to_rgba(v)
                for k, v in reduce_col_data.iteritems()
            }

        # make colorbar
        if colorbar:
            _colorbar_kws = {
                'labelsize': 4,
                'linewidth': 0.5,
                'orientation': 'vertical'
            }
            if colorbar_kws is None:
                colorbar_kws = {}
            _colorbar_kws.update(colorbar_kws)
            bbox_to_anchor = _colorbar_kws.pop('bbox_to_anchor')

            cax = inset_axes(ax,
                             width="3%",
                             height="25%",
                             loc='lower right',
                             borderpad=0,
                             bbox_to_anchor=bbox_to_anchor)
            cax = plot_colorbar(cax,
                                cmap=cmap,
                                cnorm=norm,
                                hue_norm=(vmin, vmax),
                                label=hue_data.name,
                                **_colorbar_kws)
            return_axes.append(cax)

    # prepare data
    if uniform_section:
        dedup_groups = pie_data.reset_index().set_index(
            pie_data.columns.tolist()).index.drop_duplicates()
        dedup_groups = pd.DataFrame(dedup_groups.tolist(),
                                    columns=pie_data.columns)
        pie_data = dedup_groups

    # prepare color
    _col_color_dict = {col: None for col in pie_data.columns}
    if col_color_dict is not None:
        _col_color_dict.update(col_color_dict)

    # prepare plot parameters
    ncols = pie_data.columns.size
    if anno_col is None:
        anno_layer_size = 0
    outer_radius = outer_radius - anno_layer_size
    layer_size = (outer_radius - inner_radius) / ncols

    # plot multiple donuts
    previous_order = pd.Series([])
    anno_wedges = []
    anno_names = []
    for col, col_name in enumerate(pie_data.columns):
        cur_radius = inner_radius + (col + 1) * layer_size
        col_pie_data = pie_data[col_name].value_counts()

        # manage order
        if col_name in order_dict:
            _ordered_data = col_pie_data.reindex(pd.Index(
                order_dict[col_name]))
            previous_order = _ordered_data
        else:
            if col == 0:
                _ordered_data = col_pie_data
                previous_order = _ordered_data
            else:
                records = []
                for section in previous_order.index:
                    section_subs = pie_data[pie_data.iloc[:, col - 1] ==
                                            section][col_name].unique()
                    records.append(
                        col_pie_data.reindex(
                            pd.Index(section_subs)).sort_values(
                                ascending=False))
                _ordered_data = pd.concat(records)
                previous_order = _ordered_data

        # plot the real pie charts
        pie_color = _col_color_dict[col_name]
        if isinstance(pie_color, dict):
            pie_color = [pie_color[i] for i in _ordered_data.index]
        ax.pie(_ordered_data,
               radius=cur_radius,
               colors=pie_color,
               startangle=startangle,
               wedgeprops=dict(width=layer_size, edgecolor='w'))

        # plot an additional thin layer to anchor anno label
        if anno_col == col:
            wedges, texts = ax.pie(_ordered_data,
                                   radius=outer_radius + anno_layer_size,
                                   colors=pie_color,
                                   startangle=startangle,
                                   wedgeprops=dict(width=anno_layer_size,
                                                   edgecolor='w'))
            if text_anno:
                anno_wedges = wedges
                anno_names = _ordered_data.index.tolist()

    # annotate wedges
    for i, p in enumerate(anno_wedges):
        delta_ang = p.theta2 - p.theta1
        if delta_ang < anno_ang_min:
            continue
        ang = (p.theta2 - p.theta1) / 2. + p.theta1
        y = np.sin(np.deg2rad(ang))
        x = np.cos(np.deg2rad(ang))

        if text_anno == 'anno_box':
            # wedges annotation
            bbox_props = dict(boxstyle="round,pad=0.2",
                              fc="#FFFFFF88",
                              ec="#00000022",
                              lw=0.72)
            kw = dict(xycoords='data',
                      textcoords='data',
                      arrowprops=dict(arrowstyle="-", color='#00000055'),
                      bbox=bbox_props,
                      zorder=0,
                      va="center")
            # separate all y
            y_niche = np.arange(-anno_border, anno_border, anno_border / 10)
            allow_y_niche = OrderedDict(enumerate(y_niche))

            horizontalalignment = {-1: "right", 1: "left"}[int(np.sign(x))]
            connectionstyle = f"angle,angleA=0,angleB={ang},rad=5"
            kw["arrowprops"].update({"connectionstyle": connectionstyle})

            suitable_niche = np.abs(
                np.array(list(allow_y_niche.values())) -
                anno_border * y).argmin()
            suitable_niche = list(allow_y_niche.keys())[suitable_niche]
            y_niche = allow_y_niche.pop(suitable_niche)
            ax.annotate(anno_names[i],
                        xy=(x, y),
                        xytext=(anno_border * np.sign(x), y_niche),
                        horizontalalignment=horizontalalignment,
                        **kw)
        elif text_anno == 'text':
            ha = 'left'
            if x < 0:
                # left side label
                ang += 180
                ha = 'right'
            if ang > 180:
                # so label will not be up-side-down
                ang = ang - 360
            ax.text(x * text_expend,
                    y * text_expend,
                    anno_names[i],
                    fontdict=None,
                    withdash=False,
                    rotation=ang,
                    va='center',
                    ha=ha,
                    rotation_mode='anchor')
        elif text_anno is None:
            pass
        else:
            raise ValueError(
                f'text_anno can only be "text", "anno_box" or None, got {text_anno}'
            )

    if len(return_axes) == 1:
        return ax
    else:
        return tuple(return_axes)
Example #54
0
marker = ['o', 's', '^', 'v', '>', '<']

for i, case in enumerate(cases):
    ax[i].set_xscale('log')
    ax[i].set_yscale('log')
    ax[i].set_ylabel(f'$L^1$ Error (n={n[i]})')
    for j, (method, title) in enumerate(methods.items()):
        ax[i].plot(case['dt'], case[method], label=title, marker=marker[j])

ax[N - 1].legend()
ax[N - 1].set_xlabel('$\\gamma h$ (friction constant $\\times$ step size)')

# Plot histograms as inset:
inset = inset_axes(ax[0],
                   width="100%",
                   height="100%",
                   bbox_to_anchor=(.2, .5, .5, .5),
                   bbox_transform=ax[0].transAxes)

step_sizes = [1000, 10000]
histograms = [
    pd.read_csv(f'stationary/stationary_2_{dt}.hist') for dt in step_sizes
]
vlim = math.sqrt(2)
colors = ['blue', 'orange']
for H, dt, color in zip(histograms, step_sizes, colors):
    # inset.bar(H['v'], H[' rho(v)'], width=math.sqrt(2)/len(H.index), label=f'$\\gamma h$ = {dt/10000}')
    x = H['v'].values.copy()
    y = H[' rho(v)'].values.copy()
    inset.plot(x, y, label=f'$\\gamma h$ = {dt/10000}', color=color)
    inset.plot([x[0], x[0], np.nan, x[-1], x[-1]], [0, y[0], np.nan, y[-1], 0],