Esempio n. 1
0
def plot_obs(true_state, obs, size, name='Name_left_empty', save=False):
    fig = plt.figure(figsize=(size[0], size[1]))
    font = FontProperties()
    font.set_family('serif')
    font.set_style('italic')
    ax = plt.subplot(111)
    ax.plot(*true_state.get_rv_plotting(obs), color="blue")
    plt.errorbar(obs.t, obs.rv, yerr=obs.err, fmt='.r')
    ax.set_xticklabels([])
    ax.set_ylabel("$Initial RV$", fontsize=28)
    ax.tick_params(axis='both', labelsize=18)
    plt.grid()
    frame2 = fig.add_axes([0.125, -0.17, 0.775, 0.22])
    plt.tick_params(axis='both', labelsize=18)
    frame2.set_ylabel("$Res. RV$", fontsize=28)
    frame2.set_xlabel("$Time$", fontsize=28)
    plt.errorbar(obs.t,
                 true_state.get_rv(obs.t) - obs.rv,
                 yerr=obs.err,
                 fmt='.r')
    frame2.locator_params(nbins=3, axis='y')
    plt.grid()
    if (save):
        plt.savefig('mcmcplots/{n}.png'.format(n=name), bbox_inches='tight')
        plt.close('all')
Esempio n. 2
0
def comentionfigure(request):
    term_count = {}
    for i in Article_content.objects.all():
        words = Article_content.key_word(i)
        for word in words:
            if word not in term_count:
                term_count[word] = 1
            else:
                term_count[word] = term_count[word] + 1
    data = pd.DataFrame.from_dict(term_count, orient='index')
    data = data.reset_index()
    data.columns = ['Terms', 'Count']
    terms = data.sort_values(by=['Count'], ascending=False).head(20)
    terms = terms[2:]
    terms1 = terms.sort_index()
    qs = Article_content.objects.all()
    df = read_frame(qs)
    text = " ".join(content for content in df.content)
    stopwords1 = set(STOPWORDS)
    qs1 = Article.objects.all()
    df1 = read_frame(qs1)
    df1['date'] = df1['date_of_publish'].apply(
        lambda x: pd.to_datetime(str(x), format='%Y-%m-%d'))
    df1['YM'] = df1['date'].apply(lambda x: str(x.year) + '-' + str(x.month))
    c = list()
    for d in df1.YM.unique():
        count = len(df1[df1.YM == d])
        c.append(count)
    result = pd.DataFrame(list(zip(df1.YM.unique(), c)),
                          columns=['Publish_Time', 'Num'])
    result['date'] = result['Publish_Time'].apply(
        lambda x: pd.to_datetime(str(x), format='%Y-%m'))
    result = result.sort_values(by='date')
    ind = np.arange(len(df1.YM.unique()))
    # Generate a word cloud image
    wordcloud = WordCloud(stopwords=stopwords1,
                          background_color="white",
                          colormap='viridis').generate(text)
    font = FontProperties()
    font.set_family('serif')
    font.set_name('Arial Rounded MT')
    font.set_style('italic')
    plt.figure(figsize=(100, 120), facecolor='white')
    fig, ax = plt.subplots(2, 1)
    ax[1].imshow(wordcloud, interpolation='bilinear')
    ax[1].axis('off')
    ax[0].plot(ind, result.Num)
    ax[0].set_xticks([1, 5, 10])
    ticks = list(result.Publish_Time)
    t = (ticks[1], ticks[5], ticks[10])
    ax[0].set_xticklabels(t)
    buf = io.BytesIO()
    canvas = FigureCanvasAgg(fig)
    canvas.print_png(buf)
    response = HttpResponse(buf.getvalue(), content_type='image/png')
    # if required clear the figure for reuse
    fig.clear()
    # I recommend to add Content-Length for Django
    response['Content-Length'] = str(len(response.content))
    return response
Esempio n. 3
0
def plot_trimmed_results(bundle, Ntrails, size, name='', save=False):
    Niter, mcmc, chain, chainlogp, true_state, obs, is_emcee, Nwalkers = bundle.mcmc_Niter, bundle.mcmc, bundle.mcmc_chain, bundle.mcmc_chainlogp, bundle.mcmc_initial_state, bundle.mcmc_obs, bundle.mcmc_is_emcee, bundle.mcmc_Nwalkers
    trimmedchain = bundle.mcmc_trimmedchain
    list_of_states = []
    for i in range(len(trimmedchain)):
        s = mcmc.state.deepcopy()
        s.set_params(chain[i])
        list_of_states.append(s)

    fig = plt.figure(figsize=(size[0], size[1]))
    font = FontProperties()
    font.set_family('serif')
    font.set_style('italic')
    ax = plt.subplot(111)
    selected = np.sort(np.random.choice(len(list_of_states), Ntrails))
    for j in range(len(selected)):
        a = list_of_states[selected[j]]
        ax.plot(*a.get_rv_plotting(obs), alpha=0.28, color="darkolivegreen")

    print "Selected some {nt} samples to plot.".format(nt=Ntrails)

    averageRandomState = mcmc.state.deepcopy()
    averageRandomChain = np.average(chain, axis=0)
    averageRandomState.set_params(averageRandomChain)
    ax.plot(*true_state.get_rv_plotting(obs), color="purple")
    plt.errorbar(obs.t, obs.rv, yerr=obs.err, fmt='.r')
    ax.set_xticklabels([])
    plt.grid()
    ax2 = fig.add_axes([0.125, -0.63, 0.775, 0.7])
    ax.set_ylabel("Initial RV", fontproperties=font, fontsize=26)
    ax2.set_ylabel("Average Result RV", fontproperties=font, fontsize=26)
    ax.yaxis.label.set_size(26)
    ax2.yaxis.label.set_size(26)
    ax.tick_params(axis='both', labelsize=18)
    ax2.tick_params(axis='both', labelsize=18)
    plt.plot(*averageRandomState.get_rv_plotting(obs),
             alpha=0.99,
             color="black")
    print "Resulting average params state (randomly sampledriver.ind):"
    print averageRandomState.get_keys()
    print averageRandomState.get_params()
    plt.errorbar(obs.t, obs.rv, yerr=obs.err, fmt='.r')
    ax2.set_xticklabels([])
    plt.grid()
    ax3 = fig.add_axes([0.125, -0.9, 0.775, 0.23])
    ax3.tick_params(axis='both', labelsize=18)
    ax3.yaxis.label.set_size(26)
    ax3.set_ylabel("Res. RV", fontproperties=font, fontsize=26)
    ax3.locator_params(nbins=3, axis='y')
    ax3.xaxis.label.set_size(26)
    ax3.set_xlabel("Time", fontproperties=font, fontsize=26)
    plt.errorbar(obs.t,
                 averageRandomState.get_rv(obs.t) - obs.rv,
                 yerr=obs.err,
                 fmt='.r')
    plt.grid()
    if (save):
        plt.savefig('mcmcplots/{n}.png'.format(n=name), bbox_inches='tight')
    plt.close('all')
    return fig
