def _rainbow_gen(x,y,strings,colors,ax=None,kw=[dict()],add_space=True): """ See: rainbow_text, except kw is an array now. """ if ax is None: ax = plt.gca() t = ax.transData canvas = ax.figure.canvas # horizontal version n_kw = len(kw) for i,(s, c) in enumerate(zip(strings, colors)): if (add_space): s_text = s + " " else: s_text = s kw_tmp = sanitize_text_dict(kw[i % n_kw]) text = ax.text(x, y, s_text, color=c, transform=t, clip_on=False,**(kw_tmp)) text.draw(canvas.get_renderer()) ex = text.get_window_extent() if "\n" not in s: t = transforms.offset_copy(text._transform, x=ex.width, units='dots') else: t = transforms.offset_copy(text._transform, x=0,y=-ex.height/2, units='dots')
def alphatext(ax, x, y, ls, **kw): """ Take a list of strings ``ls`` and colors ``lc`` and place them next to each other, with text ls[i] being shown in color lc[i]. """ t = ax.transData #horizontal version if kw.get('rotation', 'horizontal') == 'horizontal': for s, c in ls: text = ax.text(x, y, s, alpha=c, transform=t, **kw) text.draw(ax.figure.canvas.get_renderer()) ex = text.get_window_extent() t = transforms.offset_copy(text._transform, x=-ex.width, units='dots') else: for s, c in ls: text = ax.text(x, y, s, alpha=c, transform=t, va='bottom', ha='center', **kw) text.draw(ax.figure.canvas.get_renderer()) ex = text.get_window_extent() t = transforms.offset_copy(text._transform, y=ex.height, units='dots')
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 rainbow_text(x,y,ls,lc,**kw): """ Take a list of strings ``ls`` and colors ``lc`` and place them next to each other, with text ls[i] being shown in color lc[i]. This example shows how to do both vertical and horizontal text, and will pass all keyword arguments to plt.text, so you can set the font size, family, etc. """ t = plt.gca().transData fig = plt.gcf() #### note: this line moved down ....### #plt.show() # ####################################### #horizontal version for s,c in zip(ls,lc): text = plt.text(x,y," "+s+" ",color=c, transform=t,fontsize=15,bbox=bb **kw) text.draw(fig.canvas.get_renderer()) ex = text.get_window_extent() t = transforms.offset_copy(text._transform, x=ex.width, units='dots') #vertical version for s,c in zip(ls,lc): text = plt.text(x,y," "+s+" ",color=c, transform=t, rotation=90,va='bottom',ha='center',**kw) text.draw(fig.canvas.get_renderer()) ex = text.get_window_extent() t = transforms.offset_copy(text._transform, y=ex.height, units='dots') t = plt.gca().transData fig = plt.gcf() plt.show() ############### when this is here, you can see that
def rainbow_text(x, y, strings, colors, orientation='horizontal', ax=None, **kwargs): if ax is None: ax = plt.gca() t = ax.transData canvas = ax.figure.canvas assert orientation in ['horizontal', 'vertical'] if orientation == 'vertical': kwargs.update(rotation=90, verticalalignment='bottom') for s, c in zip(strings, colors): text = ax.text(x, y, s + " ", color=c, transform=t, **kwargs) # Need to draw to update the text position. text.draw(canvas.get_renderer()) ex = text.get_window_extent() if orientation == 'horizontal': t = transforms.offset_copy(text.get_transform(), x=ex.width, units='dots') else: t = transforms.offset_copy(text.get_transform(), y=ex.height, units='dots')
def rainbow_text(x, y, ls, lc, **kw): t = plt.gca().transData figlocal = plt.gcf() space_size = 1.45 * kw['size'] #horizontal version for string, c in zip(ls, lc): string_raw = r'{}'.format(string) #string = str_text[1:-1] #string = string.encode('unicode_escape') text = plt.text(x, y, string_raw, color=c, transform=t, **kw) text.set_path_effects([ path_effects.Stroke(linewidth=2, foreground='black'), path_effects.Normal() ]) text.draw(figlocal.canvas.get_renderer()) ex = text.get_window_extent(renderer=figlocal.canvas.get_renderer()) if "odot" in string: #import pdb #pdb.set_trace() #t = transforms.offset_copy(text._transform, x=ex.width, units='dots') t = transforms.offset_copy(text._transform, x=0.75 * ex.width, units='dots') else: #import pdb #pdb.set_trace() #t = transforms.offset_copy(text._transform, x=space_size, units='dots') t = transforms.offset_copy(text._transform, x=0.75 * ex.width, units='dots')
def rainbow_text(x, y, strings, colors, orientation='horizontal', ax=None, f=None, fudge=1.5, **kwargs): """ Modified from https://matplotlib.org/3.1.1/gallery/text_labels_and_annotations/rainbow_text.html Take a list of *strings* and *colors* and place them next to each other, with text strings[i] being shown in colors[i]. Parameters ---------- x, y : float Text position in data coordinates. strings : list of str The strings to draw. colors : list of color The colors to use. orientation : {'horizontal', 'vertical'} ax : Axes, optional The Axes to draw into. If None, the current axes will be used. f : Figure, optional The Figure to draw into. **kwargs All other keyword arguments are passed to plt.text(), so you can set the font size, family, etc. """ if ax is None: ax = plt.gca() t = ax.transData canvas = ax.figure.canvas if f is not None: t = f.transFigure canvas = f.canvas assert orientation in ['horizontal', 'vertical'] if orientation == 'vertical': kwargs.update(rotation=90, verticalalignment='bottom') for s, c in zip(strings, colors): text = ax.text(x, y, s + " ", color=c, transform=t, **kwargs) # Need to draw to update the text position. text.draw(canvas.get_renderer()) ex = text.get_window_extent() if orientation == 'horizontal': t = transforms.offset_copy(text.get_transform(), x=fudge * ex.width, units='dots') else: t = transforms.offset_copy(text.get_transform(), y=ex.height, units='dots')
def rainbow_text(x, y, strings, colors, ax=None, **kw): """ Take a list of ``strings`` and ``colors`` and place them next to each other, with text strings[i] being shown in colors[i]. This example shows how to do both vertical and horizontal text, and will pass all keyword arguments to plt.text, so you can set the font size, family, etc. The text will get added to the ``ax`` axes, if provided, otherwise the currently active axes will be used. """ if ax is None: ax = plt.gca() t = ax.transData canvas = ax.figure.canvas # horizontal version for s, c in zip(strings, colors): text = ax.text(x, y, " " + s + " ", color=c, transform=t, **kw) text.draw(canvas.get_renderer()) ex = text.get_window_extent() t = transforms.offset_copy(text._transform, x=ex.width, units='dots') # vertical version for s, c in zip(strings, colors): text = ax.text(x, y, " " + s + " ", color=c, transform=t, rotation=90, va='bottom', ha='center', **kw) text.draw(canvas.get_renderer()) ex = text.get_window_extent() t = transforms.offset_copy(text._transform, y=ex.height, units='dots')
def draw_logo2(all_scores, fontfamily='Arial', size=80): if fontfamily == 'xkcd': plt.xkcd() else: mpl.rcParams['font.family'] = fontfamily window = Tk() window.title("Cluster") window.geometry('1120x300') canvas2 = Canvas(window, width=1100, height=420) canvas2.pack(expand=1, side=LEFT) 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, 3)) ax.set_xticklabels(range(1, len(all_scores) + 1), rotation=90) ax.set_yticklabels(np.arange(0, 3, 1)) seaborn.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=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') fig_photo2 = draw_figure(canvas2, fig) window.mainloop()
def rtext(x, y, strings, colors, ax=None, orientation='horizontal', **kw): """ Take a list of ``strings`` and ``colors`` and place them next to each other, with text strings[i] being shown in colors[i]. This example shows how to do both vertical and horizontal text, and will pass all keyword arguments to plt.text, so you can set the font size, family, etc. The text will get added to the ``ax`` axes, if provided, otherwise the currently active axes will be used. from: http://matplotlib.org/examples/text_labels_and_annotations/rainbow_text.html :param x: float, location on the plot (see plt.text) :param y: float, location on the plot (see plt.text) :param strings: list of strings, containing the words to color :param colors: list of strings, containing the colour of each word :param ax: plt.gca() axis or frame :param orientation: string, "h"/"horizontal" or "v"/"vertical" :param kw: dictionary, keyword arguments to be passed to plt.text :return: """ if ax is None: ax = plt.gca() t = ax.transData canvas = ax.figure.canvas if 'v' in orientation: # vertical version for s, c in zip(strings, colors): text = ax.text(x, y, s + " ", color=c, transform=t, rotation=90, va='bottom', ha='center', **kw) text.draw(canvas.get_renderer()) ex = text.get_window_extent() t = transforms.offset_copy(text._transform, y=ex.height, units='dots') else: # horizontal version for s, c in zip(strings, colors): text = ax.text(x, y, s + " ", color=c, transform=t, **kw) text.draw(canvas.get_renderer()) ex = text.get_window_extent() t = transforms.offset_copy(text._transform, x=ex.width, units='dots')
def draw_logo(all_scores, run, k): fig = plt.figure() fig.set_size_inches(len(all_scores) + 1, 2.5) ax = fig.add_subplot(111) ax.set_xticks(range(len(all_scores))) xshift = 0 trans_offset = transforms.offset_copy(ax.transAxes, fig=fig, x=0, y=0, units='points') for scores in all_scores: yshift = 0 for base, score in scores: txt = ax.text(0, 0, base, transform=trans_offset, fontsize=80, color=COLOR_SCHEME[base], weight='bold', ha='center', family='sans-serif') txt.set_clip_on(False) 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') xshift += window_ext.width trans_offset = transforms.offset_copy(ax.transAxes, fig=fig, x=xshift, units='points') ax.set_yticks(range(0, 3)) if type == "f": ax.set_ylabel("frequency") if type == "b": ax.set_ylabel("bits") seaborn.despine(ax=ax, offset=30, trim=True) ax.set_xticklabels(range(1, len(all_scores) + 1), rotation=90) ax.set_yticklabels(np.arange(0, 3, 1)) #plt.show() plt.savefig('figures/logo_' + str(identifier) + "_" + str(run) + "_" + str(k), dpi=600) plt.close()
def plot_stations(ax): def plot_frame(ax, start_lon, end_lon, start_lat, end_lat): # Plot frame linewidth = 15 ax.plot(np.array((start_lon,end_lon)), np.array((start_lat, start_lat)), color='black', ls='-', linewidth=linewidth, transform=ccrs.Geodetic()) ax.plot(np.array((start_lon,end_lon)), np.array((end_lat, end_lat)), color='black', ls='-', linewidth=linewidth, transform=ccrs.Geodetic()) for x in np.arange(np.ceil(start_lon),end_lon,2): ax.plot((x+linewidth/100.,x+1-linewidth/100.), np.array((start_lat, start_lat)), color='white', ls='-', linewidth=linewidth, transform=ccrs.Geodetic()) ax.plot((x+linewidth/100.,x+1-linewidth/100.), np.array((end_lat, end_lat)), color='white', ls='-', linewidth=linewidth, transform=ccrs.Geodetic()) ax.plot(np.array((start_lon, start_lon)), np.array((start_lat, end_lat)), color='black', ls='-', linewidth=linewidth, transform=ccrs.Geodetic()) ax.plot(np.array((end_lon, end_lon)), np.array((start_lat, end_lat)), color='black', ls='-', linewidth=linewidth, transform=ccrs.Geodetic()) for y in np.arange(np.ceil(start_lat),end_lat,2): ax.plot((start_lon, start_lon), np.array((y+0.06, y+1-0.04)), color='white', ls='-', linewidth=linewidth, transform=ccrs.Geodetic()) ax.plot((end_lon, end_lon), np.array((y+0.06, y+1-0.04)), color='white', ls='-', linewidth=linewidth, transform=ccrs.Geodetic()) ax.plot(station_location['Jergul'].lon, station_location['Jergul'].lat, fillstyle='left', marker='o', color='orange', markersize=12, alpha=0.7, transform=ccrs.Geodetic()) ax.plot(station_location['Karasjok'].lon, station_location['Karasjok'].lat, fillstyle='right', marker='o', color='orange', markersize=12, alpha=0.7, transform=ccrs.Geodetic()) ax.plot(station_location['Svanvik'].lon, station_location['Svanvik'].lat, marker='o', color='blueviolet', markersize=12, alpha=0.7, transform=ccrs.Geodetic()) ax.plot(station_location['Esrange'].lon, station_location['Esrange'].lat, marker='o', color='blue', markersize=12, alpha=0.7, transform=ccrs.Geodetic()) ax.plot(station_location['Pallas'].lon, station_location['Pallas'].lat, marker='o', color='black', markersize=12, alpha=0.7, transform=ccrs.Geodetic()) ax.plot(station_location['Janiskoski'].lon, station_location['Janiskoski'].lat, marker='o', color='grey', markersize=12, alpha=0.7, transform=ccrs.Geodetic()) geodetic_transform = ccrs.Geodetic()._as_mpl_transform(ax) text_transform = offset_copy(geodetic_transform, units='dots', x=-25) text_transform_2 = offset_copy(geodetic_transform, units='dots', y=40) # Add text. ax.text(station_location['Jergul'].lon, station_location['Jergul'].lat, u'Jergul', verticalalignment='center', horizontalalignment='right', size='xx-large', transform=text_transform, bbox=dict(facecolor='orange', alpha=0.5, boxstyle='round')) ax.text(station_location['Karasjok'].lon, station_location['Karasjok'].lat, u'Karasjok', verticalalignment='center', horizontalalignment='right', size='xx-large', transform=text_transform_2, bbox=dict(facecolor='orange', alpha=0.5, boxstyle='round')) ax.text(station_location['Svanvik'].lon, station_location['Svanvik'].lat, u'Svanvik', verticalalignment='center', horizontalalignment='right', size='xx-large', transform=text_transform, bbox=dict(facecolor='blueviolet', alpha=0.5, boxstyle='round')) ax.text(station_location['Esrange'].lon, station_location['Esrange'].lat, u'Esrange', verticalalignment='center', horizontalalignment='right', size='xx-large', color='white', transform=text_transform_2, bbox=dict(facecolor='blue', alpha=0.5, boxstyle='round')) ax.text(station_location['Pallas'].lon, station_location['Pallas'].lat, u'Pallas', verticalalignment='center', horizontalalignment='right', size='xx-large', color='white', transform=text_transform, bbox=dict(facecolor='black', alpha=0.5, boxstyle='round')) ax.text(station_location['Janiskoski'].lon, station_location['Janiskoski'].lat, u'Janiskoski', verticalalignment='center', horizontalalignment='right', size='xx-large', transform=text_transform, bbox=dict(facecolor='grey', alpha=0.5, boxstyle='round')) plot_frame(ax, 19.4,31.4,67.6,71.4)
def plotLogo(fig, ax, heights, charXDist=10): """ draw a sequence logo onto axis. heights is a list of dictionaries with letter -> float >>> freqs = [{"A":0.5, "C":0.3}, {"T":0.3, "G":0.7}] >>> fig.set_size_inches(3,0.5*len(freqs)) >>> plotLogo(fig, ax, freqs) """ #ax.set_xlim(0,len(heights)) ax.set_ylim(-1, 1) ax.axis('off') #t = plt.gca().transData t = ax.transData xPos = 0.0 charToCol = {"C": "b", "A": "r", "T": "k", "G": "y"} for yDict in heights: if len(yDict) == 0: yDict["A"] = 0.0 charFreqs = yDict.items() charFreqs.sort(key=operator.itemgetter(1)) #yZeroT = transforms.offset_copy(t, units="dots") lastFreq = None # need to draw something, otherwise we don't know the width to advance for char, freq in charFreqs: # jump back to y=0 when we switch from negative to positive freqs #print char, freq if lastFreq == None or (lastFreq < 0 and freq > 0): #t = transforms.offset_copy(text._transform, y=0, units='dots') #t = yZeroT t = transforms.offset_copy(ax.transData, x=xPos, units='dots') lastFreq = freq alpha = 1.0 if freq < 0: alpha = 0.5 col = charToCol.get(char.upper(), "k") text = ax.text(0, 0, char, transform=t, fontsize=50, color=col, family="monospace", alpha=alpha) text.set_path_effects([Scale(1, freq)]) fig.canvas.draw() ex = text.get_window_extent(fig.canvas.renderer) t = transforms.offset_copy(text._transform, y=ex.height * freq, units='dots') xPos += ex.width + charXDist
def rainbow_text(x, y, strings, colors, orientation='horizontal', ax=None, **kwargs): """ Take a list of *strings* and *colors* and place them next to each other, with text strings[i] being shown in colors[i]. Parameters ---------- x, y : float Text position in data coordinates. strings : list of str The strings to draw. colors : list of color The colors to use. orientation : {'horizontal', 'vertical'} ax : Axes, optional The Axes to draw into. If None, the current axes will be used. **kwargs All other keyword arguments are passed to plt.text(), so you can set the font size, family, etc. """ if ax is None: ax = plt.gca() t = ax.transData fig = ax.figure canvas = fig.canvas assert orientation in ['horizontal', 'vertical'] if orientation == 'vertical': kwargs.update(rotation=90, verticalalignment='bottom') for s, c in zip(strings, colors): text = ax.text(x, y, s + " ", color=c, transform=t, **kwargs) # Need to draw to update the text position. text.draw(canvas.get_renderer()) ex = text.get_window_extent() # Convert window extent from pixels to inches # to avoid issues displaying at different dpi ex = fig.dpi_scale_trans.inverted().transform_bbox(ex) if orientation == 'horizontal': t = text.get_transform() + \ offset_copy(Affine2D(), fig=fig, x=ex.width, y=0) else: t = text.get_transform() + \ offset_copy(Affine2D(), fig=fig, x=0, y=ex.height)
def draw_logo(all_scores): window = Tk() window.title("Cluster") window.geometry('1120x300') canvas2 = Canvas(window, width=1100, height=420) canvas2.pack(expand=1, side=LEFT) fig = plt.figure(figsize=(3, 4.5), dpi=100, facecolor='w', edgecolor='k') fig.set_size_inches(len(all_scores), 2.5) ax = fig.add_subplot(111) ax.set_xticks(range(len(all_scores))) plt.xticks(range(len(all_scores))) xshift = 0 trans_offset = transforms.offset_copy(ax.transAxes, fig=fig, x=0, y=0, units='points') for scores in all_scores: yshift = 0 for base, score in scores: txt = ax.text(0, 0, base, transform=trans_offset, fontsize=40, color=COLOR_SCHEME[base], weight='bold', ha='center', family='sans-serif') txt.set_clip_on(False) 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') xshift += window_ext.width trans_offset = transforms.offset_copy(ax.transAxes, fig=fig, x=xshift, units='points') ax.set_yticks(range(0, 3)) seaborn.despine(ax=ax, offset=30, trim=True) ax.set_xticklabels(range(1, len(all_scores) + 1), rotation=90) ax.set_yticklabels(np.arange(0, 3, 1)) fig_photo2 = draw_figure(canvas2, fig) window.mainloop()
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 draw_logo(all_scores, run, k, n): fig = plt.figure() fig.set_size_inches(k, 2) ax = fig.add_subplot(111) xshift = 0 trans_offset = transforms.offset_copy(ax.transAxes, fig=fig, x=0, y=0, units='points') for scores in all_scores: yshift = 0 for base, score in scores: txt = ax.text(0, 0, base, transform = trans_offset, fontsize = 80, color = COLOR_SCHEME[base], weight = 'bold', ha = 'center', family = 'sans-serif' ) txt.set_clip_on(False) 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') xshift += window_ext.width trans_offset = transforms.offset_copy(ax.transAxes, fig=fig, x=xshift, units='points') ax.set_yticks(range(0,3)) if type == "f": ax.set_ylabel("frequency") if type == "b": ax.set_ylabel("bits") plt.tick_params(bottom = False, labelbottom = False) seaborn.despine(ax=ax, offset=30, trim=False, bottom=True) ax.set_yticklabels(np.arange(0,3,1)) plt.savefig("figures/"+str(identifier)+"/logos/logo_"+str(identifier)+"_"+str(run+(startround-1))+"_"+str(k)+"_"+str(n), dpi=600, bbox_inches='tight') plt.close()
def Text(x, y, txt, x_offset=0, y_offset=0, units='points', va='bottom', ha='left', color='black', fontsize=10): """ Add text ======== """ trans = offset_copy(gca().transData, fig=gcf(), x=x_offset, y=y_offset, units=units) text(x, y, txt, transform=trans, va=va, ha=ha, color=color, fontsize=fontsize)
def multicolor_text(axes, x, y, textin, cmap=None,wratio=0.5, bbox={}, **kw): import matplotlib.pyplot as plt from matplotlib import transforms """ Take a list of strings ``ls`` and colors ``lc`` and place them next to each other, with text ls[i] being shown in color lc[i]. This example shows how to do both vertical and horizontal text, and will pass all keyword arguments to plt.text, so you can set the font size, family, etc. """ fig = plt.gcf() t = axes.transAxes # horizontal version if cmap is None: cmap = plt.cm.RdYlBu textin = list(textin) ntextin = len(textin) for idx, s in enumerate(textin): # s_ = ['_']*ntextin # s_[idx] = s c = cmap(float(idx) / (ntextin - 1)) # tx = axes.text(x, y, ''.join(s_), color=c, transform=t, **kw) tx = axes.text(x, y, s, color=c, transform=t, **kw) if bbox: tx.set_bbox(bbox) tx.draw(fig.canvas.get_renderer()) ex = tx.get_window_extent() t = transforms.offset_copy(tx._transform,fig=fig, x=ex.width*wratio, units='points')
def get_text_trans(cls, figure): "return transformation for text labels" from matplotlib.transforms import offset_copy return offset_copy(figure.gca().transData, figure.figure, cls.miscProp["textOffsetX"], cls.miscProp["textOffsetY"], units="points")
def relation(xs, ys, filename, xlabel=None, ylabel=None, pointlabels = [], xlim = None, xlog = False, vertical_line = None): xsl = list(xs) ysl = list(ys) plt.clf() fig = plt.figure() ax = plt.subplot(111) trans_offset = mtrans.offset_copy(ax.transData, fig=fig, x = 0.05, y = 0.1, units='inches') ax.scatter(xsl, ysl, c = plt.cm.Set1(np.linspace(0, 1, len(xsl))), alpha=0.5) if xlabel: ax.set_xlabel(xlabel) if ylabel: ax.set_ylabel(ylabel) if xlim is not None: ax.set_xlim(xlim) if xlog: ax.set_xscale('log') if pointlabels: for x, y, l in zip(xsl, ysl, pointlabels): ax.text(x, y, l, transform = trans_offset, fontsize=8) if vertical_line: ax.axvline(vertical_line, color='red') ax.grid(True) fig.savefig(filename, dpi=100) plt.close(fig)
def relations(xss, yss, filename, xlabel=None, ylabel=None, pointlabels = [], xlim = None, labels = []): xss = list(xss) yss = list(yss) plt.clf() fig = plt.figure() ax = plt.subplot(111) trans_offset = mtrans.offset_copy(ax.transData, fig=fig, x = 0.05, y = 0.1, units='inches') if len(labels) < len(xss): labels += [''] * (len(xss) - len(labels)) for xsl, ysl, c, label in zip(xss, yss, plt.cm.Dark2(np.linspace(0, 1, len(xss))), labels): ax.scatter(xsl, ysl, c = c, alpha=0.5, label=label) if pointlabels: for x, y, l in zip(xsl, ysl, pointlabels): ax.text(x, y, l, transform = trans_offset, fontsize=8) if xlabel: ax.set_xlabel(xlabel) if ylabel: ax.set_ylabel(ylabel) if xlim is not None: ax.set_xlim(xlim) plt.legend(loc='upper center', prop={'size': 10}, bbox_to_anchor=(0.5,1.1), ncol=int(math.ceil(len(xss)/2.0)), fancybox=True) ax.grid(True) fig.savefig(filename, dpi=100) plt.close(fig)
def main(): # Create a Stamen Terrain instance. terrain = cimgt.StamenTerrain() # Create a GeoAxes in the tile's projection. plt.figure(figsize=(10,10)) ax = plt.axes(projection=terrain.crs) # Limit the extent of the map to a small longitude/latitude range. ax.set_extent([-122.3, -122, 46.1, 46.3]) # Add the MapQuest data at zoom level 8. ax.add_image(terrain, 12) # Add a marker for the Mount Saint Helens volcano. plt.plot(-122.189611,46.205868, marker='o', color='yellow', markersize=12, alpha=0.7, transform=ccrs.Geodetic()) # Use the cartopy interface to create a matplotlib transform object # for the Geodetic coordinate system. We will use this along with # matplotlib's offset_copy function to define a coordinate system which # translates the text by 25 pixels to the left. geodetic_transform = ccrs.Geodetic()._as_mpl_transform(ax) text_transform = offset_copy(geodetic_transform, units='dots', x=-25) # Add text 25 pixels to the left of the volcano. plt.text(-122.189611,46.205868, u'Mount Saint Helens Volcano', verticalalignment='center', horizontalalignment='right', transform=text_transform, bbox=dict(facecolor='wheat', alpha=0.5, boxstyle='round')) gl=ax.gridlines(draw_labels=True) gl.xlabels_top = False gl.ylabels_right = False plt.show()
def annotate_point(x, y, text, offset=5, offset_x=None, offset_y=None, text_kw={}): """Annotates the point at a given x, y position (in data coordinates), at a given pixel offset. Args: x: x-coordinate of point y: y-coordinate of point text (str): String to annotate offset: (optional) pixel offset to use offset_x, offset_y: (optional) pixel offset to use in x, y directions text_kw (dict): (optional) any additional keywords to pass to plt.text """ if offset_x is None or offset_y is None: offset_x = offset offset_y = offset ax = plt.gca() trans_offset = transforms.offset_copy(ax.transData, units='dots', x=offset_x, y=offset_y) plt.text(x, y, text, transform=trans_offset, **text_kw)
def emissores_mapa(emi_dict, limites=[-110, 30, 75, 10]): # https://scitools.org.uk/cartopy/docs/latest/gallery/eyja_volcano.html fig = plt.figure(figsize=(12, 8)) ax = fig.add_subplot(1, 1, 1, projection=ccrs.PlateCarree()) ax.set_extent(limites, ccrs.PlateCarree()) lons = [x[1] for x in emi_dict.values()] lats = [x[0] for x in emi_dict.values()] ax.scatter(lons, lats, c='r', lw=3) ax.stock_img() ax.add_feature(cfeature.BORDERS) ax.coastlines() ax.gridlines() # Use the cartopy interface to create a matplotlib transform object # for the Geodetic coordinate system. We will use this along with # matplotlib's offset_copy function to define a coordinate system which # translates the text by 25 pixels to the left. geodetic_transform = ccrs.Geodetic()._as_mpl_transform(ax) text_transform = offset_copy(geodetic_transform, units='dots', x=-15) for name, coord in emi_dict.items(): # Add text 15 pixels to the left of point. ax.text(coord[1], coord[0], name, verticalalignment='center', horizontalalignment='right', transform=text_transform, bbox=dict(facecolor='sandybrown', alpha=0.7, boxstyle='round')) plt.show()
def colored_text_to_figure(in_text, scores=None, colors=None, figsize=(10, 0.5), colormap='jet', **kw): """ Input: in_text: (list) of strings scores: same size list/array of floats, if None: colors arguement must be not None. colors: if not None, it will be used instead of scores. """ fig = plt.figure(frameon=False, figsize=figsize) ax = fig.add_axes([0, 0, 1, 1]) ax.axis('off') t = plt.gca().transData if colors is None: colors = scalars_to_colors(scores, colormap) for token, col in zip(in_text, colors): text = plt.text(0, 0, ' ' + token + ' ', color=col, transform=t, **kw) text.draw(fig.canvas.get_renderer()) ex = text.get_window_extent() t = transforms.offset_copy(text._transform, x=ex.width, units='dots') return fig
def create_map(ds): fig = plt.figure() # Create a GeoAxes in the tile's projection. ax = fig.add_subplot(1, 1, 1, projection=ccrs.Mercator()) # Limit the extent of the map to a small longitude/latitude range. ax.set_extent([9.8, 11.5, 58.7, 60], crs=ccrs.Geodetic()) # Add the Stamen data at zoom level 8. # ax.add_image(stamen_terrain, 20) ax.stock_img() ax.coastlines(resolution='50m') # Add a marker for the Eyjafjallajökull volcano. ax.plot(ds.longitude, ds.latitude, marker='o', color='red', markersize=2, alpha=0.7, transform=ccrs.Geodetic()) # Use the cartopy interface to create a matplotlib transform object # for the Geodetic coordinate system. We will use this along with # matplotlib's offset_copy function to define a coordinate system which # translates the text by 25 pixels to the left. geodetic_transform = ccrs.Geodetic()._as_mpl_transform(ax) text_transform = offset_copy(geodetic_transform, units='dots', x=-25) # Add text 25 pixels to the left of the volcano. # ax.text(-19.613333, 63.62, u'Eyjafjallajökull', # verticalalignment='center', horizontalalignment='right', # transform=text_transform, # bbox=dict(facecolor='sandybrown', alpha=0.5, boxstyle='round')) plt.show()
def _offset(ax, x, y): """Provide offset in pixels Parameters ---------- x : int Offset in pixels for x y : int Offset in pixels for y Idea borrowed from http://www.scipy.org/Cookbook/Matplotlib/Transformations but then heavily extended to be compatible with many reincarnations of matplotlib """ d = dir(mlt) if "offset_copy" in d: # tested with python-matplotlib 0.98.3-5 # ??? if pukes, might need to replace 2nd parameter from # ax to ax.get_figure() return mlt.offset_copy(ax.transData, ax, x=x, y=y, units="dots") elif "BlendedAffine2D" in d: # some newer versions of matplotlib return ax.transData + mlt.Affine2D().translate(x, y) elif "blend_xy_sep_transform" in d: trans = mlt.blend_xy_sep_transform(ax.transData, ax.transData) # Now we set the offset in pixels trans.set_offset((x, y), mlt.identity_transform()) return trans else: raise RuntimeError, "Lacking needed functions in matplotlib.transform " "for _offset. Please upgrade"
def circles(plot, p, colors='g', size=15, xoff=0, yoff=0): """ Draw circles on plot Args: plot (Tree): A Tree plot instance p: A node object or list of Node objects colors: Str or list of strs. Colors of the circles. Optional, defaults to 'g' (green) size (float): Size of the circles. Optional, defaults to 15 xoff, yoff (float): X and Y offset. Optional, defaults to 0. """ points = _xy(plot, p) trans = offset_copy( plot.transData, fig=plot.figure, x=xoff, y=yoff, units='points' ) col = CircleCollection( sizes=(pi*size*size*0.25,), offsets=points, facecolors=colors, transOffset=trans, edgecolors='none' ) plot.add_collection(col) plot.figure.canvas.draw_idle() return col
def main(): # Create a Stamen Terrain instance. stamen_terrain = cimgt.StamenTerrain() # Create a GeoAxes in the tile's projection. ax = plt.axes(projection=stamen_terrain.crs) # Limit the extent of the map to a small longitude/latitude range. ax.set_extent([-22, -15, 63, 65]) # Add the Stamen data at zoom level 8. ax.add_image(stamen_terrain, 8) # Add a marker for the Eyjafjallajökull volcano. plt.plot(-19.613333, 63.62, marker='o', color='red', markersize=12, alpha=0.7, transform=ccrs.Geodetic()) # Use the cartopy interface to create a matplotlib transform object # for the Geodetic coordinate system. We will use this along with # matplotlib's offset_copy function to define a coordinate system which # translates the text by 25 pixels to the left. geodetic_transform = ccrs.Geodetic()._as_mpl_transform(ax) text_transform = offset_copy(geodetic_transform, units='dots', x=-25) # Add text 25 pixels to the left of the volcano. plt.text(-19.613333, 63.62, u'Eyjafjallajökull', verticalalignment='center', horizontalalignment='right', transform=text_transform, bbox=dict(facecolor='sandybrown', alpha=0.5, boxstyle='round')) plt.show()
def _offset(ax, x, y): """Provide offset in pixels Parameters ---------- x : int Offset in pixels for x y : int Offset in pixels for y Idea borrowed from http://www.scipy.org/Cookbook/Matplotlib/Transformations but then heavily extended to be compatible with many reincarnations of matplotlib """ d = dir(mlt) if 'offset_copy' in d: # tested with python-matplotlib 0.98.3-5 # ??? if pukes, might need to replace 2nd parameter from # ax to ax.get_figure() return mlt.offset_copy(ax.transData, ax, x=x, y=y, units='dots') elif 'BlendedAffine2D' in d: # some newer versions of matplotlib return ax.transData + \ mlt.Affine2D().translate(x,y) elif 'blend_xy_sep_transform' in d: trans = mlt.blend_xy_sep_transform(ax.transData, ax.transData) # Now we set the offset in pixels trans.set_offset((x, y), mlt.identity_transform()) return trans else: raise RuntimeError, \ "Lacking needed functions in matplotlib.transform " \ "for _offset. Please upgrade"
def Text(x, y, txt, x_offset=0, y_offset=0, units="points", va="bottom", ha="left", color="black", fontsize=10): """ Add text ======== """ trans = offset_copy(gca().transData, fig=gcf(), x=x_offset, y=y_offset, units=units) text(x, y, txt, transform=trans, va=va, ha=ha, color=color, fontsize=fontsize)
def offset_text(text, x, y, x_offset, y_offset, transform='axis', fig=None, units='points', **kwargs): ax = kwargs.pop('ax', plt.gca()) if fig is None: fig = ax.figure if transform == 'axis': transform = ax.transAxes elif transform == 'data': transform = ax.transData offset_transform = trans.offset_copy(transform, fig, x_offset, y_offset, units=units) ax.text(x, y, text, transform=offset_transform, **kwargs)
def update_fig(self): from matplotlib import pyplot as plt from matplotlib import transforms xlim, ylim = zip((0, 0), self.dimensions) if not hasattr(self, 'fig'): plt.axis('off') self.fig = plt.figure() self.plt = self.fig.add_subplot(111, axisbg='k', aspect='equal') offset = transforms.offset_copy(self.plt.transData, x=5, y=5, units='dots') # bucket patches buckets = {'b': [], 'r': []} for cell in self.space.cells(): if cell.agents: buckets[cell.agents.copy().pop().color[0]].append(cell.point) self.plt.clear() for b, points in buckets.items(): self.plt.plot(*zip(*points), marker='o', markerfacecolor=b, linestyle='None', markersize=8, transform=offset) # need to do this on OSX self.plt.set_xlim(*xlim) self.plt.set_ylim(*ylim)
def plot( self, ax: Axes, text_kw=None, shift=None, **kwargs ) -> List[Artist]: # coverage: ignore if shift is None: # flake B006 shift = dict(units="dots", x=15) if text_kw is None: text_kw = {} else: # since we may modify it, let's make a copy text_kw = {**text_kw} if "projection" in ax.__dict__ and "transform" not in kwargs: from cartopy.crs import PlateCarree from matplotlib.transforms import offset_copy kwargs["transform"] = PlateCarree() geodetic_transform = PlateCarree()._as_mpl_transform(ax) text_kw["transform"] = offset_copy(geodetic_transform, **shift) if "color" not in kwargs: kwargs["color"] = "black" if "s" not in text_kw: if hasattr(self, "callsign"): text_kw["s"] = getattr(self, "callsign") # noqa: B009 if hasattr(self, "name"): text_kw["s"] = getattr(self, "name") # noqa: B009 cumul: List[Artist] = [] cumul.append(ax.scatter(self.longitude, self.latitude, **kwargs)) cumul.append(ax.text(self.longitude, self.latitude, **text_kw)) return cumul
def plot_caption(tokens, colors, ax): # Split long caption into multiple lines def split_long_text(tokens, max_length=42): output, chunk, count = [], [], 0 for token, color in zip(tokens, colors): count += len(token) if count > max_length: output.append(chunk) chunk, count = [], 0 chunk.append((token, color)) output.append(chunk) return output lines = split_long_text(tokens) for idx, line in enumerate(lines): transform, canvas = ax.transData, ax.figure.canvas for i, (tok, color) in enumerate(line): tok = tok.capitalize( ) if idx == i == 0 else ' ' + tok if tok not in ['.', ','] else tok offset = (idx + 1) * (0.76 - 0.18 * len(lines)) text = ax.text(0.05, offset, tok, color=color, transform=transform, size=9) text.draw(canvas.get_renderer()) ex = text.get_window_extent() transform = transforms.offset_copy(text._transform, x=ex.width, units='dots')
def add_circles(treeplot, nodes, colors="g", size=15, xoff=0, yoff=0, vis=True): """ Draw circles on plot Args: nodes: A node object or list of Node objects or label or list of labels colors: Str or list of strs. Colors of the circles. Optional, defaults to 'g' (green) size (float): Size of the circles. Optional, defaults to 15 xoff, yoff (float): X and Y offset. Optional, defaults to 0. """ points = xy(treeplot, nodes) trans = offset_copy( treeplot.transData, fig=treeplot.figure, x=xoff, y=yoff, units='points' ) col = CircleCollection( sizes=(pi*size*size*0.25,), offsets=points, facecolors=colors, transOffset=trans, edgecolors='none', zorder=1 ) col.set_visible(vis) treeplot.add_collection(col) treeplot.figure.canvas.draw_idle()
def _segment_angle_to_text_specs(self, angle, lonlat): """Get appropriate kwargs for a given text angle""" kw, loc = self._text_angle_to_specs_(angle, lonlat) if not self.rotate_labels: angle = { 'top': 90., 'right': 0., 'bottom': -90., 'left': 180. }[loc] del kw['rotation'] if ((self.x_inline and lonlat == 'lon') or (self.y_inline and lonlat == 'lat')): kw.update(transform=cartopy.crs.PlateCarree()) else: xpadding = (self.xpadding if self.xpadding is not None else matplotlib.rc_params['xtick.major.pad']) ypadding = (self.ypadding if self.ypadding is not None else matplotlib.rc_params['ytick.major.pad']) dx = ypadding * np.cos(angle * np.pi / 180) dy = xpadding * np.sin(angle * np.pi / 180) transform = mtrans.offset_copy(self.axes.transData, self.axes.figure, x=dx, y=dy, units='dots') kw.update(transform=transform) return kw, loc
def squares(plot, p, colors='r', size=15, xoff=0, yoff=0, alpha=1.0, zorder=1000): """ Draw a square at given node Args: plot (Tree): A Tree plot instance p: A node or list of nodes colors: Str or list of strs. Colors of squares to be drawn. Optional, defaults to 'r' (red) size (float): Size of the squares. Optional, defaults to 15 xoff, yoff (float): Offset for x and y dimensions. Optional, defaults to 0. alpha (float): between 0 and 1. Alpha transparency of squares. Optional, defaults to 1 (fully opaque) zorder (int): The drawing order. Higher numbers appear on top of lower numbers. Optional, defaults to 1000. """ points = _xy(plot, p) trans = offset_copy( plot.transData, fig=plot.figure, x=xoff, y=yoff, units='points') col = RegularPolyCollection( numsides=4, rotation=pi*0.25, sizes=(size*size,), offsets=points, facecolors=colors, transOffset=trans, edgecolors='none', alpha=alpha, zorder=zorder ) plot.add_collection(col) plot.figure.canvas.draw_idle()
def plot_array(array, visibilities=None): fig = plt.figure(figsize=(8,8)) ax = fig.add_subplot(111) transOffset = offset_copy(ax.transData, fig=ax.figure, x = 0.0, y=-0.10, units='inches') center = array.arrxyz # Calculate a "east" unit vector east = np.array([center[1]*center[2],-center[0]*center[2],0]) if center[2] > 0: east *= -1 east /= np.sqrt(np.sum(np.square(east))) # Calculate a "north" unit vector north = np.cross(center, east) north /= np.sqrt(np.sum(np.square(north))) stations = array.station xlist = [] ylist = [] for station in stations: if 'U' in station.sta_name: color='green' else: color='blue' x = np.inner(station.staxyz, east) y = np.inner(station.staxyz, north) xlist.append(x) ylist.append(y) ax.plot([x], [y], 'o', color=color, markersize=1+station.diameter) plt.text(x, y, station.sta_name, transform=transOffset, horizontalalignment='center', verticalalignment='top', family='serif') if visibilities: for vis in visibilities: x = np.array([np.inner(vis.station[0].staxyz, east), np.inner(vis.station[1].staxyz, east)]) y = np.array([np.inner(vis.station[0].staxyz, north), np.inner(vis.station[1].staxyz, north)]) ax.plot(x, y, linestyle='-', marker='|', markersize=20, label=vis.station[0].sta_name + vis.station[1].sta_name) ax.plot([0], [0], 'r+') plt.text(0, 0, '$\\vec{O}$', transform=transOffset, horizontalalignment='center', verticalalignment='top') ax.annotate('N', xy=(0.05, 0.25), xytext=(0.05, 0.05), xycoords='axes fraction', textcoords='axes fraction', arrowprops={'width':2}, horizontalalignment='center', verticalalignment='bottom', family='serif', size='20') minx = np.min(xlist) miny = np.min(ylist) maxx = np.max(xlist) maxy = np.max(ylist) centerx = (maxx - minx) / 2.0 + minx centery = (maxy - miny) / 2.0 + miny width = 1.1*np.max([maxx - minx, maxy - miny]) ax.set_xlim(centerx - width / 2.0, centerx + width / 2.0) ax.set_ylim(centery - width / 2.0, centery + width / 2.0) ax.relim() ax.set_xlabel('Relative position (m)') ax.set_ylabel('Relative position (m)')
def circles(plot, points, colors, size=15, xoff=0, yoff=0): trans = offset_copy(plot.transData, fig=plot.figure, x=xoff, y=yoff, units="points") col = CircleCollection( sizes=(pi * size * size * 0.25,), offsets=points, facecolors=colors, transOffset=trans, edgecolors="none" ) return plot.add_collection(col)
def get_label_tran(self): "return transformation for text labels" from matplotlib.transforms import offset_copy offset = self.get_config_section("pointLabelOffset") return offset_copy(self.gca().transData, self.figure, offset["x"], offset["y"], units="points")
def add_axlabel(x, y, text, ax=None, dx=0, dy=0, ha='center', va='center', **kwargs): """A label to an axis with appropriate default font properies""" if ax is None: ax = P.gca() dict_check_defaults(kwargs, color = cfgget('title_color'), family = cfgget('title_font'), size = cfgget('label_size'), ) trans = offset_copy(ax.transAxes, x=dx, y=dy, fig=ax.get_figure(), units='points') ax.text(x, y, text, transform=trans, ha=ha, va=va, **kwargs)
def plotLogo(fig, ax, heights, charXDist=10): """ draw a sequence logo onto axis. heights is a list of dictionaries with letter -> float >>> freqs = [{"A":0.5, "C":0.3}, {"T":0.3, "G":0.7}] >>> fig.set_size_inches(3,0.5*len(freqs)) >>> plotLogo(fig, ax, freqs) """ #ax.set_xlim(0,len(heights)) ax.set_ylim(-1,1) ax.axis('off') #t = plt.gca().transData t = ax.transData xPos = 0.0 charToCol = {"C":"b", "A":"r", "T":"k", "G":"y"} for yDict in heights: if len(yDict)==0: yDict["A"]=0.0 charFreqs = yDict.items() charFreqs.sort(key=operator.itemgetter(1)) #yZeroT = transforms.offset_copy(t, units="dots") lastFreq = None # need to draw something, otherwise we don't know the width to advance for char, freq in charFreqs: # jump back to y=0 when we switch from negative to positive freqs #print char, freq if lastFreq == None or (lastFreq < 0 and freq > 0): #t = transforms.offset_copy(text._transform, y=0, units='dots') #t = yZeroT t = transforms.offset_copy(ax.transData, x=xPos, units='dots') lastFreq = freq alpha = 1.0 if freq < 0: alpha = 0.5 col = charToCol.get(char.upper(), "k") text = ax.text(0, 0, char, transform=t, fontsize=50, color=col, family="monospace", alpha=alpha) text.set_path_effects([Scale(1,freq)]) fig.canvas.draw() ex = text.get_window_extent(fig.canvas.renderer) t = transforms.offset_copy(text._transform, y=ex.height*freq, units='dots') xPos += ex.width+charXDist
def rainbow_text(x, y, strings, colors, orientation='horizontal', ax=None, **kwargs): """ Take a list of *strings* and *colors* and place them next to each other, with text strings[i] being shown in colors[i]. Parameters ---------- x, y : float Text position in data coordinates. strings : list of str The strings to draw. colors : list of color The colors to use. orientation : {'horizontal', 'vertical'} ax : Axes, optional The Axes to draw into. If None, the current axes will be used. **kwargs All other keyword arguments are passed to plt.text(), so you can set the font size, family, etc. """ if ax is None: ax = plt.gca() t = ax.transData canvas = ax.figure.canvas assert orientation in ['horizontal', 'vertical'] if orientation == 'vertical': kwargs.update(rotation=90, verticalalignment='bottom') for s, c in zip(strings, colors): text = ax.text(x, y, s + " ", color=c, transform=t, **kwargs) # Need to draw to update the text position. text.draw(canvas.get_renderer()) ex = text.get_window_extent() if orientation == 'horizontal': t = transforms.offset_copy( text.get_transform(), x=ex.width, units='dots') else: t = transforms.offset_copy( text.get_transform(), y=ex.height, units='dots')
def offset_xlabel(label, axes, offset): """ Draws an xlabel that is at the given offset from the bottom of the axis, regardless of the status of the tick labels. (Normal xlabels adjust upwards if tick labels are removed) """ text = matplotlib.text.Text(.5, 0, label, horizontalalignment='center') text.set_transform(transforms.offset_copy( axes.transAxes, axes.figure, x=0, y=offset, units='points' )) text.set_clip_on(False) axes.add_artist(text)
def add_bar_labels(fig, ax, bars, bottom=0): transOffset = offset_copy(ax.transData, fig=fig, x=0., y= -2., units='points') transOffsetUp = offset_copy(ax.transData, fig=fig, x=0., y=1., units='points') for bar in bars: for i, [patch, num] in enumerate(zip(bar.patches, np.arange(len(bar.patches)))): if len(bottom) == len(bar): b = bottom[i] else: b = bottom height = patch.get_height() + b xi = patch.get_x() + patch.get_width() / 2. va = 'top' c = 'w' t = TextPath((0, 0), "${xi}$".format(xi=xi), rotation=0, ha='center') transform = transOffset if patch.get_extents().height <= t.get_extents().height + 5: va = 'bottom' c = 'k' transform = transOffsetUp ax.text(xi, height, "${xi}$".format(xi=int(num)), color=c, rotation=0, ha='center', va=va, transform=transform) ax.set_xticks([])
def plot_events(events, color='k', ax=None): if ax is None: import matplotlib.pyplot as plt ax = plt.gca() trans = ax.get_xaxis_transform() trans_text = offset_copy(trans, fig=ax.figure, \ x=3, units='points') for ev in events: t0, t1, ta = ev['t0'], ev['t1'], (ev['t0'] + ev['t1']) / 2. ax.vlines(t1, 0, 0.1, color=desaturate(color, 0.6), transform=trans) ax.vlines(t0, 0, 0.1, color=color, transform=trans) ax.text(ta, 0, ev['name'], ha='center', transform=trans_text)
def offset(self, x, y): ''' Returns an offset transform which can be based to text and line constructors to shift the label ``(x, y)`` with respect to the correspoding bar. Arguments: x horizontal offset y vertical offset ''' return offset_copy(self.ax.transData, x=x, y=y, units='dots')
def dots(): import pylab as P from matplotlib.transforms import offset_copy X = P.arange(7) Y = X**2 fig = P.figure(figsize=(5,10)) ax = P.subplot(2,1,1) # If we want the same offset for each text instance, # we only need to make one transform. To get the # transform argument to offset_copy, we need to make the axes # first; the subplot command above is one way to do this. transOffset = offset_copy(ax.transData, fig=fig, x = 0.05, y=0.10, units='inches') for x, y in zip(X, Y): P.plot((x,),(y,), 'ro') P.text(x, y, '%d, %d' % (int(x),int(y)), transform=transOffset) # offset_copy works for polar plots also. ax = P.subplot(2,1,2, polar=True) transOffset = offset_copy(ax.transData, fig=fig, y = 6, units='dots') for x, y in zip(X, Y): P.polar((x,),(y,), 'ro') P.text(x, y, '%d, %d' % (int(x),int(y)), transform=transOffset, horizontalalignment='center', verticalalignment='bottom') P.show()
def squares(plot, points, colors, size=15, xoff=0, yoff=0): trans = offset_copy(plot.transData, fig=plot.figure, x=xoff, y=yoff, units="points") col = RegularPolyCollection( numsides=4, rotation=pi * 0.25, sizes=(size * size,), offsets=points, facecolors=colors, transOffset=trans, edgecolors="none", ) return plot.add_collection(col)
def main(): # This is just useful for formatting returned dict # pp = pprint.PrettyPrinter(indent=2) # Create instance of Meso object, pass in YOUR token m = Meso(api_token='3428e1e281164762870915d2ae6781b4') # Use to lookup stations, could specify counties or whatever here # findstationids = m.station_list(state='CO') # print(findstationids) # Grab most recent temp (F) ob in last 90 min at each of the below stations stations = ['kgxy, kccu, kcos, kden, kgjt, kbdu, kpub, klhx, kspd, kdro, ksbs, keeo, kguc, klic, ' 'kstk, kals, ktad'] latest = m.latest_obs(stid=stations, within='90', vars='air_temp', units='temp|F') # create a list to store everything, iterate over the number of objs returned in latest and append # lat, long, temp, and stid for use later data = [] [data.append((float(ob['LATITUDE']), float(ob['LONGITUDE']), float(ob['OBSERVATIONS']['air_temp_value_1']['value']), ob['STID'])) for ob in latest['STATION']] print(data) # Create a MapQuest open aerial instance. map_quest_aerial = cimgt.MapQuestOpenAerial() # Create a GeoAxes in the tile's projection. ax = plt.axes(projection=map_quest_aerial.crs) # Limit the extent of the map to Colorado's borders ax.set_extent([-102.03, -109.03, 37, 41]) # Add the MapQuest data at zoom level 8. ax.add_image(map_quest_aerial, 8) # Plot lat/long pts with below params for lat, lon, temp, stid in data: plt.plot(lon, lat, marker='o', color='y', markersize=1, alpha=0.7, transform=ccrs.Geodetic()) # Transforms for the text func we're about to call geodetic_transform = ccrs.Geodetic()._as_mpl_transform(ax) text_transform = offset_copy(geodetic_transform, units='dots', x=0, y=0) # Plot temp and station id for each of the markers for lat, lon, temp, stid in data: plt.text(lon, lat, stid + '\n' + str(round(temp, 1)) + u' \N{DEGREE SIGN}' + 'F', verticalalignment='center', horizontalalignment='center', transform=text_transform, fontsize=9, bbox=dict(facecolor='wheat', alpha=0.5, boxstyle='round')) plt.title('Current Weather Around Colorado') plt.show()
def indexed_plots(var1,var2,Nvar1,Nvar2,labels,title=None,figname=None): fig = plt.figure() ax = plt.subplot(111) e = np.random.uniform(low=-0.05,high=0.05,size=len(var1)) transOffset = offset_copy(ax.transData, fig=fig,x = 0.05+3*e, y=0.10-3*e, units='inches') for x, y,l in zip(var1,var2,labels): ax.plot((x,),(y,), 'ro') indx = labels.index(l) #ax.text(x, y, '%s' % (l), transform= transOffset, fontsize=8) ax.text(x, y, '%s' % (l), fontsize=8, transform=offset_copy(ax.transData, fig=fig,x = 0.05+e[indx], y=0.10-e[indx], units='inches')) ax.set_xlabel(Nvar1,fontsize=8) ax.set_ylabel(Nvar2,fontsize=8) if title != None: fig.suptitle(title) if figname == None: plt.savefig('CURVE.jpg') else: plt.savefig(figname+".jpg")
def _drawPicks(self, draw=True): ''' Draw picklines onto axes ''' picks = self._getPicks() xpicks = self._getPickXPosition(picks) for _ax in self.fig.get_axes(): lines = [] labels = [] points = [] transOffset = offset_copy(_ax.transData, fig=self.fig, x=5, y=0, units='points') for _i, _xpick in enumerate(xpicks): if picks[_i].phase_hint == 'S': color = 'r' elif picks[_i].phase_hint == 'P': color = 'g' else: color = 'b' if _ax.channel != picks[_i].waveform_id.channel_code: alpha = .2 else: alpha = .8 lines.append(matplotlib.lines.Line2D([_xpick, _xpick], [_ax.get_ylim()[0]*.9, _ax.get_ylim()[1]*.8], color=color, alpha=alpha, rasterized=True)) lines[-1].obspy_pick = picks[_i] points.append(matplotlib.lines.Line2D([_xpick], [_ax.lines[0].get_ydata()[int(_xpick)]], marker='o', mfc=color, mec=color, alpha=alpha, ms=5)) labels.append(matplotlib.text.Text(_xpick, _ax.get_ylim()[0]*.8, text=picks[_i].phase_hint, color=color, size=10, alpha=alpha, transform=transOffset)) # delete all artists del _ax.artists[0:] # add updated objects for li, la, po in zip(lines, labels, points): _ax.add_artist(li) _ax.add_artist(la) _ax.add_artist(po) if draw: self._canvasDraw()
def rainbow_text(ax, x, y, ls, lc, **kw): """ Take a list of strings ``ls`` and colors ``lc`` and place them next to each other, with text ls[i] being shown in color lc[i]. This example shows how to do both vertical and horizontal text, and will pass all keyword arguments to plt.text, so you can set the font size, family, etc. """ # TODO trans = ax.transAxes # horizontal version for i, (s, c) in enumerate(zip(ls, lc)): text = ax.text(x, y, "{}{}".format(" " * bool(i), s), color=c, transform=trans, **kw) text.draw(ax.figure.canvas.get_renderer()) ex = text.get_window_extent() trans = offset_copy(text._transform, x=ex.width, units="dots")