def main(): """GO!""" font0 = FontProperties() font0.set_weight('bold') # email from Javed dated Sep 22, 2016 df = pd.read_excel("/tmp/ames.xlsx") (fig, ax) = plt.subplots(1, 1) for _, row in df.iterrows(): c = 'r' if row['Year'] in [2011, 2012, 2013] else 'k' c = 'g' if row['Year'] in [1980, 1992, 1993] else c ax.text(row['t'], row['p'], ("%i" % (row['Year'],))[-2:], color=c, ha='center') ax.set_xlim(df['t'].min() - 0.3, df['t'].max() + 0.3) ax.set_ylim(df['p'].min() - 10, df['p'].max() + 10) ax.set_xlabel(r"Average Temperature ($^\circ$C)") ax.set_ylabel("Cumulative Precipitation (cm)") ax.text(0.15, 0.95, "Cool & Wet", ha='center', transform=ax.transAxes, fontproperties=font0) ax.text(0.85, 0.95, "Warm & Wet", ha='center', transform=ax.transAxes, fontproperties=font0) ax.text(0.85, 0.05, "Warm & Dry", ha='center', transform=ax.transAxes, fontproperties=font0) ax.text(0.15, 0.05, "Cool & Dry", ha='center', transform=ax.transAxes, fontproperties=font0) ax.axhline(df['p'].mean()) ax.axvline(df['t'].mean()) fig.savefig('test.pdf', dpi=300)
def _get_3d_plot(self, label_stable=True): """ Shows the plot using pylab. Usually I won"t do imports in methods, but since plotting is a fairly expensive library to load and not all machines have matplotlib installed, I have done it this way. """ import matplotlib.pyplot as plt import mpl_toolkits.mplot3d.axes3d as p3 from matplotlib.font_manager import FontProperties fig = plt.figure() ax = p3.Axes3D(fig) font = FontProperties() font.set_weight("bold") font.set_size(20) (lines, labels, unstable) = self.pd_plot_data count = 1 newlabels = list() for x, y, z in lines: ax.plot(x, y, z, "bo-", linewidth=3, markeredgecolor="b", markerfacecolor="r", markersize=10) for coords in sorted(labels.keys()): entry = labels[coords] label = entry.name if label_stable: if len(entry.composition.elements) == 1: ax.text(coords[0], coords[1], coords[2], label) else: ax.text(coords[0], coords[1], coords[2], str(count)) newlabels.append("{} : {}".format(count, latexify(label))) count += 1 plt.figtext(0.01, 0.01, "\n".join(newlabels)) ax.axis("off") return plt
def plot_label(self, ax, **kwargs): data = self.data highlight_in = self.highlight_in label_in = self.label_in default_label_color = sns.axes_style()['text.color'] font0 = FontProperties() font0.set_weight('bold') for idx in data.index: if idx in highlight_in: color = default_label_color if hasattr(self, 'highlight_text_color' ) and self.highlight_text_color is not None: color = self.highlight_text_color if (isinstance(label_in, str) and label_in == 'all') or idx in set(label_in) or ( idx in highlight_in and self.label_highlight): if isinstance(label_in, dict): label = label_in[idx] else: label = idx x = self.data.loc[idx][self.x] y = self.data.loc[idx][self.y] ax.annotate( label, xy=(x, y), xytext=(x + 0.4, y + 0.2), arrowprops=dict(facecolor='black', shrink=0.05), ) return ax
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)
def draw_logo2(all_scores, filename, fontfamily='Arial', size=80, COLOR_SCHEME=COLOR_SCHEME_AA): if fontfamily == 'xkcd': plt.xkcd() else: matplotlib.rcParams['font.family'] = fontfamily fig, ax = plt.subplots(figsize=(len(all_scores), 2.5)) font = FontProperties() font.set_size(size) font.set_weight('bold') #font.set_family(fontfamily) ax.set_xticks(range(1, len(all_scores) + 1)) ax.set_yticks(range(0, 6)) ax.set_xticklabels(range(1, len(all_scores) + 1), rotation=90) ax.set_yticklabels(np.arange(-3, 3, 1)) sns.despine(ax=ax, trim=True) trans_offset = transforms.offset_copy(ax.transData, fig=fig, x=1, y=0, units='dots') for index, scores in enumerate(all_scores): yshift = 0 for base, score in scores: txt = ax.text( index + 1, 3, base, transform=trans_offset, fontsize=80, color=COLOR_SCHEME[base], ha='center', fontproperties=font, ) txt.set_path_effects([Scale(1.0, score)]) fig.canvas.draw() window_ext = txt.get_window_extent(txt._renderer) yshift = window_ext.height * score trans_offset = transforms.offset_copy(txt._transform, fig=fig, y=yshift, units='points') trans_offset = transforms.offset_copy(ax.transData, fig=fig, x=1, y=0, units='points') plt.axis('off') plt.savefig(filename) plt.show() plt.close()
def draw(self, ax=None, **kwargs): kwargs.setdefault("facecolor", "green") kwargs.setdefault("edgecolor", "black") kwargs.setdefault("alpha", 0.5) result = super(InterestRegion, self).draw(ax=ax, **kwargs) # Print region name if not ax: ax = plt.gca() x, y = np.array(self.poly.centroid.coords)[0] font = FontProperties() font.set_weight('bold') if len(self.region_id) <= 2: reg_id = self.region_id else: reg_id = self.region_id[-1] ax.text(x, y, "{}".format(reg_id), color='white', fontsize=13, fontproperties=font, horizontalalignment='center', verticalalignment='center') return result
def _show_3d_plot(self): ''' Shows the plot using pylab. Usually I won't do imports in methods, but since plotting is a fairly expensive library to load and not all machines have matplotlib installed, I have done it this way. ''' import matplotlib.pyplot as plt import mpl_toolkits.mplot3d.axes3d as p3 from matplotlib.font_manager import FontProperties fig = plt.figure() ax = p3.Axes3D(fig) font = FontProperties() font.set_weight('bold') font.set_size(20) (lines, labels, unstable) = self.pd_plot_data count = 1 newlabels = list() for x, y, z in lines: ax.plot(x, y, z, 'bo-', linewidth=3, markeredgecolor='b', markerfacecolor='r', markersize=10) for coords in sorted(labels.keys()): entry = labels[coords] label = entry.name if len(entry.composition.elements) == 1: # commented out options are only for matplotlib 1.0. Removed them so that most ppl can use this class. ax.text(coords[0], coords[1], coords[2], label)#, horizontalalignment=halign, verticalalignment=valign, fontproperties=font) else: ax.text(coords[0], coords[1], coords[2], str(count))#, horizontalalignment=halign, verticalalignment=valign, fontproperties=font) newlabels.append(str(count) + " : " + label) count += 1 plt.figtext(0.01, 0.01, '\n'.join(newlabels)) ax.axis('off') plt.show()
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
def make_figure(true_model): """ Show the following: - True dynamics distributions - True transition probabilities """ fig = plt.figure(figsize=(6.5, 2.75)) gs = gridspec.GridSpec(2, K) fp = FontProperties() fp.set_weight("bold") # True dynamics for k in range(K): ax = fig.add_subplot(gs[0, k], aspect=1.0) plot_dynamics(true_model.dynamics_distns[k].A[:, :D_latent], true_model.dynamics_distns[k].A[:, D_latent:], k, plot_center=True, color=colors[k], ax=ax) ax = fig.add_subplot(gs[1, k], aspect=1.0) plot_single_trans_prob(true_model.trans_distn, k, ax=ax) plt.tight_layout() plt.savefig(os.path.join(results_dir, "prior.png"), dpi=200) plt.savefig(os.path.join(results_dir, "prior.pdf")) plt.show()
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()
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
def makeSubplotFigures3(): dats = {} targets = ["influentials","nearby","random"] for target in targets: dats[target] = csv2rec("LC_target_%s_hires.stripped.csv"%target) fig = figure(figsize=(6.83,6.9)) for figrow,target in enumerate(targets): subplot(3,3,1) subplots_adjust(left=0.12,bottom=0.09,right=0.87,top=0.94,wspace=0.2,hspace=0.3) for i,threshold,tlabel in [(0,0.0001,"survival"),(1,0.5,"dominance"),(2,0.9999,"completion")]: ax = subplot(3,3,figrow*3 + i+1) datSubset = dats[target][dats[target]['mean_grammar']>=threshold] make2DHistogram(dats[target],datSubset,interpolation='nearest',contourLines=0,showColorBar=((i==2) and (figrow==1)),cmap=modifiedJet,label_font_size=16) break if (i>0): ax.yaxis.set_ticklabels([]) ax.yaxis.label.set_text("") xticks(fontsize=10) yticks(fontsize=10) if (figrow == 0): title("%s"%(tlabel), fontsize=12) # r"$P(\bar{g}(t_{final}) \geq %s)$" if (figrow != 2): xlabel("") #fig.axes[3].set_position([0.89,0.15,0.6,0.62]) #suptitle("%s bias distribution"%fixName(target) , y=0.95,fontsize=16) #figtext(0.5, [0.68, 0.37, 0.04][figrow], ["a) ","b) ","c) "][figrow] + fixName(target) + " scenario", ha="center", fontsize=9) my_font = FontProperties() my_font.set_weight('bold') figtext(0.03, [0.93, 0.62, 0.305][figrow], [r"A",r"B",r"C"][figrow], ha="center", fontsize=18, fontproperties=my_font) savefig("grassroots_fig6_2col_updated.pdf")
def show_linearComplexity(complexityVector, complexityType, seqlen, getFig=False): """ The complexity plotting functions opperate outside of the general linear sequence framework as there are types of options/behaviours specific enough to the complexity plots that trying to shoe-horn them into the existing code would not be a good design decision. """ n_bars = len(complexityVector[0, :]) LW = __get_bar_edge_width(n_bars) # first generate the bar-plot and save the list of bars barlist = plt.bar(complexityVector[0, :], complexityVector[1, :], width=1, linewidth=LW, edgecolor='k', color='#A8A8A8') # set the limits plt.ylim([0, 1]) plt.xlim([1, seqlen]) # set the font properties # set general font properties first font = {'family': 'Bitstream Vera Sans', 'weight': 'normal', 'size': 14} matplotlib.rc('font', **font) axes_pro = FontProperties() axes_pro.set_size('large') axes_pro.set_weight('bold') # set the axis labels plt.xlabel('Residue', fontproperties=axes_pro) plt.ylabel('Complexity', fontproperties=axes_pro) # set the title (i.e. what type of complexity was calculated) axes_pro.set_size('x-large') if complexityType == 'WF': title = 'Wooton-Federhen complexity' elif complexityType == 'LC': title = 'Linguistic complexity' elif complexityType == 'LZW': title = 'Lempel-Ziv-Welch complexity' else: raise PlottingException( 'Unexpected complexity type passed - should never happen') plt.title(title, fontproperties=axes_pro) # finally either show the plot or return the plt object if getFig: return plt else: plt.show()
def plot_basics(data, data_inst, fig, units): ''' This function is the main plotting function. Adapted from Newman's powerlaw package. ''' import pylab pylab.rcParams['xtick.major.pad'] = '8' pylab.rcParams['ytick.major.pad'] = '8' pylab.rcParams['font.sans-serif'] = 'Arial' from matplotlib import rc rc('font', family='sans-serif') rc('font', size=10.0) rc('text', usetex=False) from matplotlib.font_manager import FontProperties panel_label_font = FontProperties().copy() panel_label_font.set_weight("bold") panel_label_font.set_size(12.0) panel_label_font.set_family("sans-serif") n_data = 1 n_graphs = 4 from powerlaw import plot_pdf, Fit, pdf ax1 = fig.add_subplot(n_graphs, n_data, data_inst) x, y = pdf(data, linear_bins=True) ind = y > 0 y = y[ind] x = x[:-1] x = x[ind] ax1.scatter(x, y, color='r', s=.5, label='data') plot_pdf(data[data > 0], ax=ax1, color='b', linewidth=2, label='PDF') from pylab import setp setp(ax1.get_xticklabels(), visible=False) plt.legend(loc='bestloc') ax2 = fig.add_subplot(n_graphs, n_data, n_data + data_inst, sharex=ax1) plot_pdf(data[data > 0], ax=ax2, color='b', linewidth=2, label='PDF') fit = Fit(data, discrete=True) fit.power_law.plot_pdf(ax=ax2, linestyle=':', color='g', label='w/o xmin') p = fit.power_law.pdf() ax2.set_xlim(ax1.get_xlim()) fit = Fit(data, discrete=True, xmin=3) fit.power_law.plot_pdf(ax=ax2, linestyle='--', color='g', label='w xmin') from pylab import setp setp(ax2.get_xticklabels(), visible=False) plt.legend(loc='bestloc') ax3 = fig.add_subplot(n_graphs, n_data, n_data * 2 + data_inst) #, sharex=ax1)#, sharey=ax2) fit.power_law.plot_pdf(ax=ax3, linestyle='--', color='g', label='powerlaw') fit.exponential.plot_pdf(ax=ax3, linestyle='--', color='r', label='exp') fit.plot_pdf(ax=ax3, color='b', linewidth=2) ax3.set_ylim(ax2.get_ylim()) ax3.set_xlim(ax1.get_xlim()) plt.legend(loc='bestloc') ax3.set_xlabel(units)
def get_letter_font_prop(): from matplotlib.font_manager import FontProperties font = FontProperties() font.set_family("C:\\WINDOWS\\Fonts\\HelveticaNeue-CondensedBold.ttf") font.set_weight("heavy") font.set_size(10) font.letter_format = "a" return font
def show_linearComplexity(complexityVector, complexityType, seqlen, getFig=False): """ The complexity plotting functions opperate outside of the general linear sequence framework as there are types of options/behaviours specific enough to the complexity plots that trying to shoe-horn them into the existing code would not be a good design decision. """ n_bars = len(complexityVector[0,:]) LW = __get_bar_edge_width(n_bars) # first generate the bar-plot and save the list of bars barlist = plt.bar(complexityVector[0,:], complexityVector[1,:], width=1, linewidth=LW, edgecolor='k', color='#A8A8A8') # set the limits plt.ylim([0,1]) plt.xlim([1, seqlen]) # set the font properties # set general font properties first font = {'family' : 'Bitstream Vera Sans', 'weight' : 'normal', 'size' : 14} matplotlib.rc('font', **font) axes_pro = FontProperties() axes_pro.set_size('large') axes_pro.set_weight('bold') # set the axis labels plt.xlabel('Residue', fontproperties=axes_pro) plt.ylabel('Complexity', fontproperties=axes_pro) # set the title (i.e. what type of complexity was calculated) axes_pro.set_size('x-large') if complexityType == 'WF': title='Wooton-Federhen complexity' elif complexityType == 'LC': title='Linguistic complexity' elif complexityType == 'LZW': title='Lempel-Ziv-Welch complexity' else: raise PlottingException('Unexpected complexity type passed - should never happen') plt.title(title, fontproperties=axes_pro) # finally either show the plot or return the plt object if getFig: return plt else: plt.show()
def draw_plot(benchmark_time1, benchmark_time2): wierd_scale = range(len(threashold_list)) percentage_tick = [] for i in range(0, 110, 10): percentage_tick.append(i / 100.) percentage_tick_label = [] for i in range(0, 110, 10): percentage_tick_label.append(str(i) + "%") fig, ax = plt.subplots() xs = wierd_scale ys1 = map(lambda x: (count_le(benchmark_time1, threashold_list[x]) / 143.), wierd_scale) ys2 = map(lambda x: (count_le(benchmark_time2, threashold_list[x]) / 143.), wierd_scale) print ys1 print ys2 scythe, = ax.plot(xs, ys1, 'g', label="Scythe", linewidth=1.8) enum, = ax.plot(xs, ys2, '--', label="Enum", linewidth=1.8) plt.legend([scythe, enum], ['Scythe', 'Enum'], 'lower right') plt.xticks(wierd_scale, threashold_list) plt.yticks(percentage_tick, percentage_tick_label) ax.axhline(y=0.5, xmin=0, xmax=3, c="grey", linewidth=0.5, zorder=0) make_invisible = True if (make_invisible): xticks = ax.xaxis.get_major_ticks() for i in range(0, 61): if (not (i * 10) in visable_ticks): xticks[i].label1.set_visible(False) yticks = ax.yaxis.get_major_ticks() # yticks[-1].label1.set_visible(False) #xticks[-1].label1.set_visible(False) font = FontProperties() font.set_family('sans-serif') font.set_weight("bold") font.set_size('large') plt.figtext(0.04, 0.8, 'Percentage of solved cases (out of 143)', horizontalalignment='center', rotation='vertical', fontproperties=font) plt.figtext(0.5, 0.01, 'Time (seconds)', horizontalalignment='center', fontproperties=font) plt.show()
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
def plot_basics(data, data_inst, fig, units): ''' This function is the main plotting function. Adapted from Newman's powerlaw package. ''' import pylab pylab.rcParams['xtick.major.pad']='8' pylab.rcParams['ytick.major.pad']='8' pylab.rcParams['font.sans-serif']='Arial' from matplotlib import rc rc('font', family='sans-serif') rc('font', size=10.0) rc('text', usetex=False) from matplotlib.font_manager import FontProperties panel_label_font = FontProperties().copy() panel_label_font.set_weight("bold") panel_label_font.set_size(12.0) panel_label_font.set_family("sans-serif") n_data = 1 n_graphs = 4 from powerlaw import plot_pdf, Fit, pdf ax1 = fig.add_subplot(n_graphs,n_data,data_inst) x, y = pdf(data, linear_bins=True) ind = y>0 y = y[ind] x = x[:-1] x = x[ind] ax1.scatter(x, y, color='r', s=.5, label='data') plot_pdf(data[data>0], ax=ax1, color='b', linewidth=2, label='PDF') from pylab import setp setp( ax1.get_xticklabels(), visible=False) plt.legend(loc = 'bestloc') ax2 = fig.add_subplot(n_graphs,n_data,n_data+data_inst, sharex=ax1) plot_pdf(data[data>0], ax=ax2, color='b', linewidth=2, label='PDF') fit = Fit(data, discrete=True) fit.power_law.plot_pdf(ax=ax2, linestyle=':', color='g',label='w/o xmin') p = fit.power_law.pdf() ax2.set_xlim(ax1.get_xlim()) fit = Fit(data, discrete=True,xmin=3) fit.power_law.plot_pdf(ax=ax2, linestyle='--', color='g', label='w xmin') from pylab import setp setp(ax2.get_xticklabels(), visible=False) plt.legend(loc = 'bestloc') ax3 = fig.add_subplot(n_graphs,n_data,n_data*2+data_inst)#, sharex=ax1)#, sharey=ax2) fit.power_law.plot_pdf(ax=ax3, linestyle='--', color='g',label='powerlaw') fit.exponential.plot_pdf(ax=ax3, linestyle='--', color='r',label='exp') fit.plot_pdf(ax=ax3, color='b', linewidth=2) ax3.set_ylim(ax2.get_ylim()) ax3.set_xlim(ax1.get_xlim()) plt.legend(loc = 'bestloc') ax3.set_xlabel(units)
def _setup_font(fontfamily='Arial', fontsize=12): """Setup font properties""" #_setup_plt() font = FontProperties() font.set_size(fontsize) font.set_weight('bold') font.set_family(fontfamily) return font
def process_accuracies(): test_size = 100 in_file = path.abspath( path.join(path.dirname(__file__), "data", "accuracy_" + str(test_size) + ".p")) accuracies = pickle.load(open(in_file, "rb")) print(accuracies) for ws, hs_szs in accuracies.iteritems(): for hs, scores in hs_szs.iteritems(): rank_list = [] acc_list = [] for scoreset in scores: for rank, acc in scoreset.iteritems(): if rank == 1: rank += 0.08 elif rank == 10: rank -= 0.08 rank_list.append(rank) acc_list.append(acc) title = "Window size - " + str(ws) + " - Hash size - " + str(hs) plt.rc('font', weight='bold') plt.rc('xtick.major', size=5, pad=7) plt.rc('xtick', labelsize=15) fig = plt.figure() ax = fig.add_subplot(111) font = FontProperties() # sizes = ['xx-small', 'x-small', 'small', 'medium', 'large', # 'x-large', 'xx-large'] font.set_weight('bold') font.set_size('large') plt.plot(rank_list, acc_list, 'ro') for x, y in zip(rank_list, acc_list): ax.annotate('%s' % y, xy=(x, y + 0.15), textcoords='data', fontproperties=font) plt.axis([1, 10, 0, 20]) plt.xlabel('Rank', fontproperties=font) plt.ylabel('Accuracy (%)', fontproperties=font) plt.title(title, fontproperties=font) # plt.show() fig_title = str(test_size) + "_" + str(ws) + "_" + str(hs) + ".eps" fig_file = path.abspath( path.join(path.dirname(__file__), "data", "figures", fig_title)) fig.savefig(fig_file)
def annotate(ax, P, labels=None): if labels is None: labels = range(len(P)) font = FontProperties() font.set_weight("bold") for label, p in zip(labels, P): ax.text(*p, label, alpha=0.8, fontproperties=font)
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
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')
def plot_all_domains(ax1, fig1,max_dom, wpsproj, latlonproj, corner_lat_full, corner_lon_full, length_x, length_y): """ Plot all the Domains Location of dNum string to be dynamic relative to domain size and figure size would be much better. """ # d01 font0 = FontProperties() font0.set_weight('bold') #print("Number of Domains: ", max_dom) colors = ['blue',"white","red", "cyan", "magenta","gold","black","green","yellow",'pink'] dNum = ['D01','D02','D03','D04','D05','D06','D07','D08','D09','D10'] ## ORIGINAL VALUES #xbuff = [0.05, 0.05, 0.1] #ybuff = [0.9, 1.1, 0.8] for i in range(max_dom): if i == 0: corner_x, corner_y = wps_info.reproject_corners(corner_lon_full[i,:], corner_lat_full[i,:], wpsproj, latlonproj) ax1.set_xlim([corner_x[0]-length_x[0]/15, corner_x[3]+length_x[0]/15]) ## In Geodetic Coordinates # Want Lat/Lon so I can add gridlines and labels on axis ax1.set_ylim([corner_y[0]-length_y[0]/15, corner_y[3]+length_y[0]/15]) ## In Geodetic Coordinates # Want Lat/Lon so I can add gridlines and labels on axis elif i < 10: corner_x, corner_y = wps_info.reproject_corners(corner_lon_full[i,:], corner_lat_full[i,:], wpsproj, latlonproj) else: print ("Maximum Domains To Plot is 9") raise IndexError ax1.add_patch(mpl.patches.Rectangle((corner_x[0], corner_y[0]), length_x[i], length_y[i], fill=None, lw=3, edgecolor=colors[i], zorder=10)) ax1.text(corner_x[0]+length_x[i]*0.05, corner_y[0]+length_y[i]*1.0, dNum[i], fontproperties=font0, size=15, color=colors[i], zorder=10) ## Can be improved fig1.canvas.draw() ax1.add_feature(LAND, edgecolor='k',facecolor='limegreen') ax1.add_feature(OCEAN, edgecolor='k',facecolor='deepskyblue')#, facecolor='deepskyblue') ax1.add_feature(LAKES, edgecolor='k',facecolor='deepskyblue') ax1.coastlines('10m','black') ax1.add_feature(cartopy.feature.STATES.with_scale('10m')) # I DO NOT LIKE THIS LAMBERT PROJ WORK AROUND. WAIT UNTIL CARTOPY SUPPORTS IT OR DON'T USE OR IMPLEMENT #if "Lambert" in str(wpsproj): # Add tick marks for lambert projection (only) #wps_info.set_lambert_ticks(ax1) # wps_info.set_lambert_ticks(ax1,xskip=5.,yskip=5.,x_thickness=14,y_thickness=14) if "Mercator" in str(wpsproj) or "PlateCarree" in str(wpsproj): ax1.gridlines(color='lightgrey', linestyle='-', draw_labels=True) elif "Polar" in str(wpsproj) or "Stereo" in str(wpsproj) or "lat-lon" in str(wpsproj): pass else: pass # Don't think this is needed return ax1, fig1
def finalize_DasPappu(plt, legendOn, title, xLim, yLim): """ Common function which finalizes up a plot by drawing on the regions 1-5, adding the legend and title. Used by both single and multiple phasePlot function """ # define the five regions by filling the plot alphaval = 1 reg1, = plt.fill([0, 0, 0.25], [0, 0.25, 0], color='Chartreuse', alpha=alphaval, zorder=1) reg2, = plt.fill([0, 0, 0.35, 0.25], [0.25, 0.35, 0, 0], color='MediumSeaGreen', alpha=alphaval, zorder=1) reg3, = plt.fill([0, 0.325, 0.675, 0.35], [0.35, 0.675, 0.325, 0], color='DarkGreen', alpha=alphaval, zorder=1) reg4, = plt.fill([0, 0, 0.325], [0.35, 1, 0.675], color='Red', alpha=alphaval, zorder=1) reg5, = plt.fill([0.35, 0.675, 1], [0, 0.325, 0], color='Blue', alpha=alphaval, zorder=1) # set the plot limits plt.xlim([0, xLim]) plt.ylim([0, yLim]) # label the axes and set the title axes_pro = FontProperties() axes_pro.set_size('large') axes_pro.set_weight('bold') plt.xlabel( 'Fraction of positively charged residues', fontproperties=axes_pro) plt.ylabel( 'Fraction of negatively charged residues', fontproperties=axes_pro) # update the font property for the title axes_pro.set_size('x-large') plt.title(title, fontproperties=axes_pro) # if we the legend is on add the annotation if legendOn: # create and set set legend font options fontP = FontProperties() fontP.set_size('small') plt.legend([reg1, reg2, reg3, reg4, reg5], ['Weak polyampholytes & polyelectrolytes:\nGlobules & tadpoles', 'Janus sequences:\nCollapsed or expanded - context dependent', 'Strong polyampholytes:\nCoils, hairpins, & chimeras', 'Negatively charged strong polyelectrolytes:\nSwollen coils', 'Positively charged strong polyelectrolytes:\nSwollen coils'], prop=fontP) return plt
def _show_2d_plot(self): ''' Shows the plot using pylab. Usually I won't do imports in methods, but since plotting is a fairly expensive library to load and not all machines have matplotlib installed, I have done it this way. ''' import matplotlib.pyplot as plt from matplotlib.font_manager import FontProperties (lines, labels, unstable) = self.pd_plot_data for x, y in lines: plt.plot(x, y, 'bo-', linewidth=3, markeredgecolor='b', markerfacecolor='r', markersize=10) font = FontProperties() font.set_weight('bold') font.set_size(20) count = 1 if len(self._pd.elements) == 3: plt.axis('equal') plt.xlim((-0.1, 1.2)) plt.ylim((-0.1, 1.0)) plt.axis('off') legendstart = [1.0, 0.55] else: plt.xlim((-0.1, 1.4)) legendstart = [1.1, 0.0] for coords in sorted(labels.keys()): entry = labels[coords] label = entry.name x = coords[0] if coords[0] >= math.sqrt(3) / 2: halign = 'left' x += 0.02 else: halign = 'right' x += -0.02 if coords[1] > 0: valign = 'bottom' else: valign = 'top' if len(entry.composition.elements) == 1: plt.text(x, coords[1], label, horizontalalignment=halign, verticalalignment=valign, fontproperties=font) else: plt.text(x, coords[1], str(count), horizontalalignment=halign, verticalalignment=valign, fontproperties=font) plt.text(legendstart[0], legendstart[1] - 0.05 * count, str(count) + " : " + label, horizontalalignment='left', verticalalignment='top', fontproperties=font) count += 1 for entry, coords in unstable.items(): label = entry.name plt.plot(coords[0], coords[1], 'bx', linewidth=3, markeredgecolor='b', markerfacecolor='b', markersize=10) F = plt.gcf() F.set_size_inches((8, 6.4)) plt.show()
def create_results_figure(model_names, method_names, values, filename): results_table = np.array(values).transpose() n_models = results_table.shape[0] n_methods = results_table.shape[1] index = np.arange(n_methods) cmap = plt.get_cmap('tab20') x = np.linspace(0.0, 1.0, 100) font0 = FontProperties() font0.set_weight('medium') font0.set_size('medium') font1 = font0.copy() font1.set_size('x-large') font2 = font0.copy() font2.set_size('xx-large') dpi = 70 step = (1.0 / n_models) * 0.9 xmax = 100000.0 plt.figure(figsize=(1000 / dpi, 2500 / dpi), dpi=dpi) for i in range(n_models): color = cmap(i / n_models) ax = plt.barh(index - 0.35 + i * step, results_table[i], step, alpha=1.0, color=color, label=model_names[i]) rects = ax.patches for j in range(len(rects)): rect = rects[j] read_time = results_table[i][j] if read_time == 0: label = 'N/A' else: label = ' %-7.2f' % (results_table[i][j]) w = min(rect.get_width(), xmax - 1500) h = rect.get_y() + rect.get_height() * 0.45 if w == 0: w = 0.32 plt.ylabel('Library', fontproperties=font1) plt.xlabel('Time (log ms)', fontproperties=font1) plt.legend(bbox_to_anchor=(1.1, 1.0)) plt.xscale('log') plt.xlim(0.3, xmax) plt.yticks(np.arange(n_methods), method_names) plt.tight_layout() # plt.show() plt.savefig(filename, dpi=dpi)
def _add_feature_values(feature_values, ax): """Display feature's values on left of plot.""" x_coord = ax.get_xlim()[0] OFFSET = 0.15 for y_coord, (feat_name, feat_val) in enumerate(feature_values.items()): t = plt.text(x_coord, y_coord - OFFSET, '{}'.format(feat_val), size=12) t.set_bbox(dict(facecolor='white', alpha=0.5)) from matplotlib.font_manager import FontProperties font = FontProperties() font.set_weight('bold') t = plt.text(x_coord, y_coord + 1 - OFFSET, 'feature\nvalue', fontproperties=font, size=12)
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)
def draw_logo(all_scores, fontfamily='Arial', size=80): mpl.rcParams['font.family'] = fontfamily colors = {'G': 'orange', 'A': 'darkgreen', 'C': 'blue', 'T': 'red'} fig, ax = plt.subplots(figsize=(len(all_scores), 2.5)) font = FontProperties() font.set_size(size) font.set_weight('bold') ax.set_xticks(range(1, len(all_scores) + 1)) ax.set_yticks(range(0, 3)) ax.set_xticklabels(range(1, len(all_scores) + 1), rotation=90) ax.set_yticklabels(np.arange(0, 3, 1)) sns.despine(ax=ax, trim=True) trans_offset = transforms.offset_copy(ax.transData, fig=fig, x=1, y=0, units='dots') for index, scores in enumerate(all_scores): yshift = 0 for base, score in scores: txt = ax.text( index + 1, 0, base, transform=trans_offset, #fontsize=80, color=colors[base], ha='center', fontproperties=font, ) txt.set_path_effects([Scale(1.0, score)]) fig.canvas.draw() window_ext = txt.get_window_extent(txt._renderer) yshift = window_ext.height * score trans_offset = transforms.offset_copy(txt._transform, fig=fig, y=yshift, units='points') trans_offset = transforms.offset_copy(ax.transData, fig=fig, x=1, y=0, units='points') return fig
def _get_plot(self, label_stable=True, label_unstable=False): """ Plot convex hull of Pourbaix Diagram entries """ import matplotlib.pyplot as plt import mpl_toolkits.mplot3d.axes3d as p3 from matplotlib.font_manager import FontProperties fig = plt.figure() ax = p3.Axes3D(fig) font = FontProperties() font.set_weight("bold") font.set_size(14) (lines, labels, unstable) = self.pourbaix_hull_plot_data count = 1 newlabels = list() for x, y, z in lines: ax.plot(x, y, z, "bo-", linewidth=3, markeredgecolor="b", markerfacecolor="r", markersize=10) for coords in sorted(labels.keys()): entry = labels[coords] label = self.print_name(entry) if label_stable: ax.text(coords[0], coords[1], coords[2], str(count)) newlabels.append("{} : {}".format( count, latexify_ion(latexify(label)))) count += 1 if label_unstable: for entry in unstable.keys(): label = self.print_name(entry) coords = unstable[entry] ax.plot([coords[0], coords[0]], [coords[1], coords[1]], [coords[2], coords[2]], "bo", markerfacecolor="g", markersize=10) ax.text(coords[0], coords[1], coords[2], str(count)) newlabels.append("{} : {}".format( count, latexify_ion(latexify(label)))) count += 1 plt.figtext(0.01, 0.01, "\n".join(newlabels)) plt.xlabel("pH") plt.ylabel("V") return plt
def watermark_seismic(ax, text, size, colour, xn, yn=None): """ Add semi-transparent text to the seismic. """ font = FontProperties() font.set_weight('bold') font.set_family('sans-serif') style = {'size': size, 'color': colour, 'alpha': 0.5, 'fontproperties': font } alignment = {'rotation': 33, 'horizontalalignment': 'left', 'verticalalignment': 'baseline' } params = dict(style, **alignment) # Axis ranges. xr = ax.get_xticks() yr = ax.get_yticks() aspect = xr.size / yr.size yn = yn or (xn / aspect) yn += 1 # Positions for even lines. xpos = np.linspace(xr[0], xr[-1], xn)[:-1] ypos = np.linspace(yr[0], yr[-1], yn)[:-1] # Intervals. xiv = xpos[1] - xpos[0] yiv = ypos[1] - ypos[0] # Adjust the y positions. ypos += yiv / 2 # Place everything. c = False for y in ypos: for x in xpos: if c: xi = x + xiv / 2 else: xi = x ax.text(xi, y, text, clip_box=ax.clipbox, clip_on=True, **params) c = not c return ax
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)
def finalize_uversky(plt, legendOn, title, xLim, yLim): """ Common function which finalizes up a plot by drawing on the regions 1-5, adding the legend and title. Used by both single and multiple phasePlot function """ # define the five regions by filling the plot alphaval = 0.15 # folded region reg1, = plt.fill([0.0, 0, 0.772], [1, 0.413, 1], color='Chartreuse', alpha=0.25, zorder=1) # unfolded region reg2, = plt.fill([0, 0, 0.772, 1, 1], [0, 0.413, 1, 1, 0], color='Red', alpha=0.15, zorder=1) # set the plot limits plt.xlim([0, xLim]) plt.ylim([0, yLim]) # label the axes and set the title axes_pro = FontProperties() axes_pro.set_size('large') axes_pro.set_weight('bold') plt.xlabel('Mean net charge', fontproperties=axes_pro) plt.ylabel('Mean hydropathy <H>', fontproperties=axes_pro) # update the font property for the title axes_pro.set_size('x-large') plt.title(title, fontproperties=axes_pro) # if we the legend is on add the annotation if legendOn: # create and set set legend font options fontP = FontProperties() fontP.set_size('small') plt.legend([reg1, reg2], ['Folded proteins', 'Natively unfolded'], prop=fontP) return plt
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
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
def init(): font = FontProperties() font.set_family('fantasy') font.set_size('x-large') font.set_weight('semibold') ax.text(1.85, 0, "3", color='#791E94', fontsize=18, ha="center", va="center", fontproperties=font) ax.text(-1.85, 0, "9", color='#791E94', fontsize=18, ha="center", va="center", fontproperties=font) ax.text(0.05, 1.85, "12", color='#791E94', fontsize=18, ha="center", va="center", fontproperties=font) ax.text(0.05, -1.85, "6", color='#791E94', fontsize=18, ha="center", va="center", fontproperties=font) ax.set_xlim(-2, 2) ax.set_ylim(-2, 2) x_out = [r_out * np.cos(theta[i]) for i in range(len(theta))] y_out = [r_out * np.sin(theta[i]) for i in range(len(theta))] ln1.set_data(x_out, y_out) return ln1,
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()
def _get_plot(self, label_stable=True, label_unstable=False): """ Plot convex hull of Pourbaix Diagram entries """ import matplotlib.pyplot as plt import mpl_toolkits.mplot3d.axes3d as p3 from matplotlib.font_manager import FontProperties fig = plt.figure() ax = p3.Axes3D(fig) font = FontProperties() font.set_weight("bold") font.set_size(14) (lines, labels, unstable) = self.pourbaix_hull_plot_data count = 1 newlabels = list() for x, y, z in lines: ax.plot(x, y, z, "bo-", linewidth=3, markeredgecolor="b", markerfacecolor="r", markersize=10) for coords in sorted(labels.keys()): entry = labels[coords] label = self.print_name(entry) if label_stable: ax.text(coords[0], coords[1], coords[2], str(count)) newlabels.append("{} : {}".format( count, latexify_ion(latexify(label)))) count += 1 if self.show_unstable: for entry in unstable.keys(): label = self.print_name(entry) coords = unstable[entry] ax.plot([coords[0], coords[0]], [coords[1], coords[1]], [coords[2], coords[2]], "bo", markerfacecolor="g", markersize=10) ax.text(coords[0], coords[1], coords[2], str(count)) newlabels.append("{} : {}".format( count, latexify_ion(latexify(label)))) count += 1 plt.figtext(0.01, 0.01, "\n".join(newlabels)) plt.xlabel("pH") plt.ylabel("V") # plt.tight_layout() return plt
def make_extended_figure(true_model, zs, xs): """ Show the following: - True dynamics distributions - True transition probabilities - Superposition of most likely states """ fig = plt.figure(figsize=(6.5, 2.75)) gs = gridspec.GridSpec(2, K + 1) fp = FontProperties() fp.set_weight("bold") # True dynamics for k in range(K): ax = fig.add_subplot(gs[0, k], aspect=1.0) plot_dynamics(true_model.dynamics_distns[k].A[:, :D_latent], true_model.dynamics_distns[k].A[:, D_latent:], k, plot_center=True, color=colors[k], ax=ax) ax = fig.add_subplot(gs[1, k], aspect=1.0) plot_single_trans_prob(true_model.trans_distn, k, ax=ax) ax = fig.add_subplot(gs[0, -1], aspect=1.0) plot_most_likely_dynamics(true_model.trans_distn, true_model.dynamics_distns, ax=ax, nxpts=10, nypts=10) # Plot the trajectory ax = fig.add_subplot(gs[1, -1], aspect=1.0) for z, x in zip(zs, xs): plot_trajectory(z, x, ax=ax) plt.tight_layout() plt.savefig(os.path.join(results_dir, "prior_with_sim.png"), dpi=200) plt.savefig(os.path.join(results_dir, "prior_with_sim.pdf")) plt.show()
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', )
from matplotlib import rc rc('font', family='sans-serif') rc('text', usetex=False) font_size = 7 rc('font', size=font_size) rc('axes', labelsize=font_size) rc('ytick', labelsize=font_size) rc('xtick', labelsize=font_size) rc('legend', fontsize=font_size) from matplotlib.font_manager import FontProperties panel_label_font = FontProperties().copy() panel_label_font.set_weight("bold") panel_label_font.set_size(9.0) panel_label_font.set_family("sans-serif") # In[5]: entries = pd.read_hdf(model_directory+'entries_for_performance_analysis.h5', 'entries') # In[6]: models_store = pd.HDFStore(model_directory+'performance_models.h5') # In[7]:
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)
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
def __build_linear_plot( data, title="", xlabel="Blob index", ylabel="", ylimits=[ 0, 1], hline=None, setPositiveNegativeBars=False): """ Internal function which expects data to be a Nx2 matrix (np.vstack) where column 1 is the x values and column 2 is the y values. It also assumes the Y values are scaled to between 0 and 1 (so Y-axis limits are 0 and 1) hline defines a list of horizontal lines = so [0.2,-0.2] would draw horizontal lines """ # plot the data barlist = plt.bar( data[ 0, :], data[ 1, :], width=1, linewidth=1.1, edgecolor='k', color='#A8A8A8') # this is really inefficient but means we have a consistent # if setPositiveNegativeBars: for bar in xrange(0, len(barlist)): if data[1, bar] < 0: barlist[bar].set_color('r') barlist[bar].set_edgecolor('k') else: barlist[bar].set_color('b') barlist[bar].set_edgecolor('k') # draw mao lines plt.plot([0, len(barlist)], [0.26, 0.26], color='k', linewidth=1.5, linestyle="--") plt.plot([0, len(barlist)], [-0.26, -0.26], color='k', linewidth=1.5, linestyle="--") # set Y lims plt.ylim(ylimits) plt.xlim([1, len(data[0, :])]) axes_pro = FontProperties() axes_pro.set_size('large') axes_pro.set_weight('bold') # label plt.xlabel(xlabel, fontproperties=axes_pro) plt.ylabel(ylabel, fontproperties=axes_pro) axes_pro.set_size('x-large') plt.title(title, fontproperties=axes_pro) # return plot object return plt
def plotFigure(score_data=None,release=True): pl.ion() font_size = 10 mpl.rcParams['font.family']="sans-serif" mpl.rcParams['font.sans-serif']="Arial" mpl.rcParams['font.size']=font_size mpl.rcParams['figure.dpi'] = 150 mpl.rcParams['font.weight']='medium' mpl.rcParams['figure.facecolor'] = 'white' mpl.rcParams['lines.linewidth'] = 0.8 mpl.rcParams['axes.facecolor'] = 'white' mpl.rcParams['font.size'] = font_size mpl.rcParams['patch.edgecolor'] = 'black' val = utils.Validation() categories = ['all','pure','cat1','cat2','cat3','cat4','cat5'] humvar = sp.zeros(7) exovar = sp.zeros(7) varibench_selected = sp.zeros(7) predictSNP_selected = sp.zeros(7) swissvar_selected = sp.zeros(7) datasets = ['humvar','exovar','varibench_selected','predictSNP_selected','swissvar_selected'] for dataset in datasets: score_data.selectDataset(dataset) score_data.loadCategories() for i,cat in enumerate(categories): if cat=="all": labels = score_data.getTrueLabels() if dataset=='humvar': humvar[i] = val.getROCStats(labels,score_data.getScores('fathmm_w'))['auc'] elif dataset=='exovar': exovar[i] = val.getROCStats(labels,score_data.getScores('fathmm_w'))['auc'] elif dataset=='swissvar_selected': swissvar_selected[i] = val.getROCStats(labels,score_data.getScores('fathmm_w'))['auc'] elif dataset=='predictSNP_selected': predictSNP_selected[i] = val.getROCStats(labels,score_data.getScores('fathmm_w'))['auc'] else: varibench_selected[i] = val.getROCStats(labels,score_data.getScores('fathmm_w'))['auc'] else: [labels,scores] = score_data.getData4Categorie(category=cat,tool_name='fathmm_w') if dataset=='humvar': humvar[i] = val.getROCStats(labels,scores)['auc'] elif dataset=='exovar': exovar[i] = val.getROCStats(labels,scores)['auc'] elif dataset=='predictSNP_selected': predictSNP_selected[i] = val.getROCStats(labels,scores)['auc'] elif dataset=='swissvar_selected': swissvar_selected[i] = val.getROCStats(labels,scores)['auc'] else: varibench_selected[i] = val.getROCStats(labels,scores)['auc'] pl.figure(figsize=(10,7)) font = FontProperties() font.set_weight('bold') plotBar(humvar,0,321,"HumVar",flag=False) ax = plotBar(exovar,1,322,"ExoVar",flag=True) plotBar(varibench_selected,3,323,"VariBenchSelected",flag=False) plotBar(predictSNP_selected,4,324,"predictSNPSelected",flag=True) plotBar(swissvar_selected,5,325,"SwissVarSelected",flag=False) rect = pl.Rectangle((0,0),1,1,fill=None) leg = ax.legend([rect,hatch,circle],['FatHMM-W','Type 1 Biased','Type 2 Biased'],loc='upper center', bbox_to_anchor=(0.0, 1.15),fancybox=True, ncol=5,prop={'size':10},numpoints=1) leg.get_frame().set_alpha(0.2) leg.get_frame().set_edgecolor("none") pl.subplots_adjust(left=0.065,bottom=0.11,right=0.99,top=0.94,wspace=0.03,hspace=0.5) if release: pl.savefig(os.path.abspath('Output/Supplementary/FigureS11.pdf')) else: pl.savefig(os.path.abspath('Output/Supplementary/FigureS11.pdf')) pl.savefig(os.path.abspath('Output/Supplementary/FigureS11.tiff'),dpi=300) pl.savefig(os.path.abspath('Output/Supplementary/FigureS11.jpg')) pl.close()
def _get_2d_plot(self, label_stable=True, label_unstable=True): """ Shows the plot using pylab. Usually I won"t do imports in methods, but since plotting is a fairly expensive library to load and not all machines have matplotlib installed, I have done it this way. """ plt = get_publication_quality_plot(8, 6) from matplotlib.font_manager import FontProperties (lines, labels, unstable) = self.pd_plot_data for x, y in lines: plt.plot(x, y, "ko-", linewidth=3, markeredgecolor="k", markerfacecolor="b", markersize=15) font = FontProperties() font.set_weight("bold") font.set_size(24) # Sets a nice layout depending on the type of PD. Also defines a # "center" for the PD, which then allows the annotations to be spread # out in a nice manner. if len(self._pd.elements) == 3: plt.axis("equal") plt.xlim((-0.1, 1.2)) plt.ylim((-0.1, 1.0)) plt.axis("off") center = (0.5, math.sqrt(3) / 6) else: all_coords = labels.keys() miny = min([c[1] for c in all_coords]) ybuffer = max(abs(miny) * 0.1, 0.1) plt.xlim((-0.1, 1.1)) plt.ylim((miny - ybuffer, ybuffer)) center = (0.5, miny / 2) plt.xlabel("Fraction", fontsize=28, fontweight="bold") plt.ylabel("Formation energy (eV/fu)", fontsize=28, fontweight="bold") for coords in sorted(labels.keys(), key=lambda x: -x[1]): entry = labels[coords] label = entry.name # The follow defines an offset for the annotation text emanating # from the center of the PD. Results in fairly nice layouts for the # most part. vec = np.array(coords) - center vec = vec / np.linalg.norm(vec) * 10 if np.linalg.norm(vec) != 0 else vec valign = "bottom" if vec[1] > 0 else "top" if vec[0] < -0.01: halign = "right" elif vec[0] > 0.01: halign = "left" else: halign = "center" if label_stable: plt.annotate( latexify(label), coords, xytext=vec, textcoords="offset points", horizontalalignment=halign, verticalalignment=valign, fontproperties=font, ) if self.show_unstable: font = FontProperties() font.set_size(16) for entry, coords in unstable.items(): vec = np.array(coords) - center vec = vec / np.linalg.norm(vec) * 10 label = entry.name plt.plot( coords[0], coords[1], "ks", linewidth=3, markeredgecolor="k", markerfacecolor="r", markersize=8 ) if label_unstable: plt.annotate( latexify(label), coords, xytext=vec, textcoords="offset points", horizontalalignment=halign, color="b", verticalalignment=valign, fontproperties=font, ) F = plt.gcf() F.set_size_inches((8, 6)) plt.subplots_adjust(left=0.09, right=0.98, top=0.98, bottom=0.07) return plt
if fobs[ii] == 'NUV': mags.append(mag[ii]) snums.append(snum) plot(snums,mags,marker='h',color='#95B9C7',ms=12) ii = ii + 1 then = time.time() time = then -now ########################### ### plotting commands ########################### xl = [0.2,float(len(snlist))+0.1] yl = [min(mag)-0.6,max(mag)+0.6] legend(('Bessell', 'Sloan', 'NIR(Vega)', 'NIR(ab)','SwiftUV(Vega)','SwiftUV(ab)','GALEX'), numpoints=1,bbox_to_anchor=(1.01, 1), loc=2, borderaxespad=0.) font = FontProperties() font.set_weight('bold') text(0.3,max(mag)-((max(mag)-min(mag))/18),'U-Bessell',fontproperties=font,fontsize = 12, color = 'darkblue') text(0.3,max(mag)-(2*(max(mag)-min(mag))/18),'B-Bessell',fontproperties=font,fontsize = 12, color = 'c') text(0.3, max(mag)-(3*(max(mag)-min(mag))/18),'V-Bessell',fontproperties=font,fontsize = 12, color = 'yellow') text(0.3, max(mag)-(4*(max(mag)-min(mag))/18),'R-Bessell',fontproperties=font,fontsize = 12, color = '#C35817') text(0.3, max(mag)-(5*(max(mag)-min(mag))/18),'I-Bessell',fontproperties=font,fontsize = 12, color = 'm') text(0.3, max(mag)-(6*(max(mag)-min(mag))/18),'u-Sloan',fontproperties=font,fontsize = 12, color = 'b') text(0.3, max(mag)-(7*(max(mag)-min(mag))/18),'g-Sloan',fontproperties=font,fontsize = 12, color = 'g') text(0.3, max(mag)-(8*(max(mag)-min(mag))/18),'r-Sloan',fontproperties=font,fontsize = 12, color = 'orange') text(0.3, max(mag)-(9*(max(mag)-min(mag))/18),'i-Slaon',fontproperties=font,fontsize = 12, color = 'r') text(0.3, max(mag)-(10*(max(mag)-min(mag))/18),'z-Sloan',fontproperties=font,fontsize = 12, color = 'brown') text(0.3, max(mag)-(11*(max(mag)-min(mag))/18),'J-2MASS',fontproperties=font,fontsize = 12, color = '#6F4E37') text(0.3, max(mag)-(12*(max(mag)-min(mag))/18),'H-2MASS',fontproperties=font,fontsize = 12, color = '#B87333') text(0.3, max(mag)-(13*(max(mag)-min(mag))/18),'K-2MASS',fontproperties=font,fontsize = 12, color = '#827B60') text(0.3, max(mag)-(14*(max(mag)-min(mag))/18),'uvw1-UVOT',fontproperties=font,fontsize = 12, color = '#7FFFD4') text(0.3, max(mag)-(15*(max(mag)-min(mag))/18),'uvm2-UVOT',fontproperties=font,fontsize = 12, color = '#6960EC')
def write_image(self, stream, image_format="svg"): ''' Writes the phase diagram to an image in a stream. Args: stream: stream to write to. Can be a file stream or a StringIO stream. image_format format for image. Can be any of matplotlib supported formats. Defaults to svg for best results for vector graphics. ''' (lines, labels, unstable) = self.pd_plot_data dim = len(self._pd.elements) elementref = re.compile("^[A-Z][a-z]*$") count = 1 import matplotlib as mpl from matplotlib.font_manager import FontProperties # chose a non-GUI backend mpl.use('Agg') import matplotlib.pyplot as plt font = FontProperties() font.set_weight('bold') font.set_size(20) if dim == 4: plt.clf() plt.cla() import mpl_toolkits.mplot3d.axes3d as p3 fig = plt.figure() ax = p3.Axes3D(fig) newlabels = list() for x, y, z in lines: ax.plot(x, y, z, 'bo-', linewidth=4, markeredgecolor='b', markerfacecolor='r', markersize=12) for coords in sorted(labels.keys()): label = labels[coords].name if elementref.match(label): ax.text(coords[0], coords[1], coords[2], label, fontproperties=font) else: ax.text(coords[0], coords[1], coords[2], str(count), fontproperties=font) newlabels.append(str(count) + " : " + label) count += 1 plt.figtext(0.01, 0.01, '\n'.join(newlabels), fontproperties=font) elif dim < 4 and dim > 1: plt.clf() plt.cla() for x, y in lines: plt.plot(x, y, 'bo-', linewidth=4, markeredgecolor='b', markerfacecolor='r', markersize=12) if dim == 3: plt.axis('equal') plt.xlim((-0.02, 1.18)) plt.ylim((-0.1, 1.0)) plt.axis('off') legendstart = [1.0, 1.0] legendspacing = 0.05 else: plt.xlim((-0.1, 1.4)) legendstart = [1.1, 0.0] ymin, ymax = plt.ylim() legendspacing = (ymax - ymin) / len(labels) for coords in sorted(labels.keys()): label = labels[coords].name x = coords[0] if coords[0] >= math.sqrt(3) / 2: halign = 'left' x += 0.02 else: halign = 'right' x += -0.02 if coords[1] > 0: valign = 'bottom' else: valign = 'top' if elementref.match(label): plt.text(x, coords[1], label, horizontalalignment=halign, verticalalignment=valign, fontproperties=font) else: plt.text(x, coords[1], str(count), horizontalalignment=halign, verticalalignment=valign, fontproperties=font) plt.text(legendstart[0], legendstart[1] - legendspacing * count, str(count) + " : " + label, horizontalalignment='left', verticalalignment='top', fontproperties=font) count += 1 f = plt.gcf() f.set_size_inches((12, 10)) plt.savefig(stream, format=image_format)
def _get_2d_plot(self, label_stable=True, label_unstable=True, ordering=None, energy_colormap=None, vmin_mev=-60.0, vmax_mev=60.0, show_colorbar=True, process_attributes=False): """ Shows the plot using pylab. Usually I won't do imports in methods, but since plotting is a fairly expensive library to load and not all machines have matplotlib installed, I have done it this way. """ plt = get_publication_quality_plot(8, 6) from matplotlib.font_manager import FontProperties if ordering is None: (lines, labels, unstable) = self.pd_plot_data else: (_lines, _labels, _unstable) = self.pd_plot_data (lines, labels, unstable) = order_phase_diagram( _lines, _labels, _unstable, ordering) if energy_colormap is None: if process_attributes: for x, y in lines: plt.plot(x, y, "k-", linewidth=3, markeredgecolor="k") # One should think about a clever way to have "complex" # attributes with complex processing options but with a clear # logic. At this moment, I just use the attributes to know # whether an entry is a new compound or an existing (from the # ICSD or from the MP) one. for x, y in labels.keys(): if labels[(x, y)].attribute is None or \ labels[(x, y)].attribute == "existing": plt.plot(x, y, "ko", linewidth=3, markeredgecolor="k", markerfacecolor="b", markersize=12) else: plt.plot(x, y, "k*", linewidth=3, markeredgecolor="k", markerfacecolor="g", markersize=18) else: for x, y in lines: plt.plot(x, y, "ko-", linewidth=3, markeredgecolor="k", markerfacecolor="b", markersize=15) else: from matplotlib.colors import Normalize, LinearSegmentedColormap from matplotlib.cm import ScalarMappable pda = PDAnalyzer(self._pd) for x, y in lines: plt.plot(x, y, "k-", linewidth=3, markeredgecolor="k") vmin = vmin_mev / 1000.0 vmax = vmax_mev / 1000.0 if energy_colormap == 'default': mid = - vmin / (vmax - vmin) cmap = LinearSegmentedColormap.from_list( 'my_colormap', [(0.0, '#005500'), (mid, '#55FF55'), (mid, '#FFAAAA'), (1.0, '#FF0000')]) else: cmap = energy_colormap norm = Normalize(vmin=vmin, vmax=vmax) _map = ScalarMappable(norm=norm, cmap=cmap) _energies = [pda.get_equilibrium_reaction_energy(entry) for coord, entry in labels.items()] energies = [en if en < 0.0 else -0.00000001 for en in _energies] vals_stable = _map.to_rgba(energies) ii = 0 if process_attributes: for x, y in labels.keys(): if labels[(x, y)].attribute is None or \ labels[(x, y)].attribute == "existing": plt.plot(x, y, "o", markerfacecolor=vals_stable[ii], markersize=12) else: plt.plot(x, y, "*", markerfacecolor=vals_stable[ii], markersize=18) ii += 1 else: for x, y in labels.keys(): plt.plot(x, y, "o", markerfacecolor=vals_stable[ii], markersize=15) ii += 1 font = FontProperties() font.set_weight("bold") font.set_size(24) # Sets a nice layout depending on the type of PD. Also defines a # "center" for the PD, which then allows the annotations to be spread # out in a nice manner. if len(self._pd.elements) == 3: plt.axis("equal") plt.xlim((-0.1, 1.2)) plt.ylim((-0.1, 1.0)) plt.axis("off") center = (0.5, math.sqrt(3) / 6) else: all_coords = labels.keys() miny = min([c[1] for c in all_coords]) ybuffer = max(abs(miny) * 0.1, 0.1) plt.xlim((-0.1, 1.1)) plt.ylim((miny - ybuffer, ybuffer)) center = (0.5, miny / 2) plt.xlabel("Fraction", fontsize=28, fontweight='bold') plt.ylabel("Formation energy (eV/fu)", fontsize=28, fontweight='bold') for coords in sorted(labels.keys(), key=lambda x: -x[1]): entry = labels[coords] label = entry.name # The follow defines an offset for the annotation text emanating # from the center of the PD. Results in fairly nice layouts for the # most part. vec = (np.array(coords) - center) vec = vec / np.linalg.norm(vec) * 10 if np.linalg.norm(vec) != 0 \ else vec valign = "bottom" if vec[1] > 0 else "top" if vec[0] < -0.01: halign = "right" elif vec[0] > 0.01: halign = "left" else: halign = "center" if label_stable: if process_attributes and entry.attribute == 'new': plt.annotate(latexify(label), coords, xytext=vec, textcoords="offset points", horizontalalignment=halign, verticalalignment=valign, fontproperties=font, color='g') else: plt.annotate(latexify(label), coords, xytext=vec, textcoords="offset points", horizontalalignment=halign, verticalalignment=valign, fontproperties=font) if self.show_unstable: font = FontProperties() font.set_size(16) pda = PDAnalyzer(self._pd) energies_unstable = [pda.get_e_above_hull(entry) for entry, coord in unstable.items()] if energy_colormap is not None: energies.extend(energies_unstable) vals_unstable = _map.to_rgba(energies_unstable) ii = 0 for entry, coords in unstable.items(): vec = (np.array(coords) - center) vec = vec / np.linalg.norm(vec) * 10 \ if np.linalg.norm(vec) != 0 else vec label = entry.name if energy_colormap is None: plt.plot(coords[0], coords[1], "ks", linewidth=3, markeredgecolor="k", markerfacecolor="r", markersize=8) else: plt.plot(coords[0], coords[1], "s", linewidth=3, markeredgecolor="k", markerfacecolor=vals_unstable[ii], markersize=8) if label_unstable: plt.annotate(latexify(label), coords, xytext=vec, textcoords="offset points", horizontalalignment=halign, color="b", verticalalignment=valign, fontproperties=font) ii += 1 if energy_colormap is not None and show_colorbar: _map.set_array(energies) cbar = plt.colorbar(_map) cbar.set_label( 'Energy [meV/at] above hull (in red)\nInverse energy [' 'meV/at] above hull (in green)', rotation=-90, ha='left', va='center') ticks = cbar.ax.get_yticklabels() cbar.ax.set_yticklabels(['${v}$'.format( v=float(t.get_text().strip('$'))*1000.0) for t in ticks]) f = plt.gcf() f.set_size_inches((8, 6)) plt.subplots_adjust(left=0.09, right=0.98, top=0.98, bottom=0.07) return plt
from matplotlib.backends.backend_agg import Figure, FigureCanvas from matplotlib.gridspec import GridSpec from matplotlib.font_manager import FontProperties from matplotlib.ticker import FuncFormatter from matplotlib import rcParams from matplotlib.dates import DateFormatter, num2date from matplotlib.dates import AutoDateFormatter, AutoDateLocator from datetime import datetime ts2date = datetime.fromtimestamp mplfont = FontProperties() mplfont.set_size(11) mplfont.set_weight('semibold') matplotlib.rc('xtick', labelsize=10) matplotlib.rc('ytick', labelsize=10) matplotlib.rc('grid', linewidth=0.5, color='#EDEDED', linestyle='-') matplotlib.rc('savefig', dpi=150) plotopts = dict(linewidth=2.0, marker='s', markersize=3.5, markeredgewidth=0.0, drawstyle='steps-post', zorder=25) def auto_margins(fig, canvas, axes, gspec): """automatically set margins""" trans = fig.transFigure.inverted().transform l, t, r, b, dl, dt, dr, db = [0.025]*8 for ax in fig.get_axes():
def _draw_tracks(self, **kwargs): '''create an axis for each track and moves accordingly all the child features''' self.Drawn_objects = [] self.track_axes = [] draw_xmin = kwargs.get('xmin', None) draw_xmax = kwargs.get('xmax', None) if draw_xmin is not None: self.xmin = draw_xmin if draw_xmax is not None: self.xmax = draw_xmax '''estimate track height using track.drawn_lines find max and min x coords, and check for colorbar presence in at least one track''' cbars = False self.drawn_lines = 0 Xs =[] track_height_user_specified = False for track in self.tracks: if track.features:#skip tracks with no features if track.track_height and self.fig_height: #if not fig_height is specified user track heights are ignored track_height_user_specified = True if track_height_user_specified and not track.track_height: track_height_user_specified = False #disable if some track has not a specified heigth warnings.warn('All tracks need to have a specified track_height, reverting to automatic track height') track._sort_features(dpi=self.dpi, xoffset=self.xmin) #THIS WILL DRAW ALL THE FEATURES if track.draw_cb: if cbars != 'label': cbars = 'simple' if track.cb_label: cbars = 'label' self.drawn_lines += track.drawn_lines Xs.append(track.xmin) Xs.append(track.xmax) if self.xmin is None: self.xmin = min(Xs) if Xs != [] else 0 if self.xmax is None: self.xmax = max(Xs) '''auto estimate fig_heigth and panning if needed ''' if not self.fig_height: #automatically set fig height basing on the total number of features self.fig_height = self._estimate_fig_height() self.vpadding = (float(self.padding)/self.dpi) / self.fig_height self.vtrack_padding = (float(self.track_padding)/self.dpi) / self.fig_height #print("vtrack_padding", self.fig_height, self.padding, self.track_padding, self.dpi, self.fig_height, self.vpadding, self.vtrack_padding) if self.use_existing_figure: self.axisHeightScaling = self.fig_height / self.existing_fig_height # print("self.axisHeightScaling", self.axisHeightScaling) # plt.gcf().set_figheight(self.existing_fig_height + self.fig_height) # plt.gcf().subplots_adjust(bottom=self.axisHeightScaling) else: self.axisHeightScaling = 1.0 '''set colorbar dimension ''' if cbars == 'label': cbar_extent=0.015 cbar_axis_space = 0.05 cbar_right_pad = 0.03 else: cbar_extent=0.015 cbar_axis_space = 0.05 cbar_right_pad = 0.01 '''arrange tracks''' axis_left_pad = self.hpadding default_figure_bottom_space = self.vpadding + float(self.figure_bottom_space)/self.dpi if self.use_existing_figure: default_figure_bottom_space = 0. axis_bottom_pad = 0.0 - default_figure_bottom_space else: axis_bottom_pad = 1.0 - default_figure_bottom_space axis_width = 1.-2*self.hpadding axis_scale = None# used to persist the same scale on all the tracks if cbars: axis_width -= (cbar_extent + cbar_axis_space + cbar_right_pad) if self.use_existing_figure: # Use the same axis width as the figure axis_width = self.ax.get_position().width '''cycle trought tracks and draw them as axix object ''' #canvas_height = 0 for track_num, track in enumerate(self.tracks): if track.features:#skip tracks with no features '''define axis dimensions and position and create axis''' if track_height_user_specified: axis_height = track.track_height /float(self.fig_height) else: if axis_scale: axis_height = axis_scale * track.drawn_lines else: axis_height = (float(track.drawn_lines)/self.drawn_lines) - self.vpadding/(2.*len(self.tracks)) axis_scale = axis_height / float(track.drawn_lines) axis_bottom_pad -= (axis_height + self.vtrack_padding/2.) axis = matplotlib.pyplot.axes([axis_left_pad, axis_bottom_pad*self.axisHeightScaling, axis_width, axis_height*self.axisHeightScaling ], label=track_num) self.track_axes.append(axis) '''handle track axis display, ticks and tickslabel ''' '''set Y lims ''' if isinstance(track, PlotTrack): if track.show_name: if track.show_name == 'top': axis.set_ylim(track.Ycord, track.ymax+1) track_name = axis.text(self.xmin + (self.xmax * 0.01), track.ymax + .5, track.name, horizontalalignment='left', verticalalignment='bottom', fontproperties=track.name_font_feat,) elif track.show_name == 'bottom': axis.set_ylim(track.Ycord-1, track.ymax) track_name = axis.text(self.xmin + (self.xmax * 0.01), track.Ycord - .5, track.name, horizontalalignment='left', verticalalignment='bottom', fontproperties=track.name_font_feat,) else: axis.set_ylim(track.Ycord, track.ymax) else: if track.show_name: if track.show_name == 'top': axis.set_ylim(track.Ycord, track.ymax+2.5) track_name = axis.text(self.xmin + (self.xmax * 0.01), track.ymax + 1.5, track.name, horizontalalignment='left', verticalalignment='bottom', fontproperties=track.name_font_feat,) elif track.show_name == 'bottom': axis.set_ylim(track.Ycord-1, track.ymax + 1.5) track_name = axis.text(self.xmin + (self.xmax * 0.01), track.Ycord - 0., track.name, horizontalalignment='left', verticalalignment='bottom', fontproperties=track.name_font_feat,) else: axis.set_ylim(track.Ycord, track.ymax+1.5,) '''set X lims''' axis.set_xlim(self.xmin, self.xmax) '''handle last bottom axis ''' if (track_num+1 == len(self.tracks)) and ('force no axis' not in track.draw_axis): track.draw_axis.append('bottom') if not self.track_padding: if (track_num+1 != len(self.tracks)): if 'bottom' in track.draw_axis: del track.draw_axis[track.draw_axis.index('bottom')] if 'top' in track.draw_axis: del track.draw_axis[track.draw_axis.index('top')] axis.spines["top"].set_color('none') '''handle axis and ticks''' for spine in ["right", "left", "top", "bottom"]: if spine not in track.draw_axis: axis.spines[spine].set_color('none')# don't draw axis if ("right" not in track.draw_axis) and ("left" not in track.draw_axis): axis.yaxis.set_ticks([])# dont'show ticks and labels on y if 'top' not in track.draw_axis: axis.xaxis.set_ticks_position('bottom')# only show bottom ticks if 'right' not in track.draw_axis: axis.yaxis.set_ticks_position('left')# only show left ticks '''handle X ticks and labels ''' step=int(round(self.xmax/10.,1-len(str(int(self.xmax / 10.))))) auto_X_major_ticks = range(self.xmin, self.xmax + 1, step) step_min = step / 4. tick = auto_X_major_ticks[0] auto_X_minor_ticks =[] while tick <= self.xmax: auto_X_minor_ticks.append(int(round(tick))) tick+= step_min '''use sequence as X ticks ''' if track.x_use_sequence: if len(track.x_use_sequence) < self.xmax-self.xmin: raise Exception('Sequence must be of the same length of X coords') track.xticks_minor = [] track.xticklabels_minor = [] for i, seq in enumerate(track.x_use_sequence): if self.xmin+i <= self.xmax: track.xticks_minor.append(self.xmin+i) track.xticklabels_minor.append(str(seq)) '''major X ticks ''' X_major_ticks_labels = None if track.xticks_major != None: X_major_ticks = track.xticks_major if (track.xticklabels_major != None) \ and len(track.xticklabels_major) == len(track.xticks_major): X_major_ticks_labels = track.xticklabels_major else: X_major_ticks = auto_X_major_ticks if 'bottom' in track.draw_axis : axis.set_xticks(X_major_ticks) else: axis.set_xticks([]) '''major ticks labels ''' if (track_num+1 == len(self.tracks)) or track.show_xticklabels:# last track or forced display if X_major_ticks_labels == None: X_major_ticks_labels = [] for i in X_major_ticks: if isinstance(i, (float, int)): X_major_ticks_labels.append(i+ self.start_position) else: X_major_ticks_labels.append(i) axis.set_xticklabels(X_major_ticks_labels, fontsize=track.tickfontsize) if track.x_use_sequence: axis.xaxis.set_tick_params(pad = 15, ) else: axis.set_xticklabels([]) '''minor X ticks ''' X_minor_ticks_labels = None if track.xticks_minor != None: X_minor_ticks = track.xticks_minor if (track.xticklabels_minor != None) \ and len(track.xticklabels_minor) == len(track.xticks_minor): X_minor_ticks_labels = track.xticklabels_minor else: X_minor_ticks = auto_X_minor_ticks if 'bottom' in track.draw_axis : axis.set_xticks(X_minor_ticks, minor=True) else: axis.set_xticks([], minor=True) '''minor ticks labels ''' if (track_num+1 == len(self.tracks)) or track.show_xticklabels:# last track or forced display if X_minor_ticks_labels == None: X_minor_ticks_labels = [] '''for i in X_minor_ticks: if i in X_major_ticks: X_minor_ticks_labels.append('') else: label = '' if isinstance(i, (float, int)): label = str(i+ self.start_position) else: label = i if (len(str(i).split('.')[0])>=4) : #avoid too long minor ticks label = '' X_minor_ticks_labels = [] break#no minor ticks displayed X_minor_ticks_labels.append(label)''' axis.set_xticklabels(X_minor_ticks_labels, fontsize=track.tickfontsize_minor, minor=True) else: axis.set_xticklabels([], minor=True) '''handle Y ticks and labels ''' '''major Y ticks ''' Y_major_ticks_labels = None if track.yticks_major != None: Y_major_ticks = track.yticks_major if (track.yticklabels_major != None) \ and len(track.yticklabels_major) == len(track.yticks_major): Y_major_ticks_labels = track.yticklabels_major else: Y_major_ticks = None if ('left' in track.draw_axis) and track.yticks_major: axis.set_yticks(Y_major_ticks) '''major ticks labels ''' if Y_major_ticks and track.show_yticklabels: if Y_major_ticks_labels == None: Y_major_ticks_labels = [] for i in Y_major_ticks: Y_major_ticks_labels.append(i) axis.set_yticklabels(Y_major_ticks_labels, fontsize=track.tickfontsize) else: axis.yaxis.set_tick_params(labelsize=track.tickfontsize) '''minor Y ticks ''' Y_minor_ticks_labels = None if track.yticks_minor is not None: Y_minor_ticks = track.yticks_minor if (track.yticklabels_minor is not None) \ and len(track.yticklabels_minor) == len(track.yticks_minor): Y_minor_ticks_labels = track.yticklabels_minor else: Y_minor_ticks = None if ('left' in track.draw_axis) and track.yticks_minor: axis.set_yticks(Y_minor_ticks, minor=True) '''minor ticks labels ''' if Y_minor_ticks and track.show_yticklabels: if Y_minor_ticks_labels is None: Y_minor_ticks_labels = [] for i in Y_minor_ticks: if i in Y_major_ticks: Y_minor_ticks_labels.append('') else: Y_minor_ticks_labels.append(i) axis.set_yticklabels(Y_minor_ticks_labels, fontsize=track.tickfontsize_minor, minor=True) else: axis.yaxis.set_tick_params(which='minor', labelsize=track.tickfontsize) '''draw grid''' if self.grid: if (self.grid == 'major') or (self.grid == 'both'): for X in auto_X_major_ticks: axis.axvline(X,ls=':',c='grey',alpha=0.66, zorder = -1) if (self.grid == 'minor') or (self.grid == 'both'): for X in auto_X_minor_ticks: axis.axvline(X,ls=':',c='grey',alpha=0.33, zorder = -1) '''add feature patches to track axes ''' for feature in track.features: self.Drawn_objects.append(feature) for patch in feature.patches: if isinstance(patch, matplotlib.lines.Line2D): axis.add_line(patch) elif isinstance(patch, matplotlib.patches.Patch): axis.add_patch(patch) else: axis.add_artist(patch) patch.set_transform(axis.transData)# IMPORTANT WORKAROUND!!! if not manually set, transform is not passed correctly in Line2D objects feature.draw_feat_name(ax=axis) for feat_name in feature.feat_name: #feat_name.set_visible(True) axis.add_artist(feat_name) if track.draw_cb: cb_axis = matplotlib.pyplot.axes([axis_left_pad + axis_width + cbar_axis_space - cbar_right_pad ,axis_bottom_pad, cbar_extent, axis_height ],) if (track.min_score == None) and (track.max_score == None): for feat in track.features: if feat.norm != None: track.norm = feat.norm break cb1 = matplotlib.colorbar.ColorbarBase(cb_axis, cmap=track.cm, norm=track.norm, alpha = track.cb_alpha, orientation='vertical') if track.cb_label: cb1.set_label(track.cb_label) #cb_axis.axes.set_axis_off() for label in cb_axis.get_yticklabels(): label.set_fontsize('xx-small') '''handle legend ''' legend_font=FontProperties() legend_font.set_size('x-small') legend_font.set_family('serif') legend_font.set_weight('normal') axis.legend(prop = legend_font) if not self.use_existing_figure: '''set panel size and panning ''' self.fig.set_figheight(self.fig_height) self.fig.set_figwidth(self.fig_width)
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)
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)
class GraphicsContext(basecore2d.GraphicsContextBase): def __init__(self, size, dpi=72, format='svg', renderer=None, *args, **kwargs): super(GraphicsContext, self).__init__(self, size, *args, **kwargs) width, height = size self.size = size self._height = height self.contents = StringIO() self._clipmap = {} self.format = format self._font_prop = FontProperties(weight='roman') self.state._transformed_clip_path = None import matplotlib.pyplot as plt self.figure = plt.figure() self._backend = renderer def render(self, format): return self.contents.getvalue() def clear(self): # TODO: clear the contents pass def width(self): return self.size[0] def height(self): return self.size[1] def save(self, filename): f = open(filename, 'w') self._backend.finalize() f.write(self.contents.getvalue()) f.close() # Text handling code def set_font(self, font): import kiva.constants as kc # Mapping of strings to valid Kiva font families: font_families = { kc.DEFAULT: 'default', kc.DECORATIVE: 'decorative', kc.ROMAN: 'rm', kc.SCRIPT: 'script', kc.SWISS: 'swiss', kc.MODERN: 'cm', } self.state.font = font face_name = font.face_name if face_name == '': face_name = 'Bitstream Vera Sans' else: face_name = font_families[font.family] self._font_prop.set_size(font.size) self._font_prop.set_weight('bold' if font.weight else 'regular') self._font_prop.set_family(face_name) def device_show_text(self, text): ttm = self.get_text_matrix() ctm = self.get_ctm() # not device_ctm!! m = affine.concat(ctm,ttm) tx,ty,sx,sy,angle = affine.trs_factor(m) angle = angle * 180. / pi gc = self._backend.new_gc() text = unicode_to_mathtext(text) if self._backend.flipy(): ty = self.height() - ty self._backend.draw_text(gc, tx, ty - 1, text, self._font_prop, angle, ismath=True) gc.restore() def device_get_full_text_extent(self, text): text = unicode_to_mathtext(text) width, height, descent = self._backend.get_text_width_height_descent(text, self._font_prop, ismath=True) return width, height, descent, 0. #height*1.2 # assume leading of 1.2*height # actual implementation =) def device_draw_image(self, img, rect): """ draw_image(img_gc, rect=(x,y,w,h)) Draws another gc into this one. If 'rect' is not provided, then the image gc is drawn into this one, rooted at (0,0) and at full pixel size. If 'rect' is provided, then the image is resized into the (w,h) given and drawn into this GC at point (x,y). img_gc is either a Numeric array (WxHx3 or WxHx4) or a GC from Kiva's Agg backend (kiva.agg.GraphicsContextArray). Requires the Python Imaging Library (PIL). """ from PIL import Image as PilImage from matplotlib import _image # We turn img into a PIL object, since that is what ReportLab # requires. To do this, we first determine if the input image # GC needs to be converted to RGBA/RGB. If so, we see if we can # do it nicely (using convert_pixel_format), and if not, we do # it brute-force using Agg. if type(img) == type(array([])): # Numeric array converted_img = agg.GraphicsContextArray(img, pix_format='rgba32') format = 'RGBA' elif isinstance(img, agg.GraphicsContextArray): if img.format().startswith('RGBA'): format = 'RGBA' elif img.format().startswith('RGB'): format = 'RGB' else: converted_img = img.convert_pixel_format('rgba32', inplace=0) format = 'RGBA' # Should probably take this into account # interp = img.get_image_interpolation() else: warnings.warn("Cannot render image of type %r into SVG context." % type(img)) return if rect == None: rect = (0, 0, img.width(), img.height()) width, height = img.width(), img.height() # converted_img now holds an Agg graphics context with the image pil_img = PilImage.fromstring(format, (converted_img.width(), converted_img.height()), converted_img.bmp_array.tostring()) left, top, width, height = rect if width != img.width() or height != img.height(): # This is not strictly required. pil_img = pil_img.resize((int(width), int(height)), PilImage.NEAREST) pil_img = pil_img.transpose(PilImage.FLIP_TOP_BOTTOM) # Fix for the SVG backend, which seems to flip x when a transform is provided. if self._backend.flipy(): pil_img = pil_img.transpose(PilImage.FLIP_LEFT_RIGHT) mpl_img = _image.frombuffer(pil_img.tostring(), width, height, True) mpl_img.is_grayscale = False gc = self._backend.new_gc() if self.state.clipping_path: gc.set_clip_path(self._get_transformed_clip_path()) transform = Affine2D.from_values(*affine.affine_params(self.get_ctm())) self._backend.draw_image(gc, left, top, mpl_img, dx=width, dy=height, transform=transform) gc.restore() def device_fill_points(self, points, mode): if mode in (FILL, FILL_STROKE, EOF_FILL_STROKE, EOF_FILL): fill = tuple(self.state.fill_color) else: fill = None if mode in (STROKE, FILL_STROKE, EOF_FILL_STROKE): color = tuple(self.state.line_color) else: color = tuple(self.state.fill_color) path = Path(points) gc = self._backend.new_gc() gc.set_linewidth(self.state.line_width) if not (self.state.line_dash[1] == 0).all(): gc.set_dashes(self.state.line_dash[0], list(self.state.line_dash[1])) if self.state.clipping_path: gc.set_clip_path(self._get_transformed_clip_path()) gc.set_joinstyle(line_join_map[self.state.line_join]) gc.set_capstyle(line_cap_map[self.state.line_cap]) gc.set_foreground(color, isRGB=True) gc.set_alpha(self.state.alpha) transform = Affine2D.from_values(*affine.affine_params(self.get_ctm())) self._backend.draw_path(gc, path, transform, fill) gc.restore() def _get_transformed_clip_path(self): x, y, width, height = self.state.clipping_path rect = ((x, y), (x+width, y), (x+width, y+height), (x, y+height)) transform = Affine2D.from_values(*affine.affine_params(self.get_ctm())) return TransformedPath(Path(rect), transform) # noops which seem to be needed def device_stroke_points(self, points, mode): # handled by device_fill_points pass def device_set_clipping_path(self, x, y, width, height): pass def device_destroy_clipping_path(self): pass def device_update_line_state(self): pass def device_update_fill_state(self): pass
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()