Esempio n. 4
0
def plotLinearData(time, FeatureMatrix, OSignal, FeatureNames):
    """

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

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

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

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

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

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

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

    axes[MatrixSize[1] - 1].set_xlabel(" Time (s) ", fontproperties=font1)
    axes[MatrixSize[1] - 1].axes.get_xaxis().set_visible(True)
Esempio n. 5
0
def get_text_dimensions(text, **kwargs):
    # class SIZE(ctypes.Structure):
    #     _fields_ = [("cx", ctypes.c_long), ("cy", ctypes.c_long)]

    # hdc = ctypes.windll.user32.GetDC(0)
    # hfont = ctypes.windll.gdi32.CreateFontW(-points, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, font)
    # hfont_old = ctypes.windll.gdi32.SelectObject(hdc, hfont)
    # size = SIZE(0, 0)
    # ctypes.windll.gdi32.GetTextExtentPoint32W(hdc, text, len(text), ctypes.byref(size))
    # ctypes.windll.gdi32.SelectObject(hdc, hfont_old)
    # ctypes.windll.gdi32.DeleteObject(hfont)

    # return (size.cx, size.cy)

    try:
        ImageFont
    except:
        print('get_text_dimensions requires pillow which was not found.  Please '
              'run pip install pillow and try again.')
        return False

    font = FontProperties()
    font.set_family(kwargs['font'])
    font.set_style(kwargs['font_style'])
    font.set_weight(kwargs['font_weight'])
    fontfile = findfont(font, fallback_to_default=True)

    size = ImageFont.truetype(fontfile , kwargs['font_size']).getsize(text)

    return size[0]*1.125, size[1]*1.125  # no idea why it is off
Esempio n. 6
0
def format_plot(axes, fontsize=16, xformat="%.0f", yformat="%.0f", xlim=None, ylim=None, xlabel='', ylabel=''):
    '''format 2d-plot black and with with times font
    '''
    #-------------------------------------------------------------------
    # configure the style of the font to be used for labels and ticks
    #-------------------------------------------------------------------
    #
    from matplotlib.font_manager import FontProperties
    font = FontProperties()
#    font.set_name('Script MT')
#    font.set_name('Times')
    font.set_family('serif')
#    font.set_family('sans-serif')
    font.set_style('normal')
#    font.set_size('small')
#    font.set_size('large')
#    font.set_size('xx-large')
    font.set_size(fontsize)
#    font.set_variant('small-caps')
#    font.set_weight('ultralight')

    if xlim != None and ylim != None:
        axes.axis([0, xlim, 0., ylim], fontproperties=font)

    # format ticks for plot
    #
    locs, labels = axes.xticks()
    axes.xticks(locs, map(lambda x: xformat % x, locs), fontproperties=font)
    axes.xlabel(xlabel, fontproperties=font)

    locs, labels = axes.yticks()
    axes.yticks(locs, map(lambda x: yformat % x, locs), fontproperties=font)
    axes.ylabel(ylabel, fontproperties=font)
Esempio n. 7
0
def format_plot(axes, xlim=None, ylim=None, xlabel='', ylabel=''):
    '''format 2d-plot black and with with times legends 
    '''
    #-------------------------------------------------------------------
    # configure the style of the font to be used for labels and ticks
    #-------------------------------------------------------------------
    #
    from matplotlib.font_manager import FontProperties
    font = FontProperties()
    font.set_name('Script MT')
    font.set_family('serif')
    font.set_style('normal')
#    font.set_size('small')
    font.set_size('large')
    font.set_variant('normal')
    font.set_weight('medium')
    
    if xlim != None and ylim != None:
        axes.axis([0, xlim, 0., ylim], fontproperties=font)

    # format ticks for plot
    #
    locs, labels = axes.xticks()
    axes.xticks(locs, map(lambda x: "%.0f" % x, locs), fontproperties=font)
    axes.xlabel(xlabel, fontproperties=font)

    locs, labels = axes.yticks()
    axes.yticks(locs, map(lambda x: "%.0f" % x, locs), fontproperties=font)
    axes.ylabel(ylabel, fontproperties=font)
Esempio n. 8
0
    def plot_triangle(self):
        
        font_ = FontProperties()
        font_.set_family('sans-serif')
        font_.set_weight('normal')
        font_.set_style('italic')
        self.fig = figure()
        alpha = 0.8
        alphal = 0.5
        third_range = np.linspace(-0.0277, 0.21, 10000)
        second_upper = 2*third_range + 2.0/9.0
        plot(third_range, second_upper, color='k', alpha=alphal)
        
        second_right = 1.5*(abs(third_range)*4.0/3.0)**(2.0/3.0)
        plot(third_range, second_right, color='k', alpha=alphal)
        connectionstyle="arc3,rad=.1"
        lw = 0.5
        plot(np.array([0.0, 0.0]), np.array([0.0, 2.0/9.0]), color='k', alpha=alphal)
        gca().annotate(r'Isotropic limit', xy=np.array([0, 0]), xytext=np.array([0.05, 0.02]), fontproperties=font_, rotation=0, alpha=alpha, arrowprops=dict(arrowstyle="->", connectionstyle=connectionstyle, lw=lw))
        gca().annotate(r'Plane strain', xy=np.array([0, 1.0/9.0/2]), xytext=np.array([0.07, 0.07]), fontproperties=font_, rotation=0, alpha=alpha, arrowprops=dict(arrowstyle="->", connectionstyle=connectionstyle, lw=lw))
        gca().annotate(r'One component limit', xy=np.array([third_range[-1], second_upper[-1]]), xytext=np.array([0.00, 0.6]), fontproperties=font_, rotation=0, alpha=alpha, arrowprops=dict(arrowstyle="->", connectionstyle=connectionstyle, lw=lw))
        gca().annotate(r'Axisymmetric contraction', xy=np.array([third_range[1000/2], second_right[1000/2]]), xytext=np.array([0.09, 0.12]), fontproperties=font_, rotation=0, alpha=alpha, arrowprops=dict(arrowstyle="->", connectionstyle=connectionstyle, lw=lw))
        gca().annotate(r'Two component axisymmetric', xy=np.array([third_range[0], second_right[0]]), xytext=np.array([0.11, 0.17]), fontproperties=font_, rotation=0, alpha=alpha, arrowprops=dict(arrowstyle="->", connectionstyle=connectionstyle, lw=lw))
        gca().annotate(r'Two component plane strain', xy=np.array([0, 2.0/9.0]), xytext=np.array([0.13, 0.22]), fontproperties=font_, rotation=0, alpha=alpha, arrowprops=dict(arrowstyle="->", connectionstyle=connectionstyle, lw=lw))
        gca().annotate(r'Axisymmetric expansion', xy=np.array([third_range[4000], second_right[4000]]), xytext=np.array([0.15, 0.27]), fontproperties=font_, rotation=0, alpha=alpha, arrowprops=dict(arrowstyle="->", connectionstyle=connectionstyle, lw=lw))
        gca().annotate(r'Two component', xy=np.array([third_range[6000], second_upper[6000]]), xytext=np.array([0.05, 0.5]), fontproperties=font_, rotation=0, alpha=alpha, arrowprops=dict(arrowstyle="->", connectionstyle=connectionstyle, lw=lw))


        self.ax = gca()
        xlim(-0.05, 0.3)
        ylim(0.0, 0.7)
        grid(False)
        gca().axis('off')
        gcf().patch.set_visible(False)
        tight_layout()
Esempio n. 9
0
def plot_chains(bundle, size, name='Name_left_empty', save=False):
    fig = plt.figure(figsize=(size[0], size[1]))
    font = FontProperties()
    font.set_family('serif')
    font.set_style('italic')
    mcmc, chain, chainlogp = bundle.mcmc, bundle.mcmc_chain, bundle.mcmc_chainlogp
    for i in range(mcmc.state.Nvars):
        ax = plt.subplot(mcmc.state.Nvars + 1, 1, 1 + i)
        #ax.set_ylabel(mcmc.state.get_keys()[i])
        ax.tick_params(axis='x', labelbottom='off')
        ax.yaxis.label.set_size(28)
        ax.tick_params(axis='both', labelsize=18)
        ax.locator_params(axis='y', nbins=3)
        ax.plot(chain[:, i])
    ax = plt.subplot(mcmc.state.Nvars + 1, 1, mcmc.state.Nvars + 1)
    ax.set_ylabel("$\log \, p$")
    ax.set_xlabel("$Iterations$")
    ax.yaxis.label.set_size(28)
    ax.xaxis.label.set_size(28)
    ax.tick_params(axis='both', labelsize=18)
    ax.locator_params(axis='y', nbins=3)
    ax.plot(chainlogp)
    if (save):
        plt.savefig('mcmcplots/{n}.png'.format(n=name), bbox_inches='tight')
        plt.close('all')
Esempio n. 10
0
def plot_hex(par_dict, mjd, res, size, colorbar=True, vmin=None, vmax=None):
    my_width = 6
    mar_size = my_width * 0.33
    lab_size = my_width * 1.7
    tick_size = my_width * 0.66
    font_size = my_width * 2.0

    font2 = FontProperties()
    font2.set_size('%d' % font_size)
    font2.set_family('sans')
    font2.set_style('normal')
    font2.set_weight('bold')
    plt.tick_params('x', colors='k', size=tick_size)
    plt.tick_params('y', colors='k', size=tick_size)
    plt.rc('xtick', labelsize=lab_size)
    plt.rc('ytick', labelsize=lab_size)

    pb_i = par_dict['pb_i']
    pb_o = par_dict['pb_o']
    plt.set_cmap('coolwarm')
    im = plt.hexbin((mjd / pb_i) % 1,
                    mjd,
                    res,
                    size,
                    linewidths=0.1,
                    vmin=vmin,
                    vmax=vmax)
    plt.xlabel("inner phase", fontproperties=font2)
    plt.ylabel("MJD", fontproperties=font2)
    if colorbar:
        cb = plt.colorbar(im)
        cb.set_label('ns', fontproperties=font2)
    plt.gcf().set_size_inches(my_width * 0.77, my_width)
    return
Esempio n. 11
0
 def _check_font_properties(self, font0, weight='normal'):
     ''' Check if the given font properties are valid. '''
     #
     font = self._get_dict(font0)
     #
     fontp = FontProperties()
     #      6 parameters in a font properties dictionary
     vkey = ['family', 'style', 'variant', 'stretch', 'weight', 'size']
     for k in font:
         if k not in vkey:
             return fontp
         #
         if k == 'style':
             if not font[k] in self.fstyle:
                 font[k] = 'normal'
         else:
             font['style'] = 'normal'
         if k == 'variant':
             if not font[k] in self.fvariant:
                 font[k] = 'normal'
         else:
             font['variant'] = 'normal'
         if k == 'stretch':
             if not isfloat(font[k]):
                 if font[k] not in self.fstretch:
                     font[k] = 'normal'
             else:
                 if not (0. < float(font[k]) < 1000.):
                     font[k] = 'normal'
         else:
             font['stretch'] = 'normal'
         if k == 'weight':
             if not isfloat(font[k]):
                 if font[k] not in self.fweight:
                     font[k] = weight
             else:
                 if not (0. < float(font[k]) < 1000.):
                     font[k] = weight
         else:
             font['weight'] = weight
         if k == 'size':
             if not isfloat(font[k]):
                 if font[k] not in self.fsize:
                     font[k] = 12.
             else:
                 if not (0. < float(font[k]) < 100.):
                     font[k] = 12.
         else:
             font['size'] = 12.
     #
     fontp.set_family(font['family'])
     fontp.set_size(font['size'])
     fontp.set_weight(font['weight'])
     fontp.set_variant(font['variant'])
     fontp.set_stretch(font['stretch'])
     fontp.set_style(font['style'])
     #
     return fontp
Esempio n. 12
0
 def get_prop(self, style=None, weight=None, **args):
     prop = FontProperties()
     prop.set_family('sans-serif')
     prop.set_size(10)
     if style:
         prop.set_style(style)
     if weight:
         prop.set_weight(weight)
     return prop
Esempio n. 13
0
def drawGraphbyDesign(number, design):
    elements = design.split(' ')
    federates = set([int(e[0]) for e in elements])
    federates_location_dict = defaultdict(list)
    federates_type_dict = defaultdict(list)
    federate_coordinates_dict = defaultdict(list)
    my_dpi = 150
    plt.figure(figsize=(800/my_dpi, 800/my_dpi), dpi=my_dpi)
    for r in [4, 2.25, 1.]:
        x = np.linspace(-1.0*r, 1.0*r, 50)
        y = np.linspace(-1.0*r, 1.0*r, 50)
        X, Y = np.meshgrid(x, y)
        F = X ** 2 + Y ** 2 - r
        plt.contour(X, Y, F, [0], colors='k', linewidths = 0.3, origin = 'lower', zorder = -1)

    font = FontProperties()
    font.set_style('italic')
    font.set_weight('bold')
    font.set_size('x-small')
    for x,y,lab in [(0,0,'SUR'), (0, 1, "LEO"),(0, 1.5, 'MEO'),(0, 2, 'GEO')]:
        # plt.annotate(lab, xy = (x,y), xytext = (x-0.2, y-0.1))
        plt.text(x,y, ha="center", va="center", s = lab, bbox = dict(fc="w", ec="w", lw=2),fontproperties=font)

    for i, (x, y) in enumerate([convertLocation2xy(e) for e in ['OOO'+str(i) for i in range(1,7)]]):
        plt.text(x, y, ha="center", va="center", s=str(i+1), bbox=dict(fc="none", ec="none", lw=2), fontproperties=font)

    font.set_size('medium')
    plt.text(0, 2.3 , ha="left", va="center", s=r'$|\rightarrow \theta$', bbox=dict(fc="w", ec="w", lw=2), fontproperties=font)

    types_dict = {'GroundSta': "G", 'Sat': 'S'}
    colordict = {'F1': 'yellow', 'F2': 'lightcyan', 'F3': 'lightgrey'}
    allpossiblelocations = []
    for location in ['SUR', 'LEO', 'MEO', 'GEO']:
        for i in range(1,7):
            allpossiblelocations.append(location + str(i))

    allpossiblecoordinates = [convertLocation2xy(e) for e in allpossiblelocations]
    plt.scatter(*zip(*allpossiblecoordinates), marker = "H", s = 800, color = 'k', facecolors = 'w')
    for f in federates:
        types = [re.search(r'\d\.(.+)@(\w+\d)', e).group(1) for e in elements if '%d.' % f in e]
        federates_type_dict['F%d'%f] = [types_dict[t] for t in types]
        federates_location_dict['F%d'%f] = [re.search(r'(.+)@(\w+\d)', e).group(2) for e in elements if '%d.'%f in e]
        federate_coordinates_dict['F%d'%f] = [convertLocation2xy(loc) for loc in federates_location_dict['F%d'%f]]
        plt.scatter(*zip(*federate_coordinates_dict['F%d'%f]), marker = "H", s = 800, edgecolors = 'k', facecolors = colordict['F%d'%f], linewidth='3')
        for x, y in federate_coordinates_dict['F%d'%f]:
            plt.annotate('F%d'%f, xy = (x, y), xytext = (x-0.1, y-0.075))


    plt.xticks([])
    plt.yticks([])
    rlim = 2.5
    plt.xlim(-rlim, rlim)
    plt.ylim(-rlim+0.2, rlim)
    plt.axis('off')
    des_roman_dict = {1: 'I', 2: 'II', 3:'III', 4:'IV', 5:'V'}
    plt.savefig("Design_%s.pdf"%des_roman_dict[number], bbox_inches='tight')
Esempio n. 14
0
def labelPanels(axl, axlist=None, font='Arial', fontsize=18, weight='normal', xy=(-0.05, 1.05)):
    """
    Provide labeling of panels in a figure with multiple subplots (axes)
    
    Parameters
    ----------
    axl : list of axes objects
        If a single axis object is present, it will be converted to a list here.
    
    axlist : list of string labels (default : None)
        Contains a list of the string labels. If the default value is provided,
        the axes will be lettered in alphabetical sequence. 
    
    font : string (default : 'Arial')
        Name of a valid font to use for the panel labels
    
    fontsize : float (default : 18, in points)
        Font size to use for axis labeling
    
    weight : string (default : 'normal')
        Font weight to use for labels. 'Bold', 'Italic', and 'Normal' are options
    
    xy : tuple (default : (-0.05, 1.05))
        A tuple (x,y) indicating where the label should go relative to the axis frame.
        Values are normalized as a fraction of the frame size.
    
    Returns
    -------
        Nothing

    """
    if type(axl) is dict:
        axt = [axl[x] for x in axl]
        axlist = axl.keys()
        axl = axt
    if type(axl) is not list:
        axl = [axl]
    if axlist is None:
        axlist = string.uppercase[0:len(axl)]
        # assume we wish to go in sequence
        assert len(axlist) == len(axl)
    font = FontProperties()
    font.set_family('sans-serif')
    font.set_weight=weight
    font.set_size=fontsize
    font.set_style('normal')
    for i, ax in enumerate(axl):
        if ax is None:
            continue
        ax.annotate(axlist[i], xy=xy, xycoords='axes fraction',
                annotation_clip=False,
                color="k", verticalalignment='bottom',weight=weight, horizontalalignment='right',
                fontsize=fontsize, family='sans-serif',
                )
Esempio n. 15
0
def addtext(ax, text = None, xloc = 1, yloc = -1.5, color = '#dd1c77', style =
'italic', weight = 'light', rotation = 10):
    font0 = FontProperties()
    font0.set_style(style)
    font0.set_weight(weight)
    if text == None:
        text = 'Happy 65 anniversary my beloved China  =^^=\n\
            Continue to give priority to development,\n\
            adhere to reform and innovation and \n\
            stay committed to the path of peaceful development\n\
                                                                       Love,R'
    ax.text(xloc, yloc, text , color = color, fontproperties=font0, rotation=rotation)
Esempio n. 16
0
def plot_pie(df, title, filename, size=(6, 6)):
	font = FontProperties()
	font.set_weight('bold')
	df.sort_values().plot.pie(autopct='%.2f', figsize=size, title=title)
	count = df.sum()
	
	font = FontProperties()
	font.set_style('italic')
	font.set_weight('light')
	font.set_size('medium')
	plt.annotate('Total Count: {}'.format(count), xy=(0.01, 0.96), xycoords='axes fraction', fontproperties=font)
	
	plt.xlabel('')
	plt.ylabel('')

	pplot(filename)
Esempio n. 17
0
def font_properties_from_style(style: dict) -> FontProperties:
    """ convert a style to a FontProperties object """
    fp = FontProperties()
    for key, value in style.items():
        if key == "font-family":
            fp.set_family(value)
        if key == "font-size":
            fp.set_size(svgUnitToMpl(value))
        if key == "font-weight":
            fp.set_weight(value)
        if key == "font-style":
            fp.set_style(value)
        if key == "font-variant":
            fp.set_variant(value)
        if key == "font-stretch":
            fp.set_stretch(value)
    return fp
Esempio n. 18
0
def font_properties_from_style(style):
    from matplotlib.font_manager import FontProperties
    fp = FontProperties()
    for key, value in style.items():
        if key == "font-family":
            fp.set_family(value)
        if key == "font-size":
            fp.set_size(svgUnitToMpl(value))
        if key == "font-weight":
            fp.set_weight(value)
        if key == "font-style":
            fp.set_style(value)
        if key == "font-variant":
            fp.set_variant(value)
        if key == "font-stretch":
            fp.set_stretch(value)
    return fp
Esempio n. 19
0
def plot_grid_numbers(rows_outL,
                      header='',
                      x_axis_label='',
                      do_show=True,
                      fmt='%g'):

    if not got_matplotlob:
        banner(
            'ERROR: could not import matplotlib\n"plot_grid_numbers" FAILED.')
        return

    Nrows = len(rows_outL)
    Ncols = max([len(row) for row in rows_outL])

    fig, axs = plt.subplots()
    plt.axes()

    font = FontProperties()
    font.set_size('large')
    font.set_family('fantasy')
    font.set_style('normal')

    for i in range(Nrows):
        rowL = rows_outL[i]
        x = Nrows - i - 1
        for j in range(Ncols):
            if j < len(rowL):
                s = rowL[j]
            else:
                s = '*'
            #      Rectangle(  (x,y),    width,   height)
            rect = Rectangle((j, x),
                             0.9,
                             0.9,
                             fc='r',
                             alpha=0.5,
                             edgecolor='black')
            plt.gca().add_patch(rect)

            t = plt.text(j + .45, x + .45, s, fontproperties=font, **alignment)

    plt.xlim(0, Ncols)
    plt.ylim(0, Nrows)

    plt.show()
Esempio n. 20
0
    def plot_triangle(self):
        font_ = FontProperties()
        font_.set_family('sans-serif')
        font_.set_weight('normal')
        font_.set_style('italic')
        alpha = 0.8
        self.fig = figure()
        
        alphal = 0.5
        plot((self.x1[0], self.x2[0]), (self.x1[1], self.x2[1]), color='k', alpha=alphal)
        plot((self.x2[0], self.x3[0]), (self.x2[1], self.x3[1]), color='k', alpha=alphal)
        plot((self.x3[0], self.x1[0]), (self.x3[1], self.x1[1]), color='k', alpha=alphal)
        plot((self.x3[0], self.x4[0]), (self.x3[1], self.x4[1]), color='k', alpha=alphal)
        self.ax = gca()
        xlim(-0.2, 1.2)
        ylim(-0.2, 1.1)
        gca().annotate(r'One component', xy=self.x1, xytext=(0.85, -0.05), 
                       fontproperties=font_, alpha=alpha)
        gca().annotate(r'Two component', xy=self.x2, xytext=(-0.15, -0.05), 
                       fontproperties=font_, alpha=alpha)
        gca().annotate(r'Three component', xy=self.x3, xytext=(0.35, 0.90), 
                       fontproperties=font_, alpha=alpha)
        m = (self.x3[1] - self.x4[1])/(self.x3[0] - self.x4[0])
        y = 0.1
        x = self.x4[0] + (1.0/m)*y
        gca().annotate(r'Plane strain', xy=np.array([x, y]), xytext=(0.5, -0.1), 
                       fontproperties=font_,arrowprops=dict(facecolor='black',lw=0.5, arrowstyle="->",), alpha=alpha)

        m = (self.x3[1] - self.x1[1])/(self.x3[0] - self.x1[0])
        y = 0.6
        x = self.x1[0] + (1.0/m)*y
        dx = 0.02
        gca().annotate(r'Axisymmetric Expansion', xy=np.array([x, y]), xytext=np.array([x+dx, y-1.0/m*dx]), fontproperties=font_, rotation=-55, alpha=alpha)

        m = self.x3[1]/self.x3[0]
        y = 0.6
        x = (1.0/m)*y - 0.27
        dx = 0.02
        gca().annotate(r'Axisymmetric Contraction', xy=np.array([x, y]), xytext=np.array([x-dx, y+1.0/m*dx]), fontproperties=font_, rotation=55, alpha=alpha)

        grid(False)
        gca().axis('off')
        gcf().patch.set_visible(False)
        tight_layout()
Esempio n. 21
0
def plot_(X, Y, Z, figsize, font_size=26, save=True, fn='plot', vmax=None):
    '''Plot pocolormesh figure,
    X,Y: the axis
    Z: the values
    xaxis,yaxis the figure size'''
    # set font for both x and y label
    font0 = FontProperties()
    font0.set_style('italic')
    font0.set_size(font_size)
    font0.set_weight('bold')

    fig = plt.figure(figsize=figsize)
    plt.pcolormesh(X, Y, Z, cmap=plt.cm.jet, vmax=vmax)
    plt.axis([X.max(), X.min(), Y.min(), Y.max()])
    plt.colorbar()
    plt.xlabel('Wavenumber  /  $cm^{-1}$', fontproperties=font0)
    plt.ylabel('Time / $s$', fontproperties=font0)
    plt.tick_params(axis='both', labelsize=26, top='off', right='off')
    #   plt.yticks(fontweight='bold')
    if save == True:
        plt.savefig('{}.png'.format(fn), dpi=300)
Esempio n. 22
0
def plot_confusion_matrix(cm, class_names, model):
    """
    Returns a matplotlib figure containing the plotted confusion matrix.
    
    Args:
       cm (array, shape = [n, n]): a confusion matrix of integer classes
       class_names (array, shape = [n]): String names of the integer classes

    credit: https://towardsdatascience.com/exploring-confusion-matrix-evolution-on-tensorboard-e66b39f4ac12
    """

    cm = cm.cpu().detach().numpy()
    font = FontProperties()
    font.set_family('serif')
    font.set_name('Times New Roman')
    font.set_style('normal')

    figure = plt.figure(figsize=(8, 8))
    plt.imshow(cm, interpolation='nearest', cmap=plt.cm.Blues)
    plt.title("Confusion matrix")
    plt.colorbar()
    tick_marks = np.arange(len(class_names))
    plt.xticks(tick_marks, class_names, rotation=45)
    plt.yticks(tick_marks, class_names)

    # Normalize the confusion matrix.
    cm = np.around(cm.astype('float') / cm.sum(axis=1)[:, np.newaxis],
                   decimals=2)

    # Use white text if squares are dark; otherwise black.
    threshold = cm.max() / 2.

    for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
        color = "white" if cm[i, j] > threshold else "black"
        plt.text(j, i, cm[i, j], horizontalalignment="center", color=color)

    plt.tight_layout()
    plt.ylabel('True label')
    plt.xlabel('Predicted label')
    figure.savefig(f'experiments/{model}/test_mtx.png')
Esempio n. 23
0
def font_config():

    # specify Font properties with fontmanager---------------------------------------------------
    font0 = FontProperties()
    font0.set_weight('medium')
    font0.set_family('monospace')

    # Specify Font properties of Legends
    font1 = FontProperties()
    font1.set_weight('normal')
    font1.set_family('sans-serif')
    font1.set_style('italic')
    font1.set_size(12)

    # Specify font properties of Titles
    font2 = FontProperties()
    font2.set_size(15)
    font2.set_family('sans-serif')
    font2.set_weight('medium')
    font2.set_style('italic')

    return font0, font1, font2
Esempio n. 24
0
def plot_Chart(d1, h1, date, time):

    daily_threshold = 2.0
    hourly_threshold = 1.0

    x_axis = np.arange(len(h1))
    width = 0.8
    font_ax = FontProperties()
    font_ax.set_size('xx-small')

    font_lbl = FontProperties()
    font_lbl.set_size('small')
    font_lbl.set_style('italic')

    font_ttl = FontProperties()
    font_ttl.set_size('small')
    #    font_ttl.set_weight('bold')

    plt.subplot(121)
    plt.bar(x_axis, d1['ABS_strength'], width, color='red')
    plt.xticks(x_axis, d1['Currency'], fontproperties=font_ax, rotation=90)
    plt.xlabel('currency', fontproperties=font_lbl)
    plt.ylabel('% Change', fontproperties=font_lbl)
    plt.hlines(daily_threshold, 0, len(d1), linestyles='--', color='k')
    plt.hlines(-daily_threshold, 0, len(d1), linestyles='--', color='k')
    plt.title('Daily Absolute Strength\n ' + str(date),
              fontproperties=font_ttl)

    plt.subplot(122)
    plt.bar(x_axis, h1['ABS_strength'], width, color='blue')
    plt.xticks(x_axis, h1['Currency'], fontproperties=font_ax, rotation=90)
    plt.xlabel('currency', fontproperties=font_lbl)
    plt.hlines(hourly_threshold, 0, len(h1), linestyles='--', color='k')
    plt.hlines(-hourly_threshold, 0, len(h1), linestyles='--', color='k')
    plt.title('Hourly Absolute Strength\n' + str(time),
              fontproperties=font_ttl)

    plt.savefig('index.png')
    plt.clf()
Esempio n. 25
0
class TickLabels(object):
    def __init__(self, parent):

        # Store references to axes
        self._ax1 = parent._ax1
        self._ax2 = parent._ax2
        self._wcs = parent._wcs
        self._figure = parent._figure

        # Save plotting parameters (required for @auto_refresh)
        self._parameters = parent._parameters

        # Set font
        self._label_fontproperties = FontProperties()

        self.set_style("plain")

        system, equinox, units = wcs_util.system(self._wcs)

        # Set default label format
        if self._wcs.xaxis_coord_type in ["longitude", "latitude"]:
            if system["name"] == "equatorial":
                if self._wcs.xaxis_coord_type == "longitude":
                    self.set_xformat("hh:mm:ss.ss")
                else:
                    self.set_xformat("dd:mm:ss.s")
            else:
                self.set_xformat("ddd.dddd")
        else:
            self.set_xformat("%g")

        if self._wcs.yaxis_coord_type in ["longitude", "latitude"]:
            if system["name"] == "equatorial":
                if self._wcs.yaxis_coord_type == "longitude":
                    self.set_yformat("hh:mm:ss.ss")
                else:
                    self.set_yformat("dd:mm:ss.s")
            else:
                self.set_yformat("ddd.dddd")
        else:
            self.set_yformat("%g")

        # Set major tick formatters
        fx1 = WCSFormatter(wcs=self._wcs, coord="x")
        fy1 = WCSFormatter(wcs=self._wcs, coord="y")
        self._ax1.xaxis.set_major_formatter(fx1)
        self._ax1.yaxis.set_major_formatter(fy1)

        fx2 = mpl.NullFormatter()
        fy2 = mpl.NullFormatter()
        self._ax2.xaxis.set_major_formatter(fx2)
        self._ax2.yaxis.set_major_formatter(fy2)

        # Cursor display
        self._ax1._cursor_world = True
        self._figure.canvas.mpl_connect("key_press_event", self._set_cursor_prefs)

    @auto_refresh
    def set_xformat(self, format):
        """
        Set the format of the x-axis tick labels. If the x-axis type is
        ``longitude`` or ``latitude``, then the options are:

            * ``ddd.ddddd`` - decimal degrees, where the number of decimal places can be varied
            * ``hh`` or ``dd`` - hours (or degrees)
            * ``hh:mm`` or ``dd:mm`` - hours and minutes (or degrees and arcminutes)
            * ``hh:mm:ss`` or ``dd:mm:ss`` - hours, minutes, and seconds (or degrees, arcminutes, and arcseconds)
            * ``hh:mm:ss.ss`` or ``dd:mm:ss.ss`` - hours, minutes, and seconds (or degrees, arcminutes, and arcseconds), where the number of decimal places can be varied.

        If the x-axis type is ``scalar``, then the format should be a valid
        python string format beginning with a ``%``.

        If one of these arguments is not specified, the format for that axis
        is left unchanged.
        """
        if self._wcs.xaxis_coord_type in ["longitude", "latitude"]:
            if format.startswith("%"):
                raise Exception("Cannot specify Python format for longitude or latitude")
            try:
                if not self._ax1.xaxis.apl_auto_tick_spacing:
                    au._check_format_spacing_consistency(format, self._ax1.xaxis.apl_tick_spacing)
            except au.InconsistentSpacing:
                warnings.warn(
                    "WARNING: Requested label format is not accurate enough to display ticks. The label format will not be changed."
                )
                return
        else:
            if not format.startswith("%"):
                raise Exception("For scalar tick labels, format should be a Python format beginning with %")

        self._ax1.xaxis.apl_label_form = format
        self._ax2.xaxis.apl_label_form = format

    @auto_refresh
    def set_yformat(self, format):
        """
        Set the format of the y-axis tick labels. If the y-axis type is
        ``longitude`` or ``latitude``, then the options are:

            * ``ddd.ddddd`` - decimal degrees, where the number of decimal places can be varied
            * ``hh`` or ``dd`` - hours (or degrees)
            * ``hh:mm`` or ``dd:mm`` - hours and minutes (or degrees and arcminutes)
            * ``hh:mm:ss`` or ``dd:mm:ss`` - hours, minutes, and seconds (or degrees, arcminutes, and arcseconds)
            * ``hh:mm:ss.ss`` or ``dd:mm:ss.ss`` - hours, minutes, and seconds (or degrees, arcminutes, and arcseconds), where the number of decimal places can be varied.

        If the y-axis type is ``scalar``, then the format should be a valid
        python string format beginning with a ``%``.

        If one of these arguments is not specified, the format for that axis
        is left unchanged.
        """
        if self._wcs.yaxis_coord_type in ["longitude", "latitude"]:
            if format.startswith("%"):
                raise Exception("Cannot specify Python format for longitude or latitude")
            try:
                if not self._ax1.yaxis.apl_auto_tick_spacing:
                    au._check_format_spacing_consistency(format, self._ax1.yaxis.apl_tick_spacing)
            except au.InconsistentSpacing:
                warnings.warn(
                    "WARNING: Requested label format is not accurate enough to display ticks. The label format will not be changed."
                )
                return
        else:
            if not format.startswith("%"):
                raise Exception("For scalar tick labels, format should be a Python format beginning with %")

        self._ax1.yaxis.apl_label_form = format
        self._ax2.yaxis.apl_label_form = format

    @auto_refresh
    def set_style(self, style):
        """
        Set the format of the x-axis tick labels. This can be 'colons' or 'plain':

            * 'colons' uses colons as separators, for example 31:41:59.26 +27:18:28.1
            * 'plain' uses letters and symbols as separators, for example 31h41m59.26s +27º18'28.1"
        """

        if style == "latex":
            warnings.warn(
                "latex has now been merged with plain - whether or not to use LaTeX is controled through set_system_latex"
            )
            style = "plain"

        if not style in ["colons", "plain"]:
            raise Exception("Label style should be one of colons/plain")

        self._ax1.xaxis.apl_labels_style = style
        self._ax1.yaxis.apl_labels_style = style
        self._ax2.xaxis.apl_labels_style = style
        self._ax2.yaxis.apl_labels_style = style

    @auto_refresh
    @fixdocstring
    def set_font(
        self, family=None, style=None, variant=None, stretch=None, weight=None, size=None, fontproperties=None
    ):
        """
        Set the font of the tick labels

        Optional Keyword Arguments:

        common: family, style, variant, stretch, weight, size, fontproperties

        Default values are set by matplotlib or previously set values if
        set_font has already been called. Global default values can be set by
        editing the matplotlibrc file.
        """

        if family:
            self._label_fontproperties.set_family(family)

        if style:
            self._label_fontproperties.set_style(style)

        if variant:
            self._label_fontproperties.set_variant(variant)

        if stretch:
            self._label_fontproperties.set_stretch(stretch)

        if weight:
            self._label_fontproperties.set_weight(weight)

        if size:
            self._label_fontproperties.set_size(size)

        if fontproperties:
            self._label_fontproperties = fontproperties

        for tick in self._ax1.get_xticklabels():
            tick.set_fontproperties(self._label_fontproperties)
        for tick in self._ax1.get_yticklabels():
            tick.set_fontproperties(self._label_fontproperties)
        for tick in self._ax2.get_xticklabels():
            tick.set_fontproperties(self._label_fontproperties)
        for tick in self._ax2.get_yticklabels():
            tick.set_fontproperties(self._label_fontproperties)

    @auto_refresh
    def show(self):
        """
        Show the x- and y-axis tick labels
        """
        self.show_x()
        self.show_y()

    @auto_refresh
    def hide(self):
        """
        Hide the x- and y-axis tick labels
        """
        self.hide_x()
        self.hide_y()

    @auto_refresh
    def show_x(self):
        """
        Show the x-axis tick labels
        """

        for tick in self._ax1.get_xticklabels():
            tick.set_visible(True)
        for tick in self._ax2.get_xticklabels():
            tick.set_visible(True)

    @auto_refresh
    def hide_x(self):
        """
        Hide the x-axis tick labels
        """

        for tick in self._ax1.get_xticklabels():
            tick.set_visible(False)
        for tick in self._ax2.get_xticklabels():
            tick.set_visible(False)

    @auto_refresh
    def show_y(self):
        """
        Show the y-axis tick labels
        """

        for tick in self._ax1.get_yticklabels():
            tick.set_visible(True)
        for tick in self._ax2.get_yticklabels():
            tick.set_visible(True)

    @auto_refresh
    def hide_y(self):
        """
        Hide the y-axis tick labels
        """

        for tick in self._ax1.get_yticklabels():
            tick.set_visible(False)
        for tick in self._ax2.get_yticklabels():
            tick.set_visible(False)

    @auto_refresh
    def set_xposition(self, position):
        "Set the position of the x-axis tick labels ('top' or 'bottom')"
        if position == "bottom":
            fx1 = WCSFormatter(wcs=self._wcs, coord="x")
            self._ax1.xaxis.set_major_formatter(fx1)
            fx2 = mpl.NullFormatter()
            self._ax2.xaxis.set_major_formatter(fx2)
        elif position == "top":
            fx1 = mpl.NullFormatter()
            self._ax1.xaxis.set_major_formatter(fx1)
            fx2 = WCSFormatter(wcs=self._wcs, coord="x")
            self._ax2.xaxis.set_major_formatter(fx2)
        else:
            raise ValueError("position should be one of 'top' or 'bottom'")

    @auto_refresh
    def set_yposition(self, position):
        "Set the position of the y-axis tick labels ('left' or 'right')"
        if position == "left":
            fy1 = WCSFormatter(wcs=self._wcs, coord="y")
            self._ax1.yaxis.set_major_formatter(fy1)
            fy2 = mpl.NullFormatter()
            self._ax2.yaxis.set_major_formatter(fy2)
        elif position == "right":
            fy1 = mpl.NullFormatter()
            self._ax1.yaxis.set_major_formatter(fy1)
            fy2 = WCSFormatter(wcs=self._wcs, coord="y")
            self._ax2.yaxis.set_major_formatter(fy2)
        else:
            raise ValueError("position should be one of 'left' or 'right'")

    def _set_cursor_prefs(self, event, **kwargs):
        if event.key == "c":
            self._ax1._cursor_world = not self._ax1._cursor_world

    def _cursor_position(self, x, y):

        xaxis = self._ax1.xaxis
        yaxis = self._ax1.yaxis

        if self._ax1._cursor_world:

            xw, yw = wcs_util.pix2world(self._wcs, x, y)

            if self._wcs.xaxis_coord_type in ["longitude", "latitude"]:

                xw = au.Angle(degrees=xw, latitude=self._wcs.xaxis_coord_type == "latitude")

                hours = "h" in xaxis.apl_label_form

                if hours:
                    xw = xw.tohours()

                if xaxis.apl_labels_style in ["plain", "latex"]:
                    sep = ("d", "m", "s")
                    if hours:
                        sep = ("h", "m", "s")
                elif xaxis.apl_labels_style == "colons":
                    sep = (":", ":", "")

                xlabel = xw.tostringlist(format=xaxis.apl_label_form, sep=sep)
                xlabel = string.join(xlabel, "")

            else:

                xlabel = xaxis.apl_label_form % xw

            if self._wcs.yaxis_coord_type in ["longitude", "latitude"]:

                yw = au.Angle(degrees=yw, latitude=self._wcs.yaxis_coord_type == "latitude")

                hours = "h" in yaxis.apl_label_form

                if hours:
                    yw = yw.tohours()

                if yaxis.apl_labels_style in ["plain", "latex"]:
                    sep = ("d", "m", "s")
                    if hours:
                        sep = ("h", "m", "s")
                elif yaxis.apl_labels_style == "colons":
                    sep = (":", ":", "")

                ylabel = yw.tostringlist(format=yaxis.apl_label_form, sep=sep)
                ylabel = string.join(ylabel, "")

            else:

                ylabel = yaxis.apl_label_form % yw

            return "%s %s (world)" % (xlabel, ylabel)

        else:

            return "%g %g (pixel)" % (x, y)
Esempio n. 26
0
class Colorbar(object):
    def __init__(self, parent):
        self._figure = parent._figure
        self._colorbar_axes = None
        self._parent = parent

        self._base_settings = {}
        self._ticklabel_fontproperties = FontProperties()
        self._axislabel_fontproperties = FontProperties()

    @auto_refresh
    def show(self,
             location='right',
             width=0.2,
             pad=0.05,
             ticks=None,
             labels=True,
             log_format=False,
             box=None,
             box_orientation='vertical',
             axis_label_text=None,
             axis_label_rotation=None,
             axis_label_pad=5):
        """
        Show a colorbar on the side of the image.

        Parameters
        ----------

        location : str, optional
            Where to place the colorbar. Should be one of 'left', 'right',
            'top', 'bottom'.

        width : float, optional
            The width of the colorbar relative to the canvas size.

        pad : float, optional
            The spacing between the colorbar and the image relative to the
            canvas size.

        ticks : list, optional
            The position of the ticks on the colorbar.

        labels : bool, optional
            Whether to show numerical labels.

        log_format : bool, optional
            Whether to format ticks in exponential notation

        box : list, optional
            A custom box within which to place the colorbar. This should
            be in the form [xmin, ymin, dx, dy] and be in relative figure
            units. This overrides the location argument.

        box_orientation str, optional
            The orientation of the colorbar within the box. Can be
            'horizontal' or 'vertical'

        axis_label_text str, optional
            Optional text label of the colorbar.
        """

        self._base_settings['location'] = location
        self._base_settings['width'] = width
        self._base_settings['pad'] = pad
        self._base_settings['ticks'] = ticks
        self._base_settings['labels'] = labels
        self._base_settings['log_format'] = log_format
        self._base_settings['box'] = box
        self._base_settings['box_orientation'] = box_orientation
        self._base_settings['axis_label_text'] = axis_label_text
        self._base_settings['axis_label_rotation'] = axis_label_rotation
        self._base_settings['axis_label_pad'] = axis_label_pad

        if self._parent.image:

            if self._colorbar_axes:
                self._figure.delaxes(self._colorbar_axes)

            if box is None:

                divider = make_axes_locatable(self._parent.ax)

                if location == 'right':
                    self._colorbar_axes = divider.new_horizontal(
                        size=width, pad=pad, axes_class=maxes.Axes)
                    orientation = 'vertical'
                elif location == 'top':
                    self._colorbar_axes = divider.new_vertical(
                        size=width, pad=pad, axes_class=maxes.Axes)
                    orientation = 'horizontal'
                elif location == 'left':
                    warnings.warn("Left colorbar not fully implemented")
                    self._colorbar_axes = divider.new_horizontal(
                        size=width,
                        pad=pad,
                        pack_start=True,
                        axes_class=maxes.Axes)
                    locator = divider.new_locator(nx=0, ny=0)
                    self._colorbar_axes.set_axes_locator(locator)
                    orientation = 'vertical'
                elif location == 'bottom':
                    warnings.warn("Bottom colorbar not fully implemented")
                    self._colorbar_axes = divider.new_vertical(
                        size=width,
                        pad=pad,
                        pack_start=True,
                        axes_class=maxes.Axes)
                    locator = divider.new_locator(nx=0, ny=0)
                    self._colorbar_axes.set_axes_locator(locator)
                    orientation = 'horizontal'
                else:
                    raise Exception("location should be one of: right/top")

                self._figure.add_axes(self._colorbar_axes)

            else:

                self._colorbar_axes = self._figure.add_axes(box)
                orientation = box_orientation

            if log_format:
                format = LogFormatterMathtext()
            else:
                format = None

            self._colorbar = self._figure.colorbar(self._parent.image,
                                                   cax=self._colorbar_axes,
                                                   orientation=orientation,
                                                   format=format,
                                                   ticks=ticks)
            if axis_label_text:
                if axis_label_rotation:
                    self._colorbar.set_label(axis_label_text,
                                             rotation=axis_label_rotation)
                else:
                    self._colorbar.set_label(axis_label_text)

            if location == 'right':
                for tick in self._colorbar_axes.yaxis.get_major_ticks():
                    tick.tick1line.set_visible(True)
                    tick.tick2line.set_visible(True)
                    tick.label1.set_visible(False)
                    tick.label2.set_visible(labels)
                self._colorbar_axes.yaxis.set_label_position('right')
                self._colorbar_axes.yaxis.labelpad = axis_label_pad
            elif location == 'top':
                for tick in self._colorbar_axes.xaxis.get_major_ticks():
                    tick.tick1line.set_visible(True)
                    tick.tick2line.set_visible(True)
                    tick.label1.set_visible(False)
                    tick.label2.set_visible(labels)
                self._colorbar_axes.xaxis.set_label_position('top')
                self._colorbar_axes.xaxis.labelpad = axis_label_pad
            elif location == 'left':
                for tick in self._colorbar_axes.yaxis.get_major_ticks():
                    tick.tick1line.set_visible(True)
                    tick.tick2line.set_visible(True)
                    tick.label1.set_visible(labels)
                    tick.label2.set_visible(False)
                self._colorbar_axes.yaxis.set_label_position('left')
                self._colorbar_axes.yaxis.labelpad = axis_label_pad
            elif location == 'bottom':
                for tick in self._colorbar_axes.xaxis.get_major_ticks():
                    tick.tick1line.set_visible(True)
                    tick.tick2line.set_visible(True)
                    tick.label1.set_visible(labels)
                    tick.label2.set_visible(False)
                self._colorbar_axes.xaxis.set_label_position('bottom')
                self._colorbar_axes.xaxis.labelpad = axis_label_pad

        else:

            warnings.warn(
                "No image is shown, therefore, no colorbar will be plotted")

    @auto_refresh
    def update(self):
        if self._colorbar_axes:
            self.show(**self._base_settings)

    @auto_refresh
    def hide(self):
        self._figure.delaxes(self._colorbar_axes)
        self._colorbar_axes = None

    @auto_refresh
    def _remove(self):
        self._figure.delaxes(self._colorbar_axes)

    # LOCATION AND SIZE

    @auto_refresh
    def set_location(self, location):
        """
        Set the location of the colorbar.

        Should be one of 'left', 'right', 'top', 'bottom'.
        """
        self._base_settings['location'] = location
        self.show(**self._base_settings)
        self.set_font(fontproperties=self._ticklabel_fontproperties)
        self.set_axis_label_font(fontproperties=self._axislabel_fontproperties)

    @auto_refresh
    def set_width(self, width):
        """
        Set the width of the colorbar relative to the canvas size.
        """
        self._base_settings['width'] = width
        self.show(**self._base_settings)
        self.set_font(fontproperties=self._ticklabel_fontproperties)
        self.set_axis_label_font(fontproperties=self._axislabel_fontproperties)

    @auto_refresh
    def set_pad(self, pad):
        """
        Set the spacing between the colorbar and the image relative to the
        canvas size.
        """
        self._base_settings['pad'] = pad
        self.show(**self._base_settings)
        self.set_font(fontproperties=self._ticklabel_fontproperties)
        self.set_axis_label_font(fontproperties=self._axislabel_fontproperties)

    @auto_refresh
    def set_ticks(self, ticks):
        """
        Set the position of the ticks on the colorbar.
        """
        self._base_settings['ticks'] = ticks
        self.show(**self._base_settings)
        self.set_font(fontproperties=self._ticklabel_fontproperties)
        self.set_axis_label_font(fontproperties=self._axislabel_fontproperties)

    @auto_refresh
    def set_labels(self, labels):
        """
        Set whether to show numerical labels.
        """
        self._base_settings['labels'] = labels
        self.show(**self._base_settings)
        self.set_font(fontproperties=self._ticklabel_fontproperties)
        self.set_axis_label_font(fontproperties=self._axislabel_fontproperties)

    @auto_refresh
    def set_box(self, box, box_orientation='vertical'):
        """
        Set the box within which to place the colorbar.

        This should be in the form [xmin, ymin, dx, dy] and be in relative
        figure units. The orientation of the colorbar within the box can be
        controlled with the box_orientation argument.
        """
        self._base_settings['box'] = box
        self._base_settings['box_orientation'] = box_orientation
        self.show(**self._base_settings)
        self.set_font(fontproperties=self._ticklabel_fontproperties)
        self.set_axis_label_font(fontproperties=self._axislabel_fontproperties)

    @auto_refresh
    def set_axis_label_text(self, axis_label_text):
        """
        Set the colorbar label text.
        """
        self._base_settings['axis_label_text'] = axis_label_text
        self.show(**self._base_settings)
        self.set_font(fontproperties=self._ticklabel_fontproperties)
        self.set_axis_label_font(fontproperties=self._axislabel_fontproperties)

    @auto_refresh
    def set_axis_label_rotation(self, axis_label_rotation):
        """
        Set the colorbar label rotation.
        """
        self._base_settings['axis_label_rotation'] = axis_label_rotation
        self.show(**self._base_settings)
        self.set_font(fontproperties=self._ticklabel_fontproperties)
        self.set_axis_label_font(fontproperties=self._axislabel_fontproperties)

    @auto_refresh
    def set_axis_label_pad(self, axis_label_pad):
        """
        Set the colorbar label displacement, in points.
        """
        self._base_settings['axis_label_pad'] = axis_label_pad
        self.show(**self._base_settings)
        self.set_font(fontproperties=self._ticklabel_fontproperties)
        self.set_axis_label_font(fontproperties=self._axislabel_fontproperties)

    # FONT PROPERTIES

    @auto_refresh
    def set_label_properties(self, *args, **kwargs):
        warnings.warn(
            "set_label_properties is deprecated - use set_font instead",
            DeprecationWarning)
        self.set_font(*args, **kwargs)

    @auto_refresh
    @fixdocstring
    def set_font(self,
                 family=None,
                 style=None,
                 variant=None,
                 stretch=None,
                 weight=None,
                 size=None,
                 fontproperties=None):
        """
        Set the font of the tick labels.

        Parameters
        ----------

        common: family, style, variant, stretch, weight, size, fontproperties

        Notes
        -----

        Default values are set by matplotlib or previously set values if
        set_font has already been called. Global default values can be set by
        editing the matplotlibrc file.
        """

        if family:
            self._ticklabel_fontproperties.set_family(family)

        if style:
            self._ticklabel_fontproperties.set_style(style)

        if variant:
            self._ticklabel_fontproperties.set_variant(variant)

        if stretch:
            self._ticklabel_fontproperties.set_stretch(stretch)

        if weight:
            self._ticklabel_fontproperties.set_weight(weight)

        if size:
            self._ticklabel_fontproperties.set_size(size)

        if fontproperties:
            self._ticklabel_fontproperties = fontproperties

        # Update the tick label font properties
        for label in self._colorbar_axes.get_xticklabels():
            label.set_fontproperties(self._ticklabel_fontproperties)
        for label in self._colorbar_axes.get_yticklabels():
            label.set_fontproperties(self._ticklabel_fontproperties)

        # Also update the offset text font properties
        label = self._colorbar_axes.xaxis.get_offset_text()
        label.set_fontproperties(self._ticklabel_fontproperties)
        label = self._colorbar_axes.yaxis.get_offset_text()
        label.set_fontproperties(self._ticklabel_fontproperties)

    @auto_refresh
    @fixdocstring
    def set_axis_label_font(self,
                            family=None,
                            style=None,
                            variant=None,
                            stretch=None,
                            weight=None,
                            size=None,
                            fontproperties=None):
        """
        Set the font of the tick labels.

        Parameters
        ----------

        common: family, style, variant, stretch, weight, size, fontproperties

        Notes
        -----

        Default values are set by matplotlib or previously set values if
        set_font has already been called. Global default values can be set by
        editing the matplotlibrc file.
        """

        if family:
            self._axislabel_fontproperties.set_family(family)

        if style:
            self._axislabel_fontproperties.set_style(style)

        if variant:
            self._axislabel_fontproperties.set_variant(variant)

        if stretch:
            self._axislabel_fontproperties.set_stretch(stretch)

        if weight:
            self._axislabel_fontproperties.set_weight(weight)

        if size:
            self._axislabel_fontproperties.set_size(size)

        if fontproperties:
            self._axislabel_fontproperties = fontproperties

        # Update the label font properties
        label = self._colorbar_axes.xaxis.get_label()
        label.set_fontproperties(self._axislabel_fontproperties)
        label = self._colorbar_axes.yaxis.get_label()
        label.set_fontproperties(self._axislabel_fontproperties)

    # FRAME PROPERTIES

    @auto_refresh
    def set_frame_linewidth(self, linewidth):
        """
        Set the linewidth of the colorbar frame, in points.
        """
        warnings.warn("This method is not functional at this time")
        for key in self._colorbar_axes.spines:
            self._colorbar_axes.spines[key].set_linewidth(linewidth)

    @auto_refresh
    def set_frame_color(self, color):
        """
        Set the color of the colorbar frame, in points.
        """
        warnings.warn("This method is not functional at this time")
        for key in self._colorbar_axes.spines:
            self._colorbar_axes.spines[key].set_edgecolor(color)
Esempio n. 27
0
class Dashboard(object):
    def __init__(self, **kws):
        self.canvas = plt
        self._return_charts = kws.get('return_charts', True)
        self.prop = FontProperties()
        self.prop.set_size(10)
        self.prop.set_stretch('ultra-expanded')
        self.prop.set_style('oblique')
        self.prop.set_variant('small-caps')
        self.prop.set_weight('book')
        self.prop.set_family('fantasy')

    _mocked_meth = lambda s: print('!!! Your instance has `return_charts` '
                                   'set to `False`.\nDo `<your_instance>.'
                                   'return_charts = True` and retry.')

    def plot(self,
             abs_,
             imas,
             labels,
             colors,
             save=False,
             save_dir='',
             file_name='',
             bar=False):
        """ Method which graphs `imas` against `abs_`.

        Testing/Example
        ---------------
        >>> x  = np.arange(10)[None, :]
        >>> x
        array([[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]])
        >>> ys = np.mgrid[0:3:1, 0:10:1][0, :, :]
        >>> ys
        array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
               [1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
               [2, 2, 2, 2, 2, 2, 2, 2, 2, 2]])
        >>> labs = [
        ...     'constant 1',
        ...     'constant 2',
        ...     'constant 3'
        ... ]
        >>> cols = [
        ...     'red', 'blue', 'black'
        ... ]   
        >>> pltobj = Dashboard(return_charts=True).plot(
        ...     abs_   = x.T,
        ...     imas   = ys.T,
        ...     labels = labs,
        ...     colors = cols,
        ... )
        >>> pltobj.show() # doctest: +SKIP
        >>> pltobj.close() 
        >>> pltobj = Dashboard(return_charts=False).plot(
        ...     abs_   = x.T,
        ...     imas   = ys.T,
        ...     labels = labs,
        ...     colors = cols,
        ... )
        >>> pltobj.show()
        !!! Your instance has `return_charts` set to `False`.
        Do `<your_instance>.return_charts = True` and retry.

        """
        if type(abs_).__module__ != np.__name__:
            lenabs_ = len(abs_)
            abs_ = np.array(abs_)
            abs_.shape = (lenabs_, 1)
        imas = imas.T.tolist()

        self.canvas.clf()
        for ima, label, color in zip(imas, labels, colors):
            if type(ima).__module__ != np.__name__:
                lenOrd = len(ima)
                ima = np.array(ima)
                ima.shape = (lenOrd, 1)
            if bar:
                self.canvas.bar(abs_,
                                ima,
                                align='center',
                                label=label.upper(),
                                color=color,
                                linewidth=0)
            else:
                self.canvas.plot(abs_, ima, label=label.upper(), color=color)
        self.canvas.legend(prop=self.prop,
                           loc='upper right',
                           labelspacing=0.2,
                           bbox_to_anchor=(1.1, 1.))
        save_dir, file_name = save_dir_and_file_name(save_dir=save_dir,
                                                     file_name=file_name,
                                                     save=save)

        self.canvas.xticks(np.arange(min(abs_),
                                     max(abs_) + 1, 1.0),
                           rotation=70)

        if save:
            self.canvas.savefig(os.path.join(save_dir, '%s.png' % file_name),
                                bbox_inches=0,
                                dpi=200)

        if self._return_charts:
            return self.canvas

        self.canvas.close()
        return type('msger', (object, ), {
            'show': self._mocked_meth,
            'close': self._mocked_meth,
        })
Esempio n. 28
0
import os
import random
import matplotlib
matplotlib.use('Agg')

import datetime
import pylab as P
import numpy as N

import orbit_plot_utils
from variables import data_dict
from variables import color_table

from matplotlib.font_manager import FontProperties
ital = FontProperties()
ital.set_style('italic')

au2km = 149597870.691
xpagescale = au2km * 0.25
ypagescale = xpagescale / 8.5 * 11.0
ymin = -ypagescale * 1.75 / 11.0
ymax = ymin + ypagescale

pages = range(198)
xoffset = -xpagescale * 4.75 / 8.5

# 72 (points/inch) * 8.5 (inches) / xpagescale (km)
km2points = 72 * 8.5 / xpagescale
points2km = 1.0 / km2points

planets = [i for i in data_dict if str(i)[-2:] == '99' and i > 0 and i < 1000]
Esempio n. 29
0
class Colorbar(object):

    def __init__(self, parent):
        self._figure = parent._figure
        self._colorbar_axes = None
        self._parent = parent

        # Save plotting parameters (required for @auto_refresh)
        # self._parameters = parent._parameters

        self._base_settings = {}
        self._ticklabel_fontproperties = FontProperties()
        self._axislabel_fontproperties = FontProperties()

    def show(self, location='right', width=0.2, pad=0.05, ticks=None,
             labels=True, log_format=False, box=None,
             box_orientation='vertical', axis_label_text=None,
             axis_label_rotation=None, axis_label_pad=5):
        '''
        Show a colorbar on the side of the image.

        Parameters
        ----------

        location : str, optional
            Where to place the colorbar. Should be one of 'left', 'right', 'top', 'bottom'.

        width : float, optional
            The width of the colorbar relative to the canvas size.

        pad : float, optional
            The spacing between the colorbar and the image relative to the
            canvas size.

        ticks : list, optional
            The position of the ticks on the colorbar.

        labels : bool, optional
            Whether to show numerical labels.

        log_format : bool, optional
            Whether to format ticks in exponential notation

        box : list, optional
            A custom box within which to place the colorbar. This should
            be in the form [xmin, ymin, dx, dy] and be in relative figure
            units. This overrides the location argument.

        box_orientation str, optional
            The orientation of the colorbar within the box. Can be
            'horizontal' or 'vertical'

        axis_label_text str, optional
            Optional text label of the colorbar.
        '''

        self._base_settings['location'] = location
        self._base_settings['width'] = width
        self._base_settings['pad'] = pad
        self._base_settings['ticks'] = ticks
        self._base_settings['labels'] = labels
        self._base_settings['log_format'] = log_format
        self._base_settings['box'] = box
        self._base_settings['box_orientation'] = box_orientation
        self._base_settings['axis_label_text'] = axis_label_text
        self._base_settings['axis_label_rotation'] = axis_label_rotation
        self._base_settings['axis_label_pad'] = axis_label_pad

        if self._parent.image:

            if self._colorbar_axes:
                self._parent._figure.delaxes(self._colorbar_axes)

            if box is None:

                divider = make_axes_locatable(self._parent.ax)

                if location == 'right':
                    self._colorbar_axes = divider.new_horizontal(size=width, pad=pad, axes_class=maxes.Axes)
                    orientation = 'vertical'
                elif location == 'top':
                    self._colorbar_axes = divider.new_vertical(size=width, pad=pad, axes_class=maxes.Axes)
                    orientation = 'horizontal'
                elif location == 'left':
                    warnings.warn("Left colorbar not fully implemented")
                    self._colorbar_axes = divider.new_horizontal(size=width, pad=pad, pack_start=True, axes_class=maxes.Axes)
                    locator = divider.new_locator(nx=0, ny=0)
                    self._colorbar_axes.set_axes_locator(locator)
                    orientation = 'vertical'
                elif location == 'bottom':
                    warnings.warn("Bottom colorbar not fully implemented")
                    self._colorbar_axes = divider.new_vertical(size=width, pad=pad, pack_start=True, axes_class=maxes.Axes)
                    locator = divider.new_locator(nx=0, ny=0)
                    self._colorbar_axes.set_axes_locator(locator)
                    orientation = 'horizontal'
                else:
                    raise Exception("location should be one of: right/top")

                self._parent._figure.add_axes(self._colorbar_axes)

            else:

                self._colorbar_axes = self._parent._figure.add_axes(box)
                orientation = box_orientation

            if log_format:
                format = LogFormatterMathtext()
            else:
                format = None

            self._colorbar = self._parent._figure.colorbar(self._parent.image, cax=self._colorbar_axes,
                                                       orientation=orientation, format=format,
                                                       ticks=ticks)
            if axis_label_text:
                if axis_label_rotation:
                    self._colorbar.set_label(axis_label_text, rotation=axis_label_rotation)
                else:
                    self._colorbar.set_label(axis_label_text)

            if location == 'right':
                for tick in self._colorbar_axes.yaxis.get_major_ticks():
                    tick.tick1On = True
                    tick.tick2On = True
                    tick.label1On = False
                    tick.label2On = labels
                self._colorbar_axes.yaxis.set_label_position('right')
                self._colorbar_axes.yaxis.labelpad = axis_label_pad
            elif location == 'top':
                for tick in self._colorbar_axes.xaxis.get_major_ticks():
                    tick.tick1On = True
                    tick.tick2On = True
                    tick.label1On = False
                    tick.label2On = labels
                self._colorbar_axes.xaxis.set_label_position('top')
                self._colorbar_axes.xaxis.labelpad = axis_label_pad
            elif location == 'left':
                for tick in self._colorbar_axes.yaxis.get_major_ticks():
                    tick.tick1On = True
                    tick.tick2On = True
                    tick.label1On = labels
                    tick.label2On = False
                self._colorbar_axes.yaxis.set_label_position('left')
                self._colorbar_axes.yaxis.labelpad = axis_label_pad
            elif location == 'bottom':
                for tick in self._colorbar_axes.xaxis.get_major_ticks():
                    tick.tick1On = True
                    tick.tick2On = True
                    tick.label1On = labels
                    tick.label2On = False
                self._colorbar_axes.xaxis.set_label_position('bottom')
                self._colorbar_axes.xaxis.labelpad = axis_label_pad

        else:

            warnings.warn("No image is shown, therefore, no colorbar will be plotted")

    # @auto_refresh
    def update(self):
        if self._colorbar_axes:
            self.show(**self._base_settings)

    # @auto_refresh
    def hide(self):
        self._parent._figure.delaxes(self._colorbar_axes)
        self._colorbar_axes = None

    # @auto_refresh
    def _remove(self):
        self._parent._figure.delaxes(self._colorbar_axes)

    # LOCATION AND SIZE

    # @auto_refresh
    def set_location(self, location):
        '''
        Set the location of the colorbar.

        Should be one of 'left', 'right', 'top', 'bottom'.
        '''
        self._base_settings['location'] = location
        self.show(**self._base_settings)
        self.set_font(fontproperties=self._ticklabel_fontproperties)
        self.set_axis_label_font(fontproperties=self._axislabel_fontproperties)

    # @auto_refresh
    def set_width(self, width):
        '''
        Set the width of the colorbar relative to the canvas size.
        '''
        self._base_settings['width'] = width
        self.show(**self._base_settings)
        self.set_font(fontproperties=self._ticklabel_fontproperties)
        self.set_axis_label_font(fontproperties=self._axislabel_fontproperties)

    # @auto_refresh
    def set_pad(self, pad):
        '''
        Set the spacing between the colorbar and the image relative to the canvas size.
        '''
        self._base_settings['pad'] = pad
        self.show(**self._base_settings)
        self.set_font(fontproperties=self._ticklabel_fontproperties)
        self.set_axis_label_font(fontproperties=self._axislabel_fontproperties)

    # @auto_refresh
    def set_ticks(self, ticks):
        '''
        Set the position of the ticks on the colorbar.
        '''
        self._base_settings['ticks'] = ticks
        self.show(**self._base_settings)
        self.set_font(fontproperties=self._ticklabel_fontproperties)
        self.set_axis_label_font(fontproperties=self._axislabel_fontproperties)

    # @auto_refresh
    def set_labels(self, labels):
        '''
        Set whether to show numerical labels.
        '''
        self._base_settings['labels'] = labels
        self.show(**self._base_settings)
        self.set_font(fontproperties=self._ticklabel_fontproperties)
        self.set_axis_label_font(fontproperties=self._axislabel_fontproperties)

    # @auto_refresh
    def set_box(self, box, box_orientation='vertical'):
        '''
        Set the box within which to place the colorbar.

        This should be in the form [xmin, ymin, dx, dy] and be in relative
        figure units. The orientation of the colorbar within the box can be
        controlled with the box_orientation argument.
        '''
        self._base_settings['box'] = box
        self._base_settings['box_orientation'] = box_orientation
        self.show(**self._base_settings)
        self.set_font(fontproperties=self._ticklabel_fontproperties)
        self.set_axis_label_font(fontproperties=self._axislabel_fontproperties)

    # @auto_refresh
    def set_axis_label_text(self, axis_label_text):
        '''
        Set the colorbar label text.
        '''
        self._base_settings['axis_label_text'] = axis_label_text
        self.show(**self._base_settings)
        self.set_font(fontproperties=self._ticklabel_fontproperties)
        self.set_axis_label_font(fontproperties=self._axislabel_fontproperties)

    # @auto_refresh
    def set_axis_label_rotation(self, axis_label_rotation):
        '''
        Set the colorbar label rotation.
        '''
        self._base_settings['axis_label_rotation'] = axis_label_rotation
        self.show(**self._base_settings)
        self.set_font(fontproperties=self._ticklabel_fontproperties)
        self.set_axis_label_font(fontproperties=self._axislabel_fontproperties)

    # @auto_refresh
    def set_axis_label_pad(self, axis_label_pad):
        '''
        Set the colorbar label displacement, in points.
        '''
        self._base_settings['axis_label_pad'] = axis_label_pad
        self.show(**self._base_settings)
        self.set_font(fontproperties=self._ticklabel_fontproperties)
        self.set_axis_label_font(fontproperties=self._axislabel_fontproperties)

    # FONT PROPERTIES

    # @auto_refresh
    def set_label_properties(self, *args, **kwargs):
        warnings.warn("set_label_properties is deprecated - use set_font instead", DeprecationWarning)
        self.set_font(*args, **kwargs)

    # @auto_refresh
    # @fixdocstring
    def set_font(self, family=None, style=None, variant=None, stretch=None,
                 weight=None, size=None, fontproperties=None):
        '''
        Set the font of the tick labels.

        Parameters
        ----------

        common: family, style, variant, stretch, weight, size, fontproperties

        Notes
        -----

        Default values are set by matplotlib or previously set values if
        set_font has already been called. Global default values can be set by
        editing the matplotlibrc file.
        '''

        if family:
            self._ticklabel_fontproperties.set_family(family)

        if style:
            self._ticklabel_fontproperties.set_style(style)

        if variant:
            self._ticklabel_fontproperties.set_variant(variant)

        if stretch:
            self._ticklabel_fontproperties.set_stretch(stretch)

        if weight:
            self._ticklabel_fontproperties.set_weight(weight)

        if size:
            self._ticklabel_fontproperties.set_size(size)

        if fontproperties:
            self._ticklabel_fontproperties = fontproperties

        # Update the tick label font properties
        for label in self._colorbar_axes.get_xticklabels():
            label.set_fontproperties(self._ticklabel_fontproperties)
        for label in self._colorbar_axes.get_yticklabels():
            label.set_fontproperties(self._ticklabel_fontproperties)

        # Also update the offset text font properties
        label = self._colorbar_axes.xaxis.get_offset_text()
        label.set_fontproperties(self._ticklabel_fontproperties)
        label = self._colorbar_axes.yaxis.get_offset_text()
        label.set_fontproperties(self._ticklabel_fontproperties)

    # @auto_refresh
    # @fixdocstring
    def set_axis_label_font(self, family=None, style=None, variant=None,
                            stretch=None, weight=None, size=None,
                            fontproperties=None):
        '''
        Set the font of the tick labels.

        Parameters
        ----------

        common: family, style, variant, stretch, weight, size, fontproperties

        Notes
        -----

        Default values are set by matplotlib or previously set values if
        set_font has already been called. Global default values can be set by
        editing the matplotlibrc file.
        '''

        if family:
            self._axislabel_fontproperties.set_family(family)

        if style:
            self._axislabel_fontproperties.set_style(style)

        if variant:
            self._axislabel_fontproperties.set_variant(variant)

        if stretch:
            self._axislabel_fontproperties.set_stretch(stretch)

        if weight:
            self._axislabel_fontproperties.set_weight(weight)

        if size:
            self._axislabel_fontproperties.set_size(size)

        if fontproperties:
            self._axislabel_fontproperties = fontproperties

        # Update the label font properties
        label = self._colorbar_axes.xaxis.get_label()
        label.set_fontproperties(self._axislabel_fontproperties)
        label = self._colorbar_axes.yaxis.get_label()
        label.set_fontproperties(self._axislabel_fontproperties)

    # FRAME PROPERTIES

    # @auto_refresh
    def set_frame_linewidth(self, linewidth):
        '''
        Set the linewidth of the colorbar frame, in points.
        '''
        warnings.warn("This method is not functional at this time")
        for key in self._colorbar_axes.spines:
            self._colorbar_axes.spines[key].set_linewidth(linewidth)

    # @auto_refresh
    def set_frame_color(self, color):
        '''
        Set the color of the colorbar frame, in points.
        '''
        warnings.warn("This method is not functional at this time")
        for key in self._colorbar_axes.spines:
            self._colorbar_axes.spines[key].set_edgecolor(color)
Esempio n. 30
0
    def plot_trial_steps(self):
        '''Plot target (sig-eps-curve of the tensile test) and trial curves
        and corresponding phi function together with trail steps from the iteration process.
        NOTE: the global variable 'rec_trial_steps' must be set to 'True' in order to store the iteration values
              within the global variables 'phi_trial_list_n' and 'sig_trial_list_n'
        n - index of the time steps to be considered
        i - index of the iteration steps performed in order to fit the target curve
        '''
        #-------------------------------------------------------------------
        # configure the style of the font to be used for labels and ticks
        #-------------------------------------------------------------------
        #
        from matplotlib.font_manager import FontProperties
        font = FontProperties()
#        font.serif         : Times, Palatino, New Century Schoolbook, Bookman, Computer Modern Roman
#        font.sans-serif    : Helvetica, Avant Garde, Computer Modern Sans serif
#        font.cursive       : Zapf Chancery
#        font.monospace     : Courier, Computer Modern Typewriter
        font.set_name('Script MT')
        # name = ['Times New Roman', 'Helvetica', 'Script MT'] #?
        font.set_family('serif')
        # family = ['serif', 'sans-serif', 'cursive', 'fantasy', 'monospace']
        font.set_style('normal')
        # style  = ['normal', 'italic', 'oblique']
        font.set_size('small')
        # size  = ['xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large', '11']
        font.set_variant('normal')
        # variant= ['normal', 'small-caps']
        font.set_weight('medium')
        # weight = ['light', 'normal', 'medium', 'semibold', 'bold', 'heavy', 'black']

        #-------------------------------------------------------------------

        p.figure(facecolor='white', dpi=600,
                 figsize=(8, 6))  # white background

        # time list corresponding to the specified numbers of steps and step size
        #
        step_list = [n * self.step_size for n in range(self.n_steps + 1)]

        # get list of lists containing the trial values of 'sig_app' and 'phi_trail'
        # the lists are defined as global variables of 'MATSCalibDamageFn' and are filled
        # within the iteration process when the method 'get_lack_of_fit" is called
        #
        phi_trial_list_n = [[1.]] + self.phi_trial_list_n
        sig_trial_list_n = [[0.]] + self.sig_trial_list_n

        xrange = 10.  # plotting range for strain [mm/m]
        yrange = 15.  # plotting range for stress [MPa]

        for n in range(self.n_steps):
            for i in range(len(phi_trial_list_n[n + 1])):
                x = np.array([step_list[n], step_list[n + 1]])
                eps = 1000. * x  # plot strains in permil on the x-axis
                #--------------------------------------
                # sig-eps trial
                #--------------------------------------
                # plot the numerically calculated sig-eps-curve (tensile test)
                # (with trial steps)
                #
                sig_trail = np.array(
                    [sig_trial_list_n[n][-1], sig_trial_list_n[n + 1][i]])
                p.subplot(222)
                p.plot(eps, sig_trail, color='k', linewidth=1)
                p.xlabel(r'strain $\varepsilon$ [1E-3]', fontproperties=font)
                p.ylabel('stress $\sigma$ [MPa]', fontproperties=font)
                if self.format_ticks:
                    # format ticks for plot
                    p.axis([0, xrange, 0., yrange], fontproperties=font)
                    locs, labels = p.xticks()
                    p.xticks(locs, map(lambda x: "%.0f" %
                                       x, locs), fontproperties=font)
                    locs, labels = p.yticks()
                    p.yticks(locs, map(lambda x: "%.0f" %
                                       x, locs), fontproperties=font)

                #--------------------------------------
                # phi_trail
                #--------------------------------------
                # plot the fitted phi-function
                # (with trial steps)
                #
                p.subplot(224)
                phi_trail = np.array(
                    [phi_trial_list_n[n][-1], phi_trial_list_n[n + 1][i]])
                p.plot(eps, phi_trail, color='k', linewidth=1)
                p.xlabel(r'strain $\varepsilon$ [1E-3]', fontproperties=font)
                p.ylabel('integrity $\phi$ [-]', fontproperties=font)
                if self.format_ticks:
                    # format ticks for plot
                    p.yticks([0, 0.2, 0.4, 0.6, 0.8, 1.0])
                    p.axis([0, xrange, 0., 1.])
                    locs, labels = p.xticks()
                    p.xticks(locs, map(lambda x: "%.0f" %
                                       x, locs), fontproperties=font)
                    locs, labels = p.yticks()
                    p.yticks(locs, map(lambda x: "%.1f" %
                                       x, locs), fontproperties=font)

        #--------------------------------------
        # sig-eps target
        #--------------------------------------
        # plot the sig-eps-target curve (tensile test)
        #
        p.subplot(221)
        eps = 1000. * self.mfn_line_array_target.xdata[:-1]
        sig_target = self.mfn_line_array_target.ydata[:-1]
        p.plot(eps, sig_target, color='black', linewidth=1)
        p.xlabel(r'strain $\varepsilon$ [1E-3]', fontproperties=font)
        p.ylabel('stress $\sigma$ [MPa]', fontproperties=font)
        if self.format_ticks:
            # format ticks for plot
            p.axis([0, xrange, 0., yrange])
            locs, labels = p.xticks()
            p.xticks(locs, map(lambda x: "%.0f" %
                               x, locs), fontproperties=font)
            locs, labels = p.yticks()
            p.yticks(locs, map(lambda x: "%.0f" %
                               x, locs), fontproperties=font)

        #--------------------------------------
        # phi_trail (final)
        #--------------------------------------
        # plot the corresponding fitted phi-function
        # (without trial steps)
        #
        p.subplot(223)
        eps = 1000. * self.fitted_phi_fn.xdata[:-1]
        phi_fn = self.fitted_phi_fn.ydata[:-1]
        p.plot(eps, phi_fn, color='black', linewidth=1)
        p.xlabel(r'strain $\varepsilon$ [1E-3]', fontproperties=font)
        p.ylabel('integrity $\phi$ [-]', fontproperties=font)
        if self.format_ticks:
            # format ticks for plot
            p.yticks([0, 0.2, 0.4, 0.6, 0.8, 1.0])
            p.axis([0, xrange, 0., 1.])
            locs, labels = p.xticks()
            p.xticks(locs, map(lambda x: "%.0f" %
                               x, locs), fontproperties=font)
            locs, labels = p.yticks()
            p.yticks(locs, map(lambda x: "%.1f" %
                               x, locs), fontproperties=font)

        # save figure with calibration process in directory
        # "/simdb/simdata/lcc_table/output_images/save_fig_to_file.png"
        simdata_dir = os.path.join(simdb.simdata_dir, 'mats_calib_damage_fn')
        if os.path.isdir(simdata_dir) == False:
            os.makedirs(simdata_dir)

        ctt_key = self.test_key
        filename = os.path.join(simdata_dir, ctt_key + self.param_key + '.pdf')
        p.savefig(filename)
        print 'plot_trail_steps.png saved to file %s' % (filename)
        filename = os.path.join(simdata_dir, ctt_key + self.param_key + '.png')
        p.savefig(filename, dpi=600)
        print 'plot_trail_steps.png saved to file %s' % (filename)

        p.show()
Esempio n. 31
0
class AxisLabels(object):
    def __init__(self, parent):

        # Store references to axes
        self._ax1 = parent._ax1
        self._ax2 = parent._ax2
        self._wcs = parent._wcs
        self._figure = parent._figure

        # Save plotting parameters (required for @auto_refresh)
        self._parameters = parent._parameters

        # Set font
        self._label_fontproperties = FontProperties()

        self._ax2.yaxis.set_label_position('right')
        self._ax2.xaxis.set_label_position('top')

        system, equinox, units = wcs_util.system(self._wcs)

        if system['name'] == 'equatorial':

            if equinox == 'b1950':
                xtext = 'RA (B1950)'
                ytext = 'Dec (B1950)'
            else:
                xtext = 'RA (J2000)'
                ytext = 'Dec (J2000)'

        elif system['name'] == 'galactic':

            xtext = 'Galactic Longitude'
            ytext = 'Galactic Latitude'

        elif system['name'] == 'ecliptic':

            xtext = 'Ecliptic Longitude'
            ytext = 'Ecliptic Latitude'

        elif system['name'] == 'unknown':

            xunit = " (%s)" % self._wcs.cunit_x if self._wcs.cunit_x not in [
                "", None
            ] else ""
            yunit = " (%s)" % self._wcs.cunit_y if self._wcs.cunit_y not in [
                "", None
            ] else ""

            if len(self._wcs.cname_x) > 0:
                xtext = self._wcs.cname_x + xunit
            else:
                if len(self._wcs.ctype_x) == 8 and self._wcs.ctype_x[4] == '-':
                    xtext = self._wcs.ctype_x[:4].replace('-', '') + xunit
                else:
                    xtext = self._wcs.ctype_x + xunit

            if len(self._wcs.cname_y) > 0:
                ytext = self._wcs.cname_y + yunit
            else:
                if len(self._wcs.ctype_y) == 8 and self._wcs.ctype_y[4] == '-':
                    ytext = self._wcs.ctype_y[:4].replace('-', '') + yunit
                else:
                    ytext = self._wcs.ctype_y + yunit

        if system['inverted']:
            xtext, ytext = ytext, xtext

        self.set_xtext(xtext)
        self.set_ytext(ytext)

        self.set_xposition('bottom')
        self.set_yposition('left')

    @auto_refresh
    def set_xtext(self, label):
        """
        Set the x-axis label text
        """
        self._xlabel1 = self._ax1.set_xlabel(label)
        self._xlabel2 = self._ax2.set_xlabel(label)

    @auto_refresh
    def set_ytext(self, label):
        """
        Set the y-axis label text
        """
        self._ylabel1 = self._ax1.set_ylabel(label)
        self._ylabel2 = self._ax2.set_ylabel(label)

    @auto_refresh
    def set_xpad(self, pad):
        """
        Set the x-axis label displacement, in points
        """
        self._xlabel1 = self._ax1.set_xlabel(self._xlabel1.get_text(),
                                             labelpad=pad)
        self._xlabel2 = self._ax2.set_xlabel(self._xlabel2.get_text(),
                                             labelpad=pad)

    @auto_refresh
    def set_ypad(self, pad):
        """
        Set the y-axis label displacement, in points
        """
        self._ylabel1 = self._ax1.set_ylabel(self._ylabel1.get_text(),
                                             labelpad=pad)
        self._ylabel2 = self._ax2.set_ylabel(self._ylabel2.get_text(),
                                             labelpad=pad)

    @auto_refresh
    @fixdocstring
    def set_font(self,
                 family=None,
                 style=None,
                 variant=None,
                 stretch=None,
                 weight=None,
                 size=None,
                 fontproperties=None):
        """
        Set the font of the axis labels

        Optional Keyword Arguments:

        common: family, style, variant, stretch, weight, size, fontproperties

        Default values are set by matplotlib or previously set values if
        set_font has already been called. Global default values can be set by
        editing the matplotlibrc file.
        """

        if family:
            self._label_fontproperties.set_family(family)

        if style:
            self._label_fontproperties.set_style(style)

        if variant:
            self._label_fontproperties.set_variant(variant)

        if stretch:
            self._label_fontproperties.set_stretch(stretch)

        if weight:
            self._label_fontproperties.set_weight(weight)

        if size:
            self._label_fontproperties.set_size(size)

        if fontproperties:
            self._label_fontproperties = fontproperties

        self._xlabel1.set_fontproperties(self._label_fontproperties)
        self._xlabel2.set_fontproperties(self._label_fontproperties)
        self._ylabel1.set_fontproperties(self._label_fontproperties)
        self._ylabel2.set_fontproperties(self._label_fontproperties)

    @auto_refresh
    def show(self):
        """
        Show the x- and y-axis labels
        """
        self.show_x()
        self.show_y()

    @auto_refresh
    def hide(self):
        """
        Hide the x- and y-axis labels
        """
        self.hide_x()
        self.hide_y()

    @auto_refresh
    def show_x(self):
        """
        Show the x-axis label
        """
        if self._xposition == 'bottom':
            self._xlabel1.set_visible(True)
        else:
            self._xlabel2.set_visible(True)

    @auto_refresh
    def hide_x(self):
        """
        Hide the x-axis label
        """
        if self._xposition == 'bottom':
            self._xlabel1.set_visible(False)
        else:
            self._xlabel2.set_visible(False)

    @auto_refresh
    def show_y(self):
        """
        Show the y-axis label
        """
        if self._yposition == 'left':
            self._ylabel1.set_visible(True)
        else:
            self._ylabel2.set_visible(True)

    @auto_refresh
    def hide_y(self):
        """
        Hide the y-axis label
        """
        if self._yposition == 'left':
            self._ylabel1.set_visible(False)
        else:
            self._ylabel2.set_visible(False)

    @auto_refresh
    def set_xposition(self, position):
        "Set the position of the x-axis label ('top' or 'bottom')"
        if position == 'bottom':
            self._xlabel1.set_visible(True)
            self._xlabel2.set_visible(False)
        elif position == 'top':
            self._xlabel1.set_visible(False)
            self._xlabel2.set_visible(True)
        else:
            raise ValueError("position should be one of 'top' or 'bottom'")
        self._xposition = position

    @auto_refresh
    def set_yposition(self, position):
        "Set the position of the y-axis label ('left' or 'right')"
        if position == 'left':
            self._ylabel1.set_visible(True)
            self._ylabel2.set_visible(False)
        elif position == 'right':
            self._ylabel1.set_visible(False)
            self._ylabel2.set_visible(True)
        else:
            raise ValueError("position should be one of 'left' or 'right'")
        self._yposition = position
Esempio n. 32
0
def plotParameters(MajorF, MeanP, BurstPos, width, height, PixelArea, HullArea, HullVolume, pp, Title, analysis,
                   nbr_Burst=None, show=False, txt_data_temp=None, txt_data_global=None):
    # Copy of reference axis.
    nbr_Burst_aux = list(nbr_Burst)

    # Fonts
    # specify Font properties with fontmanager---------------------------------------------------
    font0 = FontProperties()
    font0.set_weight('medium')
    font0.set_family('monospace')
    # Specify Font properties of Legends
    font1 = FontProperties()
    font1.set_weight('normal')
    font1.set_family('sans-serif')
    font1.set_style('italic')
    font1.set_size(12)
    # Specify font properties of Titles
    font2 = FontProperties()
    font2.set_size(15)
    font2.set_family('sans-serif')
    font2.set_weight('medium')
    font2.set_style('italic')

    # Specify plot parameters
    # color
    face_color_r = 248 / 255.0
    face_color_g = 247 / 255.0
    face_color_b = 249 / 255.0

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

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

    smooth_factor = 0.05
    scale_factor = 5

    # Major Frequency Plot.
    fig1 = plt.figure(subplotpars=pars)
    fig1.set_facecolor((face_color_r, face_color_g, face_color_b))
    fig1.set_dpi(96)
    fig1.set_figheight(1080 / 96)
    fig1.set_figwidth(1920 / 96)
    fig1.suptitle(Title)
    # fig1.subplotpars(pars)

    # Figure Structure.
    ax11 = plt.subplot(3, 1, 1)
    r, m, y, MajorF, nbr_Burst_aux = plotParam(nbr_Burst, MajorF, ax11, 'Major Frequency', 'Major Frequency', 'Hz',
                                               font1, font2)
    # r, m, y = plotParam(nbr_Burst, MajorF, ax11, 'Major Frequency', 'Major Frequency', 'Hz', font1, font2)

    # Txt data storage.
    if analysis in [2, 4, 5]:
        # Complete txt data array.
        txt_data_temp.append("Major Frequency")
        txt_data_temp.append(r)

    # Major Frequency Deviation from regression line.
    # Figure Segment 2.
    ax12 = plt.subplot(3, 1, 2)
    deviation = np.array(MajorF) - np.array(y)
    r, m, y = plotParam(nbr_Burst_aux, deviation, ax12, 'Major Frequency Deviation', 'Deviation', 'Hz', font1, font2)[
              :3]

    if analysis in [2, 4, 5]:
        # Complete txt data array.
        txt_data_temp.append("Major Frequency Deviation")
        txt_data_temp.append(r)

    # Figure Segment 3.
    ax13 = plt.subplot(3, 1, 3)
    absolute_deviation = np.absolute(deviation)
    r, m, y = plotParam(nbr_Burst_aux, absolute_deviation, ax13, 'Major Frequency Absolute Deviation',
                        'Absolute Deviation', 'Hz', font1, font2)[:3]

    if analysis in [2, 4, 5]:
        # Complete txt data array.
        txt_data_temp.append("Major Frequency Absolute Deviation")
        txt_data_temp.append(r)

    # Figure Creation.
    pp.savefig(fig1)
    # Release Memory.
    plt.close(fig1)

    # Smooth Phase.
    if smooth_thres_factor(len(MajorF), smooth_factor, scale_factor):
        fig10 = plt.figure(subplotpars=pars)
        fig10.set_facecolor((face_color_r, face_color_g, face_color_b))
        fig10.set_dpi(96)
        fig10.set_figheight(1080 / 96)
        fig10.set_figwidth(1920 / 96)
        # fig1.subplotpars(pars)

        # Major Frequency Plot Smooth Analysis.
        ax101 = plt.subplot(3, 1, 1)
        ax102 = plt.subplot(3, 1, 2)
        ax103 = plt.subplot(3, 1, 3)
        FlagValidation10 = plotSmooth(nbr_Burst_aux, MajorF, fig10, ax101, ax102, ax103, Title, 'Major Frequency',
                                      'Major Frequency', 'Hz', font1, font2, smooth_factor)

        if FlagValidation10 == True:
            # Figure Creation.
            pp.savefig(fig10)
            # Release Memory.
            plt.close(fig10)

    # Mean Power Plot.
    fig2 = plt.figure(subplotpars=pars)
    fig2.set_facecolor((face_color_r, face_color_g, face_color_b))
    fig2.set_dpi(96)
    fig2.set_figheight(1080 / 96)
    fig2.set_figwidth(1920 / 96)
    fig2.suptitle(Title)
    # fig1.subplotpars(pars)

    # Figure Structure.
    # Mean Power Plot.
    ax21 = plt.subplot(3, 1, 1)
    r, m, y, MeanP, nbr_Burst_aux = plotParam(nbr_Burst, MeanP, ax21, 'Mean Power', 'Mean Power', 'r.u.', font1, font2)

    # Txt data storage.
    if analysis in [2, 4, 5]:
        # Complete txt data array.
        txt_data_temp.append("Mean Power")
        txt_data_temp.append(r)

    # Mean Power Deviation from regression line.
    # Figure Segment 2.
    ax22 = plt.subplot(3, 1, 2)
    deviation = np.array(MeanP) - np.array(y)
    r, m, y = plotParam(nbr_Burst_aux, deviation, ax22, 'Mean Power Deviation', 'Deviation', 'r.u.', font1, font2)[:3]

    if analysis in [2, 4, 5]:
        # Complete txt data array.
        txt_data_temp.append("Mean Power Deviation")
        txt_data_temp.append(r)

    # Figure Segment 3.
    ax23 = plt.subplot(3, 1, 3)
    absolute_deviation = np.absolute(deviation)
    r, m, y = plotParam(nbr_Burst_aux, absolute_deviation, ax23, 'Mean Power Absolute Deviation', 'Absolute Deviation',
                        'r.u.', font1, font2)[:3]

    if analysis in [2, 4, 5]:
        # Complete txt data array.
        txt_data_temp.append("Mean Power Absolute Deviation")
        txt_data_temp.append(r)

    # Figure Creation.
    pp.savefig(fig2)
    # Release Memory.
    plt.close(fig2)

    # Smooth Phase.
    if smooth_thres_factor(len(MajorF), smooth_factor, scale_factor):
        fig20 = plt.figure(subplotpars=pars)
        fig20.set_facecolor((face_color_r, face_color_g, face_color_b))
        fig20.set_dpi(96)
        fig20.set_figheight(1080 / 96)
        fig20.set_figwidth(1920 / 96)
        # fig1.subplotpars(pars)

        # Mean Power Smooth Analysis.
        ax201 = plt.subplot(3, 1, 1)
        ax202 = plt.subplot(3, 1, 2)
        ax203 = plt.subplot(3, 1, 3)
        FlagValidation20 = plotSmooth(nbr_Burst_aux, MeanP, fig20, ax201, ax202, ax203, Title, 'Mean Power',
                                      'Mean Power', 'r.u.', font1, font2, smooth_factor)

        if FlagValidation20 == True:
            # Figure Creation.
            pp.savefig(fig20)
            # Release Memory.
            plt.close(fig20)

    # Centroid Position Plot.
    fig3 = plt.figure(subplotpars=pars)
    fig3.set_facecolor((face_color_r, face_color_g, face_color_b))
    fig3.set_dpi(96)
    fig3.set_figheight(1080 / 96)
    fig3.set_figwidth(1920 / 96)
    fig3.suptitle(Title)
    # fig1.subplotpars(pars)

    # Figure Structure.
    # Centroid Position Plot.
    # Final Stage of data manipulation (Removal of null [] entries).
    ax31 = plt.subplot(3, 1, 1)
    val_ent = np.where(np.array(BurstPos) != False)[0]
    nbr_Burst_aux = np.array(nbr_Burst)[val_ent]
    BurstPos_aux = np.multiply(np.array(BurstPos)[val_ent], 100)

    ax31.set_title('Centroid Position Over The Pedal Cycle', fontproperties=font2)  # limit from 0 and 1
    ax31.plot(nbr_Burst_aux, BurstPos_aux)
    ax31.set_ylim((0, 100))
    ax31.set_ylabel("Centroid Position (% of pedal Cycle)", fontproperties=font1)
    ax31.set_xlabel("Burst/Set of Bursts", fontproperties=font1)
    ax31.set_xlim(0)
    ax31.set_ylim(min(BurstPos_aux) - 0.10 * (max(BurstPos_aux) - min(BurstPos_aux)),
                  max(BurstPos_aux) + 0.10 * (max(BurstPos_aux) - min(BurstPos_aux)))

    # Plot of the regression line.
    x, y, r, m = plotRegline(nbr_Burst_aux, BurstPos_aux)
    ax31.plot(x, y)
    ax31.text(nbr_Burst_aux[len(nbr_Burst_aux) - 1], max(np.multiply(BurstPos, 100)),
              "Corr. Coeff. (r^2) = " + str(round(r, 2)) + "\nSlope (m) = " + str(round(m, 2)),
              bbox=dict(facecolor='white'), fontsize=8)

    if analysis in [2, 4, 5]:
        # Complete txt data array.
        txt_data_temp.append("Centroid Position (% of pedal cycle)")
        txt_data_temp.append(r)

    # Centroid Position Deviation from regression line.
    # Figure Segment 2.
    ax32 = plt.subplot(3, 1, 2)
    deviation = np.array(BurstPos_aux) - np.array(y)
    r, m, y = plotParam(nbr_Burst_aux, deviation, ax32, 'Centroid Position Deviation', 'Deviation', 'r.u.', font1,
                        font2)[:3]

    if analysis in [2, 4, 5]:
        # Complete txt data array.
        txt_data_temp.append("Centroid Position Deviation")
        txt_data_temp.append(r)

    # Figure Segment 3.
    ax33 = plt.subplot(3, 1, 3)
    absolute_deviation = np.absolute(deviation)
    r, m, y = plotParam(nbr_Burst_aux, absolute_deviation, ax33, 'Centroid Position Absolute Deviation',
                        'Absolute Deviation', 'r.u.', font1, font2)[:3]

    if analysis in [2, 4, 5]:
        # Complete txt data array.
        txt_data_temp.append("Centroid Position Absolute Deviation")
        txt_data_temp.append(r)

    # Figure Creation.
    pp.savefig(fig3)
    # Release Memory.
    plt.close(fig3)

    # Smooth Phase.
    if smooth_thres_factor(len(MajorF), smooth_factor, scale_factor):
        # Centroid Position Plot - Smooth Analysis.
        fig30 = plt.figure(subplotpars=pars)
        fig30.set_dpi(96)
        fig30.set_figheight(1080 / 96)
        fig30.set_figwidth(1920 / 96)

        ax301 = plt.subplot(3, 1, 1)
        ax302 = plt.subplot(3, 1, 2)
        ax303 = plt.subplot(3, 1, 3)
        FlagValidation30 = plotSmooth(nbr_Burst_aux, BurstPos_aux, fig30, ax301, ax302, ax303, Title,
                                      'Centroid Position', 'Centroid Position', '% of pedal Cycle', font1, font2,
                                      smooth_factor)

        if FlagValidation30 == True:
            # Figure Creation.
            pp.savefig(fig30)
            # Release Memory.
            plt.close(fig30)

    if analysis != 4:
        # Time Dispersion Plot.
        fig4 = plt.figure(subplotpars=pars)
        fig4.set_dpi(96)
        fig4.set_figheight(1080 / 96)
        fig4.set_figwidth(1920 / 96)
        fig4.suptitle(Title)

        # Figure Structure.
        ax41 = plt.subplot(3, 1, 1)
        r, m, y, width, nbr_Burst_aux = plotParam(nbr_Burst, width, ax41, 'Time Dispersion', 'Width Amplitude', 'r.u.',
                                                  font1, font2)

        # Txt Data Storage.
        if analysis in [2, 4, 5]:
            # Complete txt data array.
            txt_data_temp.append("Time Dispersion")
            txt_data_temp.append(r)

        # Time Dispersion Deviation from regression line.
        # Figure Segment 2.
        ax42 = plt.subplot(3, 1, 2)
        deviation = np.array(width) - np.array(y)
        r, m, y = plotParam(nbr_Burst_aux, deviation, ax42, 'Time Dispersion Deviation', 'Deviation', 'r.u.', font1,
                            font2)[:3]

        # Txt data storage.
        if analysis in [2, 4, 5]:
            # Complete txt data array.
            txt_data_temp.append("Time Dispersion Deviation")
            txt_data_temp.append(r)

        # Figure Segment 3.
        ax43 = plt.subplot(3, 1, 3)
        absolute_deviation = np.absolute(deviation)
        r, m, y = plotParam(nbr_Burst_aux, absolute_deviation, ax43, 'Time Dispersion Absolute Deviation',
                            'Absolute Deviation', 'r.u.', font1, font2)[:3]

        # Txt data storage.
        if analysis in [2, 4, 5]:
            # Complete txt data array.
            txt_data_temp.append("Time Dispersion Absolute Deviation")
            txt_data_temp.append(r)

        # Figure Creation.
        pp.savefig(fig4)
        # Release Memory.
        plt.close(fig4)

        # Smooth Phase.
        if smooth_thres_factor(len(MajorF), smooth_factor, scale_factor):
            # Temporal Dispersion Plot - Smooth Analysis.
            fig40 = plt.figure(subplotpars=pars)
            fig40.set_dpi(96)
            fig40.set_figheight(1080 / 96)
            fig40.set_figwidth(1920 / 96)

            ax401 = plt.subplot(3, 1, 1)
            ax402 = plt.subplot(3, 1, 2)
            ax403 = plt.subplot(3, 1, 3)
            FlagValidation40 = plotSmooth(nbr_Burst_aux, width, fig40, ax401, ax402, ax403, Title, 'Time Dispersion',
                                          'Width Amplitude', 'r.u.', font1, font2, smooth_factor)

            if FlagValidation40 == True:
                # Figure Creation.
                pp.savefig(fig40)
                # Release Memory.
                plt.close(fig40)

        # Frequency Dispersion Plot.
        fig5 = plt.figure(subplotpars=pars)
        fig5.set_dpi(96)
        fig5.set_figheight(1080 / 96)
        fig5.set_figwidth(1920 / 96)
        fig5.suptitle(Title)

        # Figure Structure.
        ax51 = plt.subplot(3, 1, 1)
        r, m, y, height, nbr_Burst_aux = plotParam(nbr_Burst, height, ax51, 'Frequency Dispersion', 'Frequency Range',
                                                   'Hz', font1, font2)

        # Txt data storage.
        if analysis in [2, 4, 5]:
            # Complete txt data array.
            txt_data_temp.append("Frequency Dispersion")
            txt_data_temp.append(r)

        # Frequency Dispersion Deviation from regression line.
        # Figure Segment 2.
        ax52 = plt.subplot(3, 1, 2)
        deviation = np.array(height) - np.array(y)
        r, m, y = plotParam(nbr_Burst_aux, deviation, ax52, 'Frequency Dispersion Deviation', 'Deviation', 'Hz', font1,
                            font2)[:3]

        # Txt data storage.
        if analysis in [2, 4, 5]:
            # Complete txt data array.
            txt_data_temp.append("Frequency Dispersion Deviation")
            txt_data_temp.append(r)

        # Figure Segment 3.
        ax53 = plt.subplot(3, 1, 3)
        absolute_deviation = np.absolute(deviation)
        r, m, y = plotParam(nbr_Burst_aux, absolute_deviation, ax53, 'Frequency Dispersion Absolute Deviation',
                            'Absolute Deviation', 'Hz', font1, font2)[:3]

        # Txt data storage.
        if analysis in [2, 4, 5]:
            # Complete txt data array.
            txt_data_temp.append("Frequency Dispersion Absolute Deviation")
            txt_data_temp.append(r)

        # Figure Creation.
        pp.savefig(fig5)
        # Release Memory.
        plt.close(fig5)

        # Smooth Phase.
        if smooth_thres_factor(len(MajorF), smooth_factor, scale_factor):
            # Frequency Dispersion Plot - Smooth Analysis.
            fig50 = plt.figure(subplotpars=pars)
            fig50.set_dpi(96)
            fig50.set_figheight(1080 / 96)
            fig50.set_figwidth(1920 / 96)

            ax501 = plt.subplot(3, 1, 1)
            ax502 = plt.subplot(3, 1, 2)
            ax503 = plt.subplot(3, 1, 3)
            FlagValidation50 = plotSmooth(nbr_Burst_aux, height, fig50, ax501, ax502, ax503, Title,
                                          'Frequency Dispersion', 'Frequency Range', 'Hz', font1, font2, smooth_factor)

            if FlagValidation50 == True:
                # Figure Creation.
                pp.savefig(fig50)
                # Release Memory.
                plt.close(fig50)

        # Area in Pixels Plot.
        fig6 = plt.figure(subplotpars=pars)
        fig6.set_dpi(96)
        fig6.set_figheight(1080 / 96)
        fig6.set_figwidth(1920 / 96)
        fig6.suptitle(Title)

        # Figure Structure.
        ax61 = plt.subplot(3, 1, 1)
        r, m, y, PixelArea, nbr_Burst_aux = plotParam(nbr_Burst, PixelArea, ax61, 'Area in Pixels', 'Area', '#Pixels',
                                                      font1, font2)

        # Txt Data Storage.
        if analysis in [2, 4, 5]:
            # Complete txt data array.
            txt_data_temp.append("Area in Pixels")
            txt_data_temp.append(r)

        # Area in Pixels Deviation from regression line.
        # Figure Segment 2.
        ax62 = plt.subplot(3, 1, 2)
        deviation = np.array(PixelArea) - np.array(y)
        r, m, y = plotParam(nbr_Burst_aux, deviation, ax62, 'Area in Pixels Deviation', 'Deviation', '#Pixels', font1,
                            font2)[:3]

        if analysis in [2, 4, 5]:
            # Complete txt data array.
            txt_data_temp.append("Area in Pixels Deviation")
            txt_data_temp.append(r)

        # Figure Segment 3.
        ax63 = plt.subplot(3, 1, 3)
        absolute_deviation = np.absolute(deviation)
        r, m, y = plotParam(nbr_Burst_aux, absolute_deviation, ax63, 'Area in Pixels Absolute Deviation',
                            'Absolute Deviation', '#Pixels', font1, font2)[:3]

        # Txt data storage.
        if analysis in [2, 4, 5]:
            # Complete txt data array.
            txt_data_temp.append("Area in Pixels Absolute Deviation")
            txt_data_temp.append(r)

        # Figure Creation.
        pp.savefig(fig6)
        # Release Memory.
        plt.close(fig6)

        # Smooth Phase.
        if smooth_thres_factor(len(MajorF), smooth_factor, scale_factor):
            # Pixel Area Plot - Smooth Analysis.
            fig60 = plt.figure(subplotpars=pars)
            fig60.set_dpi(96)
            fig60.set_figheight(1080 / 96)
            fig60.set_figwidth(1920 / 96)

            ax601 = plt.subplot(3, 1, 1)
            ax602 = plt.subplot(3, 1, 2)
            ax603 = plt.subplot(3, 1, 3)
            FlagValidation60 = plotSmooth(nbr_Burst_aux, PixelArea, fig60, ax601, ax602, ax603, Title, 'Area in Pixels',
                                          'Area in Pixels', '#Pixels', font1, font2, smooth_factor)

            if FlagValidation60 == True:
                # Figure Creation.
                pp.savefig(fig60)
                # Release Memory.
                plt.close(fig60)

        # Convex Hull Area Plot.
        fig7 = plt.figure(subplotpars=pars)
        fig7.set_dpi(96)
        fig7.set_figheight(1080 / 96)
        fig7.set_figwidth(1920 / 96)
        fig7.suptitle(Title)

        # Figure Structure.
        ax71 = plt.subplot(3, 1, 1)
        r, m, y, HullArea, nbr_Burst_aux = plotParam(nbr_Burst, HullArea, ax71, 'Convex Hull Area', 'Area', 'r.u.',
                                                     font1, font2)

        # Txt data storage.
        if analysis in [2, 4, 5]:
            # Complete txt data array.
            txt_data_temp.append("Convex Hull Area")
            txt_data_temp.append(r)

        # Convex Hull Area Deviation from regression line.
        # Figure Segment 2.
        ax72 = plt.subplot(3, 1, 2)
        deviation = np.array(HullArea) - np.array(y)
        r, m, y = plotParam(nbr_Burst_aux, deviation, ax72, 'Convex Hull Area Deviation', 'Deviation', 'r.u.', font1,
                            font2)[:3]

        # Txt data storage.
        if analysis in [2, 4, 5]:
            # Complete txt data array.
            txt_data_temp.append("Convex Hull Area Deviation")
            txt_data_temp.append(r)

        # Figure Segment 3.
        ax73 = plt.subplot(3, 1, 3)
        absolute_deviation = np.absolute(deviation)
        r, m, y = plotParam(nbr_Burst_aux, absolute_deviation, ax73, 'Convex Hull Area Absolute Deviation',
                            'Absolute Deviation', 'r.u.', font1, font2)[:3]

        # Txt data storage.
        if analysis in [2, 4, 5]:
            # Complete txt data array.
            txt_data_temp.append("Convex Hull Area Absolute Deviation")
            txt_data_temp.append(r)

        # Figure Creation.
        pp.savefig(fig7)
        # Release Memory.
        plt.close(fig7)

        # Smooth Phase.
        if smooth_thres_factor(len(MajorF), smooth_factor, scale_factor):
            # Convex Hull Area Plot - Smooth Analysis.
            fig70 = plt.figure(subplotpars=pars)
            fig70.set_dpi(96)
            fig70.set_figheight(1080 / 96)
            fig70.set_figwidth(1920 / 96)

            ax701 = plt.subplot(3, 1, 1)
            ax702 = plt.subplot(3, 1, 2)
            ax703 = plt.subplot(3, 1, 3)
            FlagValidation70 = plotSmooth(nbr_Burst_aux, HullArea, fig70, ax701, ax702, ax703, Title, 'Area', 'Area',
                                          'r.u.', font1, font2, smooth_factor)

            if FlagValidation70 == True:
                # Figure Creation.
                pp.savefig(fig70)
                # Release Memory.
                plt.close(fig70)

        # Convex Hull Volume Plot.
        fig8 = plt.figure(subplotpars=pars)
        fig8.set_dpi(96)
        fig8.set_figheight(1080 / 96)
        fig8.set_figwidth(1920 / 96)
        fig8.suptitle(Title)

        # Figure Structure.
        ax81 = plt.subplot(3, 1, 1)
        r, m, y, HullVolume, nbr_Burst_aux = plotParam(nbr_Burst, HullVolume, ax81, 'Convex Hull Volume', 'Volume',
                                                       'r.u.', font1, font2)

        # Txt data storage.
        if analysis in [2, 4, 5]:
            # Complete txt data array.
            txt_data_temp.append("Convex Hull Volume")
            txt_data_temp.append(r)
            txt_data_global.append(txt_data_temp)

        # Convex Hull Volume Deviation from regression line.
        # Figure Segment 2.
        ax82 = plt.subplot(3, 1, 2)
        deviation = np.array(HullVolume) - np.array(y)
        r, m, y = plotParam(nbr_Burst_aux, deviation, ax82, 'Convex Hull Volume Deviation', 'Volume Deviation', 'r.u.',
                            font1, font2)[:3]

        # Txt data storage.
        if analysis in [2, 4, 5]:
            # Complete txt data array.
            txt_data_temp.append("Convex Hull Volume Deviation")
            txt_data_temp.append(r)

        # Figure Segment 3.
        ax83 = plt.subplot(3, 1, 3)
        absolute_deviation = np.absolute(deviation)
        r, m, y = plotParam(nbr_Burst_aux, absolute_deviation, ax83, 'Convex Hull Volume Absolute Deviation',
                            'Volume Absolute Deviation', 'r.u.', font1, font2)[:3]

        # Txt data storage.
        if analysis in [2, 4, 5]:
            # Complete txt data array.
            txt_data_temp.append("Convex Hull Volume Absolute Deviation")
            txt_data_temp.append(r)

        # Figure Creation.
        pp.savefig(fig8)
        # Release Memory.
        plt.close(fig8)

        # Smooth Phase.
        if smooth_thres_factor(len(MajorF), smooth_factor, scale_factor):
            # Hull Volume Plot - Smooth Analysis.
            fig80 = plt.figure(subplotpars=pars)
            fig80.set_dpi(96)
            fig80.set_figheight(1080 / 96)
            fig80.set_figwidth(1920 / 96)

            ax801 = plt.subplot(3, 1, 1)
            ax802 = plt.subplot(3, 1, 2)
            ax803 = plt.subplot(3, 1, 3)
            FlagValidation80 = plotSmooth(nbr_Burst_aux, HullVolume, fig80, ax801, ax802, ax803, Title,
                                          'Convex Hull Volume', 'Convex Hull Volume', 'r.u.', font1, font2,
                                          smooth_factor)

            if FlagValidation80 == True:
                # Figure Creation.
                pp.savefig(fig80)
                # Release Memory.
                plt.close(fig80)

    else:
        # Convex Hull Volume Plot.
        fig9 = plt.figure(subplotpars=pars)
        fig9.set_dpi(96)
        fig9.set_figheight(1080 / 96)
        fig9.set_figwidth(1920 / 96)
        fig9.suptitle(Title)

        # Figure Structure.
        ax91 = plt.subplot(3, 1, 1)
        r, m, y, HullVolume, nbr_Burst_aux = plotParam(nbr_Burst, HullVolume, ax91, 'Convex Hull Volume', 'Volume',
                                                       'r.u.', font1, font2)

        # Txt data storage.
        if analysis in [2, 4, 5]:
            # Complete txt data array.
            txt_data_temp.append("Convex Hull Volume")
            txt_data_temp.append(r)
            txt_data_global.append(txt_data_temp)

        # Convex Hull Volume Deviation from regression line.
        # Figure Segment 2.
        ax92 = plt.subplot(3, 1, 2)
        deviation = np.array(HullVolume) - np.array(y)
        r, m, y = plotParam(nbr_Burst_aux, deviation, ax92, 'Convex Hull Volume Deviation', 'Volume Deviation', 'r.u.',
                            font1, font2)[:3]

        # Txt data storage.
        if analysis in [2, 4, 5]:
            # Complete txt data array.
            txt_data_temp.append("Convex Hull Volume Deviation")
            txt_data_temp.append(r)

        # Figure Segment 3.
        ax93 = plt.subplot(3, 1, 3)
        absolute_deviation = np.absolute(deviation)
        r, m, y = plotParam(nbr_Burst_aux, absolute_deviation, ax93, 'Convex Hull Volume Absolute Deviation',
                            'Volume Absolute Deviation', 'r.u.', font1, font2)[:3]

        if analysis in [2, 4, 5]:
            # Complete txt data array.
            txt_data_temp.append("Convex Hull Volume Absolute Deviation")
            txt_data_temp.append(r)

        # Figure Creation.
        pp.savefig(fig9)
        # Release Memory.
        plt.close(fig9)

        # Smooth Phase.
        if smooth_thres_factor(len(MajorF), smooth_factor, scale_factor):
            # Convex Hull Volume Plot - Smooth Analysis.
            fig90 = plt.figure(subplotpars=pars)
            fig90.set_dpi(96)
            fig90.set_figheight(1080 / 96)
            fig90.set_figwidth(1920 / 96)

            ax901 = plt.subplot(3, 1, 1)
            ax902 = plt.subplot(3, 1, 2)
            ax903 = plt.subplot(3, 1, 3)
            FlagValidation90 = plotSmooth(nbr_Burst_aux, HullVolume, fig90, ax901, ax902, ax903, Title,
                                          'Convex Hull Volume', 'Convex Hull Volume', 'r.u.', font1, font2,
                                          smooth_factor)

            if FlagValidation90 == True:
                # Figure Creation.
                pp.savefig(fig90)
                # Release Memory.
                plt.close(fig90)

    plt.close('all')
    if show == True:
        plt.show()

    return txt_data_global
Esempio n. 33
0
class TickLabels(object):

    def __init__(self, parent):

        # Store references to axes
        self._ax1 = parent._ax1
        self._ax2 = parent._ax2
        self._wcs = parent._wcs
        self._figure = parent._figure

        # Set font
        self._label_fontproperties = FontProperties()

        self.set_style('plain')

        system, equinox, units = wcs_util.system(self._wcs)

        # Set default label format
        if system == 'equatorial':
            self.set_xformat("hh:mm:ss.ss")
            self.set_yformat("dd:mm:ss.s")
        else:
            self.set_xformat("ddd.dddd")
            self.set_yformat("dd.dddd")

        # Set major tick formatters
        fx1 = WCSFormatter(wcs=self._wcs, coord='x')
        fy1 = WCSFormatter(wcs=self._wcs, coord='y')
        self._ax1.xaxis.set_major_formatter(fx1)
        self._ax1.yaxis.set_major_formatter(fy1)

        fx2 = mpl.NullFormatter()
        fy2 = mpl.NullFormatter()
        self._ax2.xaxis.set_major_formatter(fx2)
        self._ax2.yaxis.set_major_formatter(fy2)

    @auto_refresh
    def set_xformat(self, format):
        '''
        Set the format of the x-axis tick labels:

            * ``ddd.ddddd`` - decimal degrees, where the number of decimal places can be varied
            * ``hh`` or ``dd`` - hours (or degrees)
            * ``hh:mm`` or ``dd:mm`` - hours and minutes (or degrees and arcminutes)
            * ``hh:mm:ss`` or ``dd:mm:ss`` - hours, minutes, and seconds (or degrees, arcminutes, and arcseconds)
            * ``hh:mm:ss.ss`` or ``dd:mm:ss.ss`` - hours, minutes, and seconds (or degrees, arcminutes, and arcseconds), where the number of decimal places can be varied.

        If one of these arguments is not specified, the format for that axis is left unchanged.
        '''
        try:
            if not self._ax1.xaxis.apl_auto_tick_spacing:
                au._check_format_spacing_consistency(format, self._ax1.xaxis.apl_tick_spacing)
        except au.InconsistentSpacing:
            warnings.warn("WARNING: Requested label format is not accurate enough to display ticks. The label format will not be changed.")
            return

        self._ax1.xaxis.apl_label_form = format
        self._ax2.xaxis.apl_label_form = format

    @auto_refresh
    def set_yformat(self, format):
        '''
        Set the format of the y-axis tick labels:

            * ``ddd.ddddd`` - decimal degrees, where the number of decimal places can be varied
            * ``hh`` or ``dd`` - hours (or degrees)
            * ``hh:mm`` or ``dd:mm`` - hours and minutes (or degrees and arcminutes)
            * ``hh:mm:ss`` or ``dd:mm:ss`` - hours, minutes, and seconds (or degrees, arcminutes, and arcseconds)
            * ``hh:mm:ss.ss`` or ``dd:mm:ss.ss`` - hours, minutes, and seconds (or degrees, arcminutes, and arcseconds), where the number of decimal places can be varied.

        If one of these arguments is not specified, the format for that axis is left unchanged.
        '''
        try:
            if not self._ax1.yaxis.apl_auto_tick_spacing:
                au._check_format_spacing_consistency(format, self._ax1.yaxis.apl_tick_spacing)
        except au.InconsistentSpacing:
            warnings.warn("WARNING: Requested label format is not accurate enough to display ticks. The label format will not be changed.")
            return

        self._ax1.yaxis.apl_label_form = format
        self._ax2.yaxis.apl_label_form = format

    @auto_refresh
    def set_style(self, style):
        """
        Set the format of the x-axis tick labels. This can be 'colons' or 'plain':

            * 'colons' uses colons as separators, for example 31:41:59.26 +27:18:28.1
            * 'plain' uses letters and symbols as separators, for example 31h41m59.26s +27º18'28.1"
        """

        if style is 'latex':
            warnings.warn("latex has now been merged with plain - whether or not to use LaTeX is controled through set_system_latex")
            style = 'plain'

        if not style in ['colons', 'plain']:
            raise Exception("Label style should be one of colons/plain")

        self._ax1.xaxis.apl_labels_style = style
        self._ax1.yaxis.apl_labels_style = style
        self._ax2.xaxis.apl_labels_style = style
        self._ax2.yaxis.apl_labels_style = style

    @auto_refresh
    @fixdocstring
    def set_font(self, family=None, style=None, variant=None, stretch=None, weight=None, size=None, fontproperties=None):
        """
        Set the font of the tick labels

        Optional Keyword Arguments:

        common: family, style, variant, stretch, weight, size, fontproperties

        Default values are set by matplotlib or previously set values if
        set_font has already been called. Global default values can be set by
        editing the matplotlibrc file.
        """

        if family:
            self._label_fontproperties.set_family(family)

        if style:
            self._label_fontproperties.set_style(style)

        if variant:
            self._label_fontproperties.set_variant(variant)

        if stretch:
            self._label_fontproperties.set_stretch(stretch)

        if weight:
            self._label_fontproperties.set_weight(weight)

        if size:
            self._label_fontproperties.set_size(size)

        if fontproperties:
            self._label_fontproperties = fontproperties

        for tick in self._ax1.get_xticklabels():
            tick.set_fontproperties(self._label_fontproperties)
        for tick in self._ax1.get_yticklabels():
            tick.set_fontproperties(self._label_fontproperties)
        for tick in self._ax2.get_xticklabels():
            tick.set_fontproperties(self._label_fontproperties)
        for tick in self._ax2.get_yticklabels():
            tick.set_fontproperties(self._label_fontproperties)

    @auto_refresh
    def show(self):
        """
        Show the x- and y-axis tick labels
        """
        self.show_x()
        self.show_y()

    @auto_refresh
    def hide(self):
        """
        Hide the x- and y-axis tick labels
        """
        self.hide_x()
        self.hide_y()

    @auto_refresh
    def show_x(self):
        """
        Show the x-axis tick labels
        """

        for tick in self._ax1.get_xticklabels():
            tick.set_visible(True)
        for tick in self._ax2.get_xticklabels():
            tick.set_visible(True)

    @auto_refresh
    def hide_x(self):
        """
        Hide the x-axis tick labels
        """

        for tick in self._ax1.get_xticklabels():
            tick.set_visible(False)
        for tick in self._ax2.get_xticklabels():
            tick.set_visible(False)

    @auto_refresh
    def show_y(self):
        """
        Show the y-axis tick labels
        """

        for tick in self._ax1.get_yticklabels():
            tick.set_visible(True)
        for tick in self._ax2.get_yticklabels():
            tick.set_visible(True)

    @auto_refresh
    def hide_y(self):
        """
        Hide the y-axis tick labels
        """

        for tick in self._ax1.get_yticklabels():
            tick.set_visible(False)
        for tick in self._ax2.get_yticklabels():
            tick.set_visible(False)

    @auto_refresh
    def set_xposition(self, position):
        "Set the position of the x-axis tick labels ('top' or 'bottom')"
        if position == 'bottom':
            fx1 = WCSFormatter(wcs=self._wcs, coord='x')
            self._ax1.xaxis.set_major_formatter(fx1)
            fx2 = mpl.NullFormatter()
            self._ax2.xaxis.set_major_formatter(fx2)
        elif position == 'top':
            fx1 = mpl.NullFormatter()
            self._ax1.xaxis.set_major_formatter(fx1)
            fx2 = WCSFormatter(wcs=self._wcs, coord='x')
            self._ax2.xaxis.set_major_formatter(fx2)
        else:
            raise Exception("position should be one of 'top' or 'bottom'")

    @auto_refresh
    def set_yposition(self, position):
        "Set the position of the y-axis tick labels ('left' or 'right')"
        if position == 'left':
            fy1 = WCSFormatter(wcs=self._wcs, coord='y')
            self._ax1.yaxis.set_major_formatter(fy1)
            fy2 = mpl.NullFormatter()
            self._ax2.yaxis.set_major_formatter(fy2)
        elif position == 'right':
            fy1 = mpl.NullFormatter()
            self._ax1.yaxis.set_major_formatter(fy1)
            fy2 = WCSFormatter(wcs=self._wcs, coord='y')
            self._ax2.yaxis.set_major_formatter(fy2)
        else:
            raise Exception("position should be one of 'left' or 'right'")

    def _cursor_position(self, x, y):

        xaxis = self._ax1.xaxis
        yaxis = self._ax1.yaxis

        xw, yw = wcs_util.pix2world(self._wcs, x, y)

        xw = au.Angle(degrees=xw, latitude=False)
        yw = au.Angle(degrees=yw, latitude=True)

        hours = 'h' in xaxis.apl_label_form

        if hours:
            xw = xw.tohours()

        if xaxis.apl_labels_style in ['plain', 'latex']:
            sep = ('d', 'm', 's')
            if hours:
                sep = ('h', 'm', 's')
        elif xaxis.apl_labels_style == 'colons':
            sep = (':', ':', '')

        xlabel = xw.tostringlist(format=xaxis.apl_label_form, sep=sep)

        if yaxis.apl_labels_style in ['plain', 'latex']:
            sep = ('d', 'm', 's')
            if hours:
                sep = ('h', 'm', 's')
        elif yaxis.apl_labels_style == 'colons':
            sep = (':', ':', '')

        ylabel = yw.tostringlist(format=yaxis.apl_label_form, sep=sep)

        return string.join(xlabel, "") + " " + string.join(ylabel, "")
Esempio n. 34
0
class AxisLabels(object):

    def __init__(self, parent):

        # Store references to axes
        self._ax1 = parent._ax1
        self._ax2 = parent._ax2
        self._wcs = parent._wcs
        self._figure = parent._figure

        # Save plotting parameters (required for @auto_refresh)
        self._parameters = parent._parameters

        # Set font
        self._label_fontproperties = FontProperties()

        self._ax2.yaxis.set_label_position('right')
        self._ax2.xaxis.set_label_position('top')

        system, equinox, units = wcs_util.system(self._wcs)

        if system['name'] == 'equatorial':

            if equinox == 'b1950':
                xtext = 'RA (B1950)'
                ytext = 'Dec (B1950)'
            else:
                xtext = 'RA (J2000)'
                ytext = 'Dec (J2000)'

        elif system['name'] == 'galactic':

            xtext = 'Galactic Longitude'
            ytext = 'Galactic Latitude'

        elif system['name'] == 'ecliptic':

            xtext = 'Ecliptic Longitude'
            ytext = 'Ecliptic Latitude'

        elif system['name'] == 'unknown':

            xunit = " (%s)" % self._wcs.cunit_x if self._wcs.cunit_x not in ["", None] else ""
            yunit = " (%s)" % self._wcs.cunit_y if self._wcs.cunit_y not in ["", None] else ""

            if len(self._wcs.cname_x) > 0:
                xtext = self._wcs.cname_x + xunit
            else:
                if len(self._wcs.ctype_x) == 8 and self._wcs.ctype_x[4] == '-':
                    xtext = self._wcs.ctype_x[:4].replace('-', '') + xunit
                else:
                    xtext = self._wcs.ctype_x + xunit

            if len(self._wcs.cname_y) > 0:
                ytext = self._wcs.cname_y + yunit
            else:
                if len(self._wcs.ctype_y) == 8 and self._wcs.ctype_y[4] == '-':
                    ytext = self._wcs.ctype_y[:4].replace('-', '') + yunit
                else:
                    ytext = self._wcs.ctype_y + yunit

        if system['inverted']:
            xtext, ytext = ytext, xtext

        self.set_xtext(xtext)
        self.set_ytext(ytext)

        self.set_xposition('bottom')
        self.set_yposition('left')

    @auto_refresh
    def set_xtext(self, label):
        """
        Set the x-axis label text
        """
        self._xlabel1 = self._ax1.set_xlabel(label)
        self._xlabel2 = self._ax2.set_xlabel(label)

    @auto_refresh
    def set_ytext(self, label):
        """
        Set the y-axis label text
        """
        self._ylabel1 = self._ax1.set_ylabel(label)
        self._ylabel2 = self._ax2.set_ylabel(label)

    @auto_refresh
    def set_xpad(self, pad):
        """
        Set the x-axis label displacement, in points
        """
        self._xlabel1 = self._ax1.set_xlabel(self._xlabel1.get_text(), labelpad=pad)
        self._xlabel2 = self._ax2.set_xlabel(self._xlabel2.get_text(), labelpad=pad)

    @auto_refresh
    def set_ypad(self, pad):
        """
        Set the y-axis label displacement, in points
        """
        self._ylabel1 = self._ax1.set_ylabel(self._ylabel1.get_text(), labelpad=pad)
        self._ylabel2 = self._ax2.set_ylabel(self._ylabel2.get_text(), labelpad=pad)

    @auto_refresh
    @fixdocstring
    def set_font(self, family=None, style=None, variant=None, stretch=None, weight=None, size=None, fontproperties=None):
        """
        Set the font of the axis labels

        Optional Keyword Arguments:

        common: family, style, variant, stretch, weight, size, fontproperties

        Default values are set by matplotlib or previously set values if
        set_font has already been called. Global default values can be set by
        editing the matplotlibrc file.
        """

        if family:
            self._label_fontproperties.set_family(family)

        if style:
            self._label_fontproperties.set_style(style)

        if variant:
            self._label_fontproperties.set_variant(variant)

        if stretch:
            self._label_fontproperties.set_stretch(stretch)

        if weight:
            self._label_fontproperties.set_weight(weight)

        if size:
            self._label_fontproperties.set_size(size)

        if fontproperties:
            self._label_fontproperties = fontproperties

        self._xlabel1.set_fontproperties(self._label_fontproperties)
        self._xlabel2.set_fontproperties(self._label_fontproperties)
        self._ylabel1.set_fontproperties(self._label_fontproperties)
        self._ylabel2.set_fontproperties(self._label_fontproperties)

    @auto_refresh
    def show(self):
        """
        Show the x- and y-axis labels
        """
        self.show_x()
        self.show_y()

    @auto_refresh
    def hide(self):
        """
        Hide the x- and y-axis labels
        """
        self.hide_x()
        self.hide_y()

    @auto_refresh
    def show_x(self):
        """
        Show the x-axis label
        """
        if self._xposition == 'bottom':
            self._xlabel1.set_visible(True)
        else:
            self._xlabel2.set_visible(True)

    @auto_refresh
    def hide_x(self):
        """
        Hide the x-axis label
        """
        if self._xposition == 'bottom':
            self._xlabel1.set_visible(False)
        else:
            self._xlabel2.set_visible(False)

    @auto_refresh
    def show_y(self):
        """
        Show the y-axis label
        """
        if self._yposition == 'left':
            self._ylabel1.set_visible(True)
        else:
            self._ylabel2.set_visible(True)

    @auto_refresh
    def hide_y(self):
        """
        Hide the y-axis label
        """
        if self._yposition == 'left':
            self._ylabel1.set_visible(False)
        else:
            self._ylabel2.set_visible(False)

    @auto_refresh
    def set_xposition(self, position):
        "Set the position of the x-axis label ('top' or 'bottom')"
        if position == 'bottom':
            self._xlabel1.set_visible(True)
            self._xlabel2.set_visible(False)
        elif position == 'top':
            self._xlabel1.set_visible(False)
            self._xlabel2.set_visible(True)
        else:
            raise ValueError("position should be one of 'top' or 'bottom'")
        self._xposition = position

    @auto_refresh
    def set_yposition(self, position):
        "Set the position of the y-axis label ('left' or 'right')"
        if position == 'left':
            self._ylabel1.set_visible(True)
            self._ylabel2.set_visible(False)
        elif position == 'right':
            self._ylabel1.set_visible(False)
            self._ylabel2.set_visible(True)
        else:
            raise ValueError("position should be one of 'left' or 'right'")
        self._yposition = position
Esempio n. 35
0
class AxisLabels(object):

    def __init__(self, parent):

        # Store references to axes
        self._ax1 = parent._ax1
        self._ax2 = parent._ax2
        self._wcs = parent._wcs
        self._figure = parent._figure

        # Set font
        self._label_fontproperties = FontProperties()

        self._ax2.yaxis.set_label_position('right')
        self._ax2.xaxis.set_label_position('top')

        system, equinox, units = wcs_util.system(self._wcs)

        if system == 'equatorial':
            if equinox == 'b1950':
                self.set_xtext('RA (B1950)')
                self.set_ytext('Dec (B1950)')
            else:
                self.set_xtext('RA (J2000)')
                self.set_ytext('Dec (J2000)')
        elif system == 'galactic':
            self.set_xtext('Galactic Longitude')
            self.set_ytext('Galactic Latitude')
        else:
            self.set_xtext('Ecliptic Longitude')
            self.set_ytext('Ecliptic Latitude')

        self.set_xposition('bottom')
        self.set_yposition('left')

    @auto_refresh
    def set_xtext(self, label):
        """
        Set the x-axis label text
        """
        self._xlabel1 = self._ax1.set_xlabel(label)
        self._xlabel2 = self._ax2.set_xlabel(label)

    @auto_refresh
    def set_ytext(self, label):
        """
        Set the y-axis label text
        """
        self._ylabel1 = self._ax1.set_ylabel(label)
        self._ylabel2 = self._ax2.set_ylabel(label)

    @auto_refresh
    def set_xpad(self, pad):
        """
        Set the x-axis label displacement, in points
        """
        self._xlabel1 = self._ax1.set_xlabel(self._xlabel1.get_text(), labelpad=pad)
        self._xlabel2 = self._ax2.set_xlabel(self._xlabel2.get_text(), labelpad=pad)

    @auto_refresh
    def set_ypad(self, pad):
        """
        Set the y-axis label displacement, in points
        """
        self._ylabel1 = self._ax1.set_ylabel(self._ylabel1.get_text(), labelpad=pad)
        self._ylabel2 = self._ax2.set_ylabel(self._ylabel2.get_text(), labelpad=pad)

    @auto_refresh
    @fixdocstring
    def set_font(self, family=None, style=None, variant=None, stretch=None, weight=None, size=None, fontproperties=None):
        """
        Set the font of the axis labels

        Optional Keyword Arguments:

        common: family, style, variant, stretch, weight, size, fontproperties

        Default values are set by matplotlib or previously set values if
        set_font has already been called. Global default values can be set by
        editing the matplotlibrc file.
        """

        if family:
            self._label_fontproperties.set_family(family)

        if style:
            self._label_fontproperties.set_style(style)

        if variant:
            self._label_fontproperties.set_variant(variant)

        if stretch:
            self._label_fontproperties.set_stretch(stretch)

        if weight:
            self._label_fontproperties.set_weight(weight)

        if size:
            self._label_fontproperties.set_size(size)

        if fontproperties:
            self._label_fontproperties = fontproperties

        self._xlabel1.set_fontproperties(self._label_fontproperties)
        self._xlabel2.set_fontproperties(self._label_fontproperties)
        self._ylabel1.set_fontproperties(self._label_fontproperties)
        self._ylabel2.set_fontproperties(self._label_fontproperties)

    @auto_refresh
    def show(self):
        """
        Show the x- and y-axis labels
        """
        self.show_x()
        self.show_y()

    @auto_refresh
    def hide(self):
        """
        Hide the x- and y-axis labels
        """
        self.hide_x()
        self.hide_y()

    @auto_refresh
    def show_x(self):
        """
        Show the x-axis label
        """
        if self._xposition == 'bottom':
            self._xlabel1.set_visible(True)
        else:
            self._xlabel2.set_visible(True)

    @auto_refresh
    def hide_x(self):
        """
        Hide the x-axis label
        """
        if self._xposition == 'bottom':
            self._xlabel1.set_visible(False)
        else:
            self._xlabel2.set_visible(False)

    @auto_refresh
    def show_y(self):
        """
        Show the y-axis label
        """
        if self._yposition == 'left':
            self._ylabel1.set_visible(True)
        else:
            self._ylabel2.set_visible(True)

    @auto_refresh
    def hide_y(self):
        """
        Hide the y-axis label
        """
        if self._yposition == 'left':
            self._ylabel1.set_visible(False)
        else:
            self._ylabel2.set_visible(False)

    @auto_refresh
    def set_xposition(self, position):
        "Set the position of the x-axis label ('top' or 'bottom')"
        if position == 'bottom':
            self._xlabel1.set_visible(True)
            self._xlabel2.set_visible(False)
        elif position == 'top':
            self._xlabel1.set_visible(False)
            self._xlabel2.set_visible(True)
        else:
            raise Exception("position should be one of 'top' or 'bottom'")
        self._xposition = position

    @auto_refresh
    def set_yposition(self, position):
        "Set the position of the y-axis label ('left' or 'right')"
        if position == 'left':
            self._ylabel1.set_visible(True)
            self._ylabel2.set_visible(False)
        elif position == 'right':
            self._ylabel1.set_visible(False)
            self._ylabel2.set_visible(True)
        else:
            raise Exception("position should be one of 'left' or 'right'")
        self._yposition = position
Esempio n. 36
0
def labelPanels(axl,
                axlist=None,
                font='Arial',
                fontsize=18,
                weight='normal',
                xy=(-0.05, 1.05),
                horizontalalignment='right',
                verticalalignment='bottom',
                rotation=0.):
    """
    Provide labeling of panels in a figure with multiple subplots (axes)
    
    Parameters
    ----------
    axl : list of axes objects
        If a single axis object is present, it will be converted to a list here.
    
    axlist : list of string labels (default : None)
        Contains a list of the string labels. If the default value is provided,
        the axes will be lettered in alphabetical sequence. 
    
    font : string (default : 'Arial')
        Name of a valid font to use for the panel labels
    
    fontsize : float (default : 18, in points)
        Font size to use for axis labeling
    
    weight : string (default : 'normal')
        Font weight to use for labels. 'Bold', 'Italic', and 'Normal' are options
    
    xy : tuple (default : (-0.05, 1.05))
        A tuple (x,y) indicating where the label should go relative to the axis frame.
        Values are normalized as a fraction of the frame size.
    
    Returns
    -------
        list of the annotations

    """
    if isinstance(axl, dict):
        axlist = axl.keys()
    axl = _ax_tolist(axl)
    # if isinstance(axl, dict):
    #     axt = [axl[x] for x in axl]
    #     axlist = axl.keys()
    #     axl = axt
    # if not isinstance(axl, list):
    #     axl = [axl]
    if axlist is None:
        axlist = string.uppercase[0:len(axl)]
    # assume we wish to go in sequence
    if len(axlist) > len(axl):
        raise ValueError(
            'axl must have more entries than axlist: got axl=%d and axlist=%d for axlist:'
            % (len(axl), len(axlist)), axlist)
    font = FontProperties()
    font.set_family('sans-serif')
    font.set_weight = weight
    font.set_size = fontsize
    font.set_style('normal')
    labels = []
    for i, ax in enumerate(axl):
        if i >= len(axlist):
            continue
        if ax is None:
            continue
        if isinstance(ax, list):
            ax = ax[0]
        ann = ax.annotate(axlist[i],
                          xy=xy,
                          xycoords='axes fraction',
                          annotation_clip=False,
                          color="k",
                          verticalalignment=verticalalignment,
                          weight=weight,
                          horizontalalignment=horizontalalignment,
                          fontsize=fontsize,
                          family='sans-serif',
                          rotation=rotation)
        labels.append(ann)
    return (labels)
Esempio n. 37
0
                      horizontalalignment='left')
ax.set_ylabel('Damped oscillation [V]')

plt.show()

##############################################################################
# All the labelling in this tutorial can be changed by manipulating the
# `matplotlib.font_manager.FontProperties` method, or by named kwargs to
# `~matplotlib.axes.Axes.set_xlabel`

from matplotlib.font_manager import FontProperties

font = FontProperties()
font.set_family('serif')
font.set_name('Times New Roman')
font.set_style('italic')

fig, ax = plt.subplots(figsize=(5, 3))
fig.subplots_adjust(bottom=0.15, left=0.2)
ax.plot(x1, y1)
ax.set_xlabel('time [s]', fontsize='large', fontweight='bold')
ax.set_ylabel('Damped oscillation [V]', fontproperties=font)

plt.show()

##############################################################################
# Finally, we can use native TeX rendering in all text objects and have
# multiple lines:

fig, ax = plt.subplots(figsize=(5, 3))
fig.subplots_adjust(bottom=0.2, left=0.2)
Esempio n. 38
0
ax.set_xlabel('time [s]', position=(0., 1e6), horizontalalignment='left')
ax.set_ylabel('Damped oscillation [V]')

plt.show()

##############################################################################
# All the labelling in this tutorial can be changed by manipulating the
# `matplotlib.font_manager.FontProperties` method, or by named kwargs to
# `~matplotlib.axes.Axes.set_xlabel`

from matplotlib.font_manager import FontProperties

font = FontProperties()
font.set_family('serif')
font.set_name('Times New Roman')
font.set_style('italic')

fig, ax = plt.subplots(figsize=(5, 3))
fig.subplots_adjust(bottom=0.15, left=0.2)
ax.plot(x1, y1)
ax.set_xlabel('time [s]', fontsize='large', fontweight='bold')
ax.set_ylabel('Damped oscillation [V]', fontproperties=font)

plt.show()

##############################################################################
# Finally, we can use native TeX rendering in all text objects and have
# multiple lines:

fig, ax = plt.subplots(figsize=(5, 3))
fig.subplots_adjust(bottom=0.2, left=0.2)
Esempio n. 39
0
import os
import random
import matplotlib
matplotlib.use('Agg')

import datetime
import pylab as P
import numpy as N

import orbit_plot_utils
from variables import data_dict
from variables import color_table

from matplotlib.font_manager import FontProperties
ital = FontProperties()
ital.set_style('italic')

au2km = 149597870.691
xpagescale = au2km*0.25
ypagescale = xpagescale/8.5*11.0
ymin = -ypagescale*1.75/11.0
ymax = ymin + ypagescale

pages = range(198)
xoffset = -xpagescale*4.75/8.5

# 72 (points/inch) * 8.5 (inches) / xpagescale (km)
km2points = 72*8.5/xpagescale
points2km = 1.0/km2points

planets = [i for i in data_dict if str(i)[-2:] == '99' and i > 0 and i < 1000]
Esempio n. 40
0
def calbar(axl,
           calbar=None,
           axesoff=True,
           orient='left',
           unitNames=None,
           fontsize=11,
           weight='normal',
           font='Arial'):
    """
        draw a calibration bar and label it. The calibration bar is defined as:
        [x0, y0, xlen, ylen]
    """
    axl = _ax_tolist(axl)
    # if type(axl) is not list:
    #     axl = [axl]
    for ax in axl:
        if ax is None:
            continue
        if axesoff is True:
            noaxes(ax)
        Hfmt = r'{:.0f}'
        if calbar[2] < 1.0:
            Hfmt = r'{:.1f}'
        Vfmt = r' {:.0f}'
        if calbar[3] < 1.0:
            Vfmt = r' {:.1f}'
        if unitNames is not None:
            Vfmt = Vfmt + r' ' + r'{:s}'.format(unitNames['y'])
            Hfmt = Hfmt + r' ' + r'{:s}'.format(unitNames['x'])
        # print(Vfmt, unitNames['y'])
        # print(Vfmt.format(calbar[3]))
        font = FontProperties()
        font.set_family('sans-serif')
        font.set_weight = weight
        font.set_size = fontsize
        font.set_style('normal')
        if calbar is not None:
            if orient == 'left':  # vertical part is on the left
                ax.plot([calbar[0], calbar[0], calbar[0] + calbar[2]],
                        [calbar[1] + calbar[3], calbar[1], calbar[1]],
                        color='k',
                        linestyle='-',
                        linewidth=1.5)
                ax.text(
                    calbar[0] + 0.05 * calbar[2],
                    calbar[1] + 0.5 * calbar[3],
                    Vfmt.format(calbar[3]),
                    horizontalalignment='left',
                    verticalalignment='center',
                    fontsize=fontsize,
                    weight=weight,
                    family='sans-serif',
                )
            elif orient == 'right':  # vertical part goes on the right
                ax.plot(
                    [calbar[0] + calbar[2], calbar[0] + calbar[2], calbar[0]],
                    [calbar[1] + calbar[3], calbar[1], calbar[1]],
                    color='k',
                    linestyle='-',
                    linewidth=1.5)
                ax.text(
                    calbar[0] + calbar[2] - 0.05 * calbar[2],
                    calbar[1] + 0.5 * calbar[3],
                    Vfmt.format(calbar[3]),
                    horizontalalignment='right',
                    verticalalignment='center',
                    fontsize=fontsize,
                    weight=weight,
                    family='sans-serif',
                )
            else:
                print "PlotHelpers.py: I did not understand orientation: %s" % (
                    orient)
                print "plotting as if set to left... "
                ax.plot([calbar[0], calbar[0], calbar[0] + calbar[2]],
                        [calbar[1] + calbar[3], calbar[1], calbar[1]],
                        color='k',
                        linestyle='-',
                        linewidth=1.5)
                ax.text(
                    calbar[0] + 0.05 * calbar[2],
                    calbar[1] + 0.5 * calbar[3],
                    Vfmt.format(calbar[3]),
                    horizontalalignment='left',
                    verticalalignment='center',
                    fontsize=fontsize,
                    weight=weight,
                    family='sans-serif',
                )
            ax.text(
                calbar[0] + calbar[2] * 0.5,
                calbar[1] - 0.1 * calbar[3],
                Hfmt.format(calbar[2]),
                horizontalalignment='center',
                verticalalignment='top',
                fontsize=fontsize,
                weight=weight,
                family='sans-serif',
            )
Esempio n. 41
0
def plot_res(data, mjd, phase, unc, name, color='b', scl=None):
    base_mjd = data['base_mjd']
    bp = data["best_parameters"]
    #p_period=1./bp['f0']
    p_period = 0.00273258863228
    pb_i = bp['pb_i']
    pb_o = bp['pb_o']
    tasc_i = bp["tasc_i"]
    tasc_o = bp["tasc_o"]
    microsec = 1e6 * p_period

    if scl is None:
        scale = microsec
    else:
        scale = scl

    #a0_format:
    im_width = 15
    my_width = 15
    mar_size = my_width * 0.28
    lab_size = my_width * 1.4
    tick_size = my_width * 0.66
    font_size = my_width * 1.8

    fig, ax1 = plt.subplots()
    ax2 = ax1.twiny()
    clr_grey = np.array([170, 183, 184]) / 255.0
    for i in range(0, 6):
        t = pb_o * i + tasc_o + base_mjd
        ax1.axvline(t, linestyle='--', color=clr_grey)

    for k in range(0, len(color)):
        tel = tel_transform(data, '%s' % name[k])
        err_clr, face_clr, mec_clr = color_fun(color[k])
        ax1.errorbar(mjd[tel.index],
                     phase[tel.index] * scale,
                     yerr=unc[tel.index] * scale,
                     marker="o",
                     linestyle='none',
                     mec=mec_clr,
                     markerfacecolor=face_clr,
                     color=err_clr,
                     markersize=mar_size)

    plt.rc('xtick', labelsize=lab_size)
    plt.rc('ytick', labelsize=lab_size)

    majorLocator = MultipleLocator(50)
    majorFormatter = FormatStrFormatter('%.0f')
    minorLocator = MultipleLocator(10)
    yearLocator = MultipleLocator(1)

    font0 = FontProperties()
    font0.set_size('%d' % font_size)
    font0.set_family('sans')
    font0.set_style('normal')
    font0.set_weight('bold')

    ax1.set_xlabel('MJD', fontproperties=font0)
    ax1.tick_params('x', colors='k', size=tick_size)
    ax1.tick_params('y', colors='k', size=tick_size)

    ax2.set_xlabel('Years', fontproperties=font0)
    ax2.tick_params('x', colors='k', size=tick_size)
    ax2.xaxis.set_major_formatter(majorFormatter)
    ax1.tick_params('x', colors='k', size=tick_size)
    if scale == microsec:
        ax1.set_ylabel(r'residuals ($\mu$s)', fontproperties=font0)
    else:
        ax1.set_ylabel(r'residuals', fontproperties=font0)
    ax2.xaxis.set_major_locator(yearLocator)

    ax1.set_xlim(base_mjd, base_mjd + 2010)

    d_n, d_x = ax1.get_xlim()
    ax2.set_xlim(day_to_year(d_n), day_to_year(d_x))
    print ax1.get_xlim()
    print ax2.get_xlim()

    plt.gcf().set_size_inches(im_width, im_width * 4. / 15.)

    return
Esempio n. 42
0
class Colorbar(object):

    def __init__(self, parent):
        self._figure = parent._figure
        self._colorbar_axes = None
        self._parent = parent

        # Save plotting parameters (required for @auto_refresh)
        self._parameters = parent._parameters

        self._base_settings = {}
        self._label_fontproperties = FontProperties()

    @auto_refresh
    def show(self, location='right', width=0.2, pad=0.05, ticks=None, labels=True, box=None, box_orientation='vertical'):
        '''
        Show a colorbar on the side of the image.

        Optional Keyword Arguments:

            *location*: [ string ]
                Where to place the colorbar. Should be one of 'left', 'right', 'top', 'bottom'.

            *width*: [ float ]
                The width of the colorbar relative to the canvas size.

            *pad*: [ float ]
                The spacing between the colorbar and the image relative to the canvas size.

            *ticks*: [ None or list ]
                The position of the ticks on the colorbar.

            *labels*: [ True or False ]
                Whether to show numerical labels.

            *box*: [ list ]
                A custom box within which to place the colorbar. This should
                be in the form [xmin, ymin, dx, dy] and be in relative figure
                units. This overrides the location argument.

            *box_orientation* [ str ]
                The orientation of the colorbar within the box. Can be
                'horizontal' or 'vertical'
        '''

        self._base_settings['location'] = location
        self._base_settings['width'] = width
        self._base_settings['pad'] = pad
        self._base_settings['ticks'] = ticks
        self._base_settings['labels'] = labels
        self._base_settings['box'] = box
        self._base_settings['box_orientation'] = box_orientation

        if self._parent.image:

            if self._colorbar_axes:
                self._parent._figure.delaxes(self._colorbar_axes)

            if box is None:

                divider = make_axes_locatable(self._parent._ax1)

                if location == 'right':
                    self._colorbar_axes = divider.new_horizontal(size=width, pad=pad, axes_class=maxes.Axes)
                    orientation = 'vertical'
                elif location == 'top':
                    self._colorbar_axes = divider.new_vertical(size=width, pad=pad, axes_class=maxes.Axes)
                    orientation = 'horizontal'
                elif location == 'left':
                    warnings.warn("Left colorbar not fully implemented")
                    self._colorbar_axes = divider.new_horizontal(size=width, pad=pad, pack_start=True, axes_class=maxes.Axes)
                    locator = divider.new_locator(nx=0, ny=0)
                    self._colorbar_axes.set_axes_locator(locator)
                    orientation = 'vertical'
                elif location == 'bottom':
                    warnings.warn("Bottom colorbar not fully implemented")
                    self._colorbar_axes = divider.new_vertical(size=width, pad=pad, pack_start=True, axes_class=maxes.Axes)
                    locator = divider.new_locator(nx=0, ny=0)
                    self._colorbar_axes.set_axes_locator(locator)
                    orientation = 'horizontal'
                else:
                    raise Exception("location should be one of: right/top")

                self._parent._figure.add_axes(self._colorbar_axes)

            else:

                self._colorbar_axes = self._parent._figure.add_axes(box)
                orientation = box_orientation

            self._colorbar = self._parent._figure.colorbar(self._parent.image, cax=self._colorbar_axes, orientation=orientation, ticks=ticks)

            if location == 'right':
                for tick in self._colorbar_axes.yaxis.get_major_ticks():
                    tick.tick1On = True
                    tick.tick2On = True
                    tick.label1On = False
                    tick.label2On = labels
            elif location == 'top':
                for tick in self._colorbar_axes.xaxis.get_major_ticks():
                    tick.tick1On = True
                    tick.tick2On = True
                    tick.label1On = False
                    tick.label2On = labels
            elif location == 'left':
                for tick in self._colorbar_axes.yaxis.get_major_ticks():
                    tick.tick1On = True
                    tick.tick2On = True
                    tick.label1On = labels
                    tick.label2On = False
            elif location == 'bottom':
                for tick in self._colorbar_axes.xaxis.get_major_ticks():
                    tick.tick1On = True
                    tick.tick2On = True
                    tick.label1On = labels
                    tick.label2On = False

        else:

            warnings.warn("No image is shown, therefore, no colorbar will be plotted")

    @auto_refresh
    def update(self):
        if self._colorbar_axes:
            self.show(**self._base_settings)

    @auto_refresh
    def hide(self):
        self._parent._figure.delaxes(self._colorbar_axes)
        self._colorbar_axes = None

    @auto_refresh
    def _remove(self):
        self._parent._figure.delaxes(self._colorbar_axes)

    # LOCATION AND SIZE

    @auto_refresh
    def set_location(self, location):
        '''
        Set the location of the colorbar. Should be one of 'left', 'right', 'top', 'bottom'.
        '''
        self._base_settings['location'] = location
        self.show(**self._base_settings)
        self.set_font(fontproperties=self._label_fontproperties)

    @auto_refresh
    def set_width(self, width):
        '''
        Set the width of the colorbar relative to the canvas size.
        '''
        self._base_settings['width'] = width
        self.show(**self._base_settings)
        self.set_font(fontproperties=self._label_fontproperties)

    @auto_refresh
    def set_pad(self, pad):
        '''
        Set the spacing between the colorbar and the image relative to the canvas size.
        '''
        self._base_settings['pad'] = pad
        self.show(**self._base_settings)
        self.set_font(fontproperties=self._label_fontproperties)

    @auto_refresh
    def set_ticks(self, ticks):
        '''
        Set the position of the ticks on the colorbar.
        '''
        self._base_settings['ticks'] = ticks
        self.show(**self._base_settings)
        self.set_font(fontproperties=self._label_fontproperties)

    @auto_refresh
    def set_labels(self, labels):
        '''
        Set whether to show numerical labels.
        '''
        self._base_settings['labels'] = labels
        self.show(**self._base_settings)
        self.set_font(fontproperties=self._label_fontproperties)

    @auto_refresh
    def set_box(self, box, box_orientation='vertical'):
        '''
        Set the box within which to place the colorbar. This should be in the
        form [xmin, ymin, dx, dy] and be in relative figure units. The
        orientation of the colorbar within the box can be controlled with the
        box_orientation argument.
        '''
        self._base_settings['box'] = box
        self._base_settings['box_orientation'] = box_orientation
        self.show(**self._base_settings)
        self.set_font(fontproperties=self._label_fontproperties)

    # FONT PROPERTIES

    @auto_refresh
    def set_label_properties(self, *args, **kwargs):
        warnings.warn("set_label_properties is deprecated - use set_font instead", DeprecationWarning)
        self.set_font(*args, **kwargs)

    @auto_refresh
    @fixdocstring
    def set_font(self, family=None, style=None, variant=None, stretch=None, weight=None, size=None, fontproperties=None):
        '''
        Set the font of the tick labels

        Optional Keyword Arguments:

        common: family, style, variant, stretch, weight, size, fontproperties

        Default values are set by matplotlib or previously set values if
        set_font has already been called. Global default values can be set by
        editing the matplotlibrc file.
        '''

        if family:
            self._label_fontproperties.set_family(family)

        if style:
            self._label_fontproperties.set_style(style)

        if variant:
            self._label_fontproperties.set_variant(variant)

        if stretch:
            self._label_fontproperties.set_stretch(stretch)

        if weight:
            self._label_fontproperties.set_weight(weight)

        if size:
            self._label_fontproperties.set_size(size)

        if fontproperties:
            self._label_fontproperties = fontproperties

        for label in self._colorbar_axes.get_xticklabels():
            label.set_fontproperties(self._label_fontproperties)
        for label in self._colorbar_axes.get_yticklabels():
            label.set_fontproperties(self._label_fontproperties)

    # FRAME PROPERTIES

    @auto_refresh
    def set_frame_linewidth(self, linewidth):
        '''
        Set the linewidth of the colorbar frame, in points
        '''
        warnings.warn("This method is not functional at this time")
        for key in self._colorbar_axes.spines:
            self._colorbar_axes.spines[key].set_linewidth(linewidth)

    @auto_refresh
    def set_frame_color(self, color):
        '''
        Set the color of the colorbar frame, in points
        '''
        warnings.warn("This method is not functional at this time")
        for key in self._colorbar_axes.spines:
            self._colorbar_axes.spines[key].set_edgecolor(color)
Esempio n. 43
0
def render_barchart(
        data_table, group_names, sample_names, axis_dims,
        fig_dims, file_out='barchart', filetype='PDF', colors=None,
        show_edge=True, legend=True, title=None, match_legend=True,
        frame=True, bar_width=0.8, x_axis=True, x_label=None,
        x_min=-0.5, x_tick_interval=1.0, y_axis=True,
        y_lims=[0, 1], y_tick_interval=0.2, y_tick_labels=None,
        y_label=None, legend_frame=False,
        legend_offset=None, font_angle=45, font_alignment='right',
        tick_font=None, label_font=None, legend_font=None,
        title_font=None, use_latex=False, rc_fam='sans-serif',
        rc_font=['Helvetica']):
    """Creates a stacked bar chart using the data in the category table.

    A single value bar chart can be created using a vector for data_table
    instead of a table.

    INPUTS:
        data_table -- a numpy array of the category information to be plotted
                    where the rows are the groups in the category and the
                    columns are the samples.
        group_names -- a list of the groups, corresponding to rows in the
                    data table

        sample_names -- a list of the sample names, corresponding to the
                    columns in the data table. The sample names must be string
                    objects.

        axis_dims -- a 2 x 2 numpy array giving the fraction of the figure
                    which should bound the axis. (row 1: [left, bottom], row 2:
                    [right, top] as a percentage of the figure space)

        fig_dims -- a 2 element tuple giving the width and height in inches of
                    the output figure.

        file_out -- a string giving the file path where the pie plot should be
                    saved.

        filetype -- a string describing the file format to save the output
                    file.  Possible values include 'PNG', 'PDF', 'EPS', and
                    'SVG'.
                    DEFAULT: PDF

        colors -- an n x 3 or n x 4 numpy array giving the desired color map.
                    Default is to color each wedge white. (array([[1, 1, 1]]))

        show_edge -- a binary value dictating whether or the edge should be
                    outlined in black.
                    DEFAULT: True

        legend -- a binary value indicating whether or not a legend should be
                    shown. This must be accounted for in the figure dimensions.
                    DEFAULT: True

        title -- a string giving a title to append to the figure. This must be
                    accounted for in the figure dimensions.
                    DEFAULT: None

        match_legend -- a binary value indicating whether the order of colors
                    in the plot should match the order of colors in the legend.
                    DEFAULT: True

        frame -- a binary value indicating whether or not the a frame should be
                    displayed around the axis
                    DEFAULT: True

        bar_width -- the fraction of the bar width to be occupied by the data.
                    DEFAULT: 0.8

        x_axis -- a binary value indicating whether or not the x-axis should be
                    labeled.
                    DEFAULT: True

        x_label -- a string describing the the data in the plot's x-axis. A
                    value of None leaves the axis label off.
                    DEFAULT: None

        x_min -- the minimum value for the x-axis. The maximum is determined by
                    the number of bars, where each bar is one unit away from
                    the next.
                    DEFAULT: 0.5

        x_tick_interval -- the spacing between the the plotted bars.
                    DEFAULT: 1.0

        y_axis -- a binary value indicating whether or not tick labels should
                    be shown on the y axis.
                    DEFAULT: True

        y_lims -- a 2 element list giving the minimum and maximum values for
                    the y axis.
                    DEFAULT: [0, 1]

        y_tick_interval -- the spacing between ticks on the y-axis.
                    DEFAULT: 0.2

        y_tick_labels -- a string with the labels for the y-ticks. If no value
                    is supplied, the labels are set up using the y-tick values.
                    DEFAULT: None

        y_label -- a string describing the data plotted on the y-axis. If None,
                    no string will be present.
                    DEFAULT: None

        legend_frame -- a binary value indicating whether a box will be
                    displayed around the legend.
                    DEFAULT: False

        legend_offset -- a two-element list giving the offset for the axes.
                    If this has a value of None, the legend will remain in the
                    original position.
                    DEFAULT: None

        font_angle -- the angle in degrees at which the x-axis text should be
                    displayed.
                    DEFAULT: 45

        font_alignment -- the horizontal alignment of the x axis labels. Values
                    may be 'left', 'right' or 'center'.
                    DEFAULT: 'right'

        tick_font -- a FontProperties object (dictionary) describing the
                    properties of the font. If None is supplied, the default is
                    to use the 15 pt normal sans-serif.
                    DEFAULT: None

        label_font -- a FontProperties object (dictionary) describing the
                    properties of the font. If None is supplied, the default is
                    to use the 20 pt italic sans-serif.
                    DEFAULT: None

        legend_font -- a FontProperties object (dictionary) describing the
                    properties of the font. If None is supplied, the default is
                    to use the 15 pt normal sans-serif.
                    DEFAULT: None

        title_font -- a FontProperties object (dictionary) describing the
                    properties of the font. If None is supplied, the default is
                    to use the 36 pt normal sans-serif.
                    DEFAULT: None

         use_latex -- a binary value indicating if matplotlib's ability to
                    render using LaTeX should be considered or not. If this is
                    the case, the supplied rc_fam and rc_font will be used.
                    DEFAULT: False

        rc_family -- the font family which should be used for LaTeX rendering.
                    Options are 'sans-serif', 'serif', 'cursive'.
                    DEFAULT: 'sans-serif'

        rc_font -- a list of the font(s) which should be used with latex
                    rendering.
                    DEFAULT: ['Helvetica']

    OUTPUT:
        The rendered figure is saved in the file_out location.
    """

    # Preforms a sanity checks that the provided data is good
    (table_height, table_width) = data_table.shape
    num_cats = len(group_names)
    num_samples = len(sample_names)

    if not table_height == num_cats:
        raise ValueError('The number of provided categories differ.')
    elif not table_width == num_samples:
        raise ValueError('The number of samples differ.')

    # Sets up the colormap
    num_colors = len(colors[:, 0])
    if num_colors is None:
        colormap = ones((table_height, 3))
    elif not isinstance(colors, ndarray):
        raise TypeError('The colormap must be a numpy array.')
    elif num_colors == 1:
        colormap = colors*ones((table_height, 1))
    elif num_colors >= table_height:
        colormap = colors
    else:
        raise ValueError('The color map cannot be determined. \nColors must '
                         'be a a list of n x 3 lists where n is the number of '
                         'patches being supplied or a single color to be used'
                         ' for all patches.')

    # Sets up the edge colormap
    if show_edge:
        edgecolor = zeros((num_cats, 3))
    else:
        edgecolor = colormap

    # Sets up the font properties for each of the label objects
    if label_font is None:
        label_font = FontProperties()
        label_font.set_size(20)
        label_font.set_family('sans-serif')
        label_font.set_style('italic')

    if legend_font is None:
        legend_font = FontProperties()
        legend_font.set_size(15)
        legend_font.set_family('sans-serif')

    if tick_font is None:
        tick_font = FontProperties()
        tick_font.set_size(15)
        tick_font.set_family('sans-serif')

    if title_font is None:
        title_font = FontProperties()
        title_font.set_size(30)
        title_font.set_family('sans-serif')

    # Sets up LateX rendering if desired
    if use_latex:
        rc('text', usetex=True)
        rc('font', **{'family': rc_fam, rc_fam: rc_font})

    # Sets up the x ticks.
    # Bar width is divided by two because the tick is assumed to be at the
    # center of the bar.
    x_tick = arange(num_samples*x_tick_interval)
    x_max = x_min + num_samples*x_tick_interval
    bar_left = x_tick - bar_width/2

    # Creates the x tick labels.
    if x_axis:
        x_text_labels = map(str, sample_names)
    else:
        x_text_labels = ['']*num_samples

    # Creates the y tick labels
    if y_tick_labels is None:
        y_tick_labels = arange(y_lims[1] + y_tick_interval, y_lims[0],
                               -y_tick_interval)
        y_tick_labels = y_tick_labels - y_tick_interval
        y_tick_labels[-1] = y_lims[0]

    num_y_ticks = len(y_tick_labels)

    if y_axis:
        y_text_labels = map(str, y_tick_labels)
    else:
        y_text_labels = ['']*num_y_ticks

    # Plots the data
    fig = plt.figure()
    fig.set_size_inches(fig_dims)
    ax1 = plt.axes(Bbox(axis_dims))

    patches_watch = []
    for plot_count, category in enumerate(data_table):
        bottom_bar = sum(data_table[0:plot_count, :], 0)
        faces = ax1.bar(bar_left, category, bar_width, bottom_bar,
                        color=colormap[plot_count, :],
                        edgecolor=edgecolor[plot_count, :])
        patches_watch.append(faces[0])

    # The y-axis is reversed so the labels are in the same order as the
    # colors in the legend
    if match_legend:
        plt.axis([x_min, x_max, y_lims[1], y_lims[0]])

    # Sets up y labels if they are desired.

    y_tick_labels = ax1.set_yticklabels(y_text_labels,
                                        fontproperties=tick_font)
    if y_label is not None:
        ax1.set_ylabel(y_label, fontproperties=label_font)

    # Set the x-axis labels
    ax1.set_xticks(x_tick)
    ax1.set_xticklabels(x_text_labels,
                        rotation=font_angle,
                        horizontalalignment='right',
                        fontproperties=label_font)

    if x_label is not None:
            ax1.set_xlabel(x_label, fontproperties=label_font)

    if legend:
        leg = plt.legend(patches_watch, group_names, prop=legend_font)
        if legend_offset is not None:
            leg.set_bbox_to_anchor((legend_offset[0], legend_offset[1]))

    if isinstance(title, str):
        plt.title(title, fontproperties=title_font)

    plt.savefig(file_out, format=filetype)
Esempio n. 44
0
from datatools import batch_data, loadFromH5, buileToH5
from model import FCN_Handnet
from modeltools import *
import tensorflow as tf
import tensorlayer as tl
import win_unicode_console, os
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.font_manager import FontProperties
win_unicode_console.enable()

font_axis = FontProperties()
font_axis.set_family('serif')
font_axis.set_name('Times New Roman')
font_axis.set_style('italic')
font_axis.set_size(20)

font_title = FontProperties()
font_title.set_family('serif')
font_title.set_name('Times New Roman')
font_title.set_style('italic')
font_title.set_size(25)


def findmax(label, imgsize=48):
    m = label.shape[0]
    label_flat = label.reshape(m, imgsize**2)
    index = np.argmax(label_flat, axis=1)[:, np.newaxis]
    return np.concatenate([index // imgsize, index % imgsize], axis=1)

Esempio n. 45
0
from matresdev.db.simdb import \
    SimDB

from matresdev.db.simdb.simdb_class import \
    SimDBClass, SimDBClassExt

simdb = SimDB()

from pickle import dump, load

from matplotlib.font_manager import FontProperties
font = FontProperties()
font.set_name('Script MT')
font.set_family('serif')
font.set_style('normal')
font.set_size('large')
font.set_variant('normal')
font.set_weight('medium')

def format_plot(axes, xlim=None, ylim=None, xlabel='', ylabel=''):
    '''format 2d-plot black and with with times legends 
    '''
    #-------------------------------------------------------------------
    # configure the style of the font to be used for labels and ticks
    #-------------------------------------------------------------------
    #
    from matplotlib.font_manager import FontProperties
    font = FontProperties()
    font.set_name('Script MT')
    font.set_family('serif')