def show(location_summaries, ap_names, ap_macs): datafile = cbook.get_sample_data('C:/Dev/android/WifiRecord/app/src/main/res/drawable/greenstone_lower.png') lower_img = imread(datafile) lower_img_flip = lower_img[::-1, :, :] lower_img_faded = (255*0.7 + lower_img_flip*0.3).astype('uint8') datafile = cbook.get_sample_data('C:/Dev/android/WifiRecord/app/src/main/res/drawable/greenstone_upper.png') upper_img = imread(datafile) upper_img_flip = upper_img[::-1, :, :] upper_img_faded = (255*0.7 + upper_img_flip*0.3).astype('uint8') fig, (ax_upper, ax_lower) = plt.subplots(2, 1) #mng = plt.get_current_fig_manager() #mng.full_screen_toggle() for (num, name) in ap_names.iteritems(): # if num>=1: # break ax_upper.cla() ax_upper.imshow(upper_img_faded, zorder=0, extent=[0, 2200, 0, 1054]) ax_upper.set_xlim(400, 1800) ax_upper.set_ylim(800, 400) ax_lower.cla() ax_lower.imshow(lower_img_faded, zorder=0, extent=[0, 2200, 0, 760]) ax_lower.axis([300, 1000, 100, 500]) ax_lower.set_ylim(500, 100) add_points(ax_upper, ax_lower, num, name, location_summaries) plt.draw() time.sleep(0.25)
def showImage(ax, filename, title='', label='', label_color='black', fontsize=DEFAULT_FONTSIZE, rotate=False, label_position=(0.05,0.95), dpi=None, ): from matplotlib import pyplot as plt import matplotlib.cbook as cbook setLabel(ax, label, color=label_color, fontsize=fontsize, position=label_position, dpi=dpi, ) image_file = cbook.get_sample_data(abspath(filename)) image = plt.imread(image_file) if rotate: image = np.transpose(image, (1,0,2)) im = ax.imshow(image) ax.axis('off') ax.set_title(title, fontsize=fontsize) return im
def get_two_stock_data(): """ load stock time and price data for two stocks The return values (d1,p1,d2,p2) are the trade time (in days) and prices for stocks 1 and 2 (intc and aapl) """ ticker1, ticker2 = 'INTC', 'AAPL' file1 = cbook.get_sample_data('INTC.dat', asfileobj=False) file2 = cbook.get_sample_data('AAPL.dat', asfileobj=False) M1 = fromstring( file(file1, 'rb').read(), '<d') M1 = resize(M1, (M1.shape[0]/2,2) ) M2 = fromstring( file(file2, 'rb').read(), '<d') M2 = resize(M2, (M2.shape[0]/2,2) ) d1, p1 = M1[:,0], M1[:,1] d2, p2 = M2[:,0], M2[:,1] return (d1,p1,d2,p2)
def paste_image(filename): # annotate plot and paste image fig, ax = plt.subplots() xy = (0.5, 0.7) ax.plot(xy[0], xy[1], ".r") fn = get_sample_data(filename, asfileobj=False) arr_lena = read_png(fn) imagebox = OffsetImage(arr_lena, zoom=0.2) ab = AnnotationBbox(imagebox, xy, xybox=(120., -80.), xycoords='data', boxcoords="offset points", pad=0.5, arrowprops=dict(arrowstyle="->", connectionstyle="angle,angleA=0,angleB=90,rad=3") ) ax.add_artist(ab) ax.set_xlim(0, 1) ax.set_ylim(0, 1) plt.draw() plt.show()
def draw_map_image(x,y): f2,ax=plt.subplots() image_file = cbook.get_sample_data('/mnt/hgfs/I/ComputerVision/ISCAS/housemap001.jpg') img = plt.imread(image_file) #img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) #img=img[:,:,0] ax.set_xticks([]) ax.set_yticks([]) plt.title('emotion map') # Show the image plt.imshow(img) # matplotColors=['blue','green','red','cyan','magenta','yellow','black','white'] colors = ['red', 'blue', 'yellow', 'green', 'cyan', 'black', 'magenta'] assert len(colors) == emotions_num # Now, loop through coord arrays, and create a circle at each x,y pair for xx,yy in zip(x,y): emotion = np.random.choice(np.arange(emotions_num), p=[0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.4]) p = Circle((xx, yy), 5, color=colors[emotion]) ax.add_patch(p) # draw legend patches=[] for color,label in zip(colors,y_ticks): patch=Circle(color=color,label=label,xy=(5,5)) patches.append(patch) plt.legend(handles=patches) #f2.draw #f2.canvas.draw() return f2
def get_demo_image(): import numpy as np from matplotlib.cbook import get_sample_data f = get_sample_data("axes_grid/bivariate_normal.npy", asfileobj=False) z = np.load(f) # z is a numpy array of 15x15 return z, (-3, 4, -4, 3)
def test_equalize(data): '''Test''' dfile = cbook.get_sample_data('s1045.ima', asfileobj=False) im = np.fromstring(file(dfile, 'rb').read(), np.uint16).astype(float) im.shape = 256, 256 #imshow(im, ColormapJet(256)) #imshow(im, cmap=cm.jet) imvals = np.sort(im.flatten()) lo = imvals[0] hi = imvals[-1] steps = (imvals[::len(imvals)/256] - lo) / (hi - lo) num_steps = float(len(steps)) interps = [(s, idx/num_steps, idx/num_steps) for idx, s in enumerate(steps)] interps.append((1, 1, 1)) cdict = {'red' : interps, 'green' : interps, 'blue' : interps} histeq_cmap = colors.LinearSegmentedColormap('HistEq', cdict) pylab.figure() pylab.imshow(im, cmap=histeq_cmap) pylab.title('histeq') pylab.show()
def use_image(self, axis, image_path): image_path = toolbox_basic.check_path(image_path) datafile = cbook.get_sample_data(image_path) image = Image.open(datafile) axis.set_ylim(0,image.size[0]) axis.set_ylim(image.size[1],0) return imshow(image)
def __plot__(self,fname): image_file = cbook.get_sample_data(fname) image = plt.imread(image_file) fig, ax1 = plt.subplots(1, 1) fig.set_size_inches(52,78) ax1.imshow(image) horiz_segments,vert_segments,horiz_intercepts,vert_intercepts = self.__get_grid_segments__() h_lines = self.__segments_to_grids__(horiz_segments,horiz_intercepts,horiz=True) v_lines = self.__segments_to_grids__(vert_segments,vert_intercepts,horiz=False) for (lb,ub) in h_lines: X,Y = zip(*lb) ax1.plot(X, Y,color="blue") X,Y = zip(*ub) ax1.plot(X, Y,color="blue") for (lb,ub) in v_lines: X,Y = zip(*lb) ax1.plot(X, Y,color="blue") X,Y = zip(*ub) ax1.plot(X, Y,color="blue") plt.savefig("/home/ggdhines/Databases/temp.jpg",bbox_inches='tight', pad_inches=0,dpi=72)
def __display_image__(self,subject_id,args_l,kwargs_l,block=True,title=None): """ return the file names for all the images associated with a given subject_id also download them if necessary :param subject_id: :return: """ subject = self.subject_collection.find_one({"zooniverse_id": subject_id}) url = subject["location"]["standard"] slash_index = url.rfind("/") object_id = url[slash_index+1:] if not(os.path.isfile(self.base_directory+"/Databases/"+self.project+"/images/"+object_id)): urllib.urlretrieve(url, self.base_directory+"/Databases/"+self.project+"/images/"+object_id) fname = self.base_directory+"/Databases/"+self.project+"/images/"+object_id image_file = cbook.get_sample_data(fname) image = plt.imread(image_file) fig, ax = plt.subplots() im = ax.imshow(image,cmap = cm.Greys_r) for args,kwargs in zip(args_l,kwargs_l): print args,kwargs ax.plot(*args,**kwargs) if title is not None: ax.set_title(title) plt.show(block=block)
def Scatter(): """ Demo of scatter plot with varying marker colors and sizes. """ import numpy as np import matplotlib.pyplot as plt import matplotlib.cbook as cbook # Load a numpy record array from yahoo csv data with fields date, # open, close, volume, adj_close from the mpl-data/example directory. # The record array stores python datetime.date as an object array in # the date column datafile = cbook.get_sample_data('goog.npy') price_data = np.load(datafile).view(np.recarray) price_data = price_data[-250:] # get the most recent 250 trading days delta1 = np.diff(price_data.adj_close)/price_data.adj_close[:-1] # Marker size in units of points^2 volume = (15 * price_data.volume[:-2] / price_data.volume[0])**2 close = 0.003 * price_data.close[:-2] / 0.003 * price_data.open[:-2] fig, ax = plt.subplots() ax.scatter(delta1[:-1], delta1[1:], c=close, s=volume, alpha=0.5) ax.set_xlabel(r'$\Delta_i$', fontsize=20) ax.set_ylabel(r'$\Delta_{i+1}$', fontsize=20) ax.set_title('Volume and percent change') ax.grid(True) fig.tight_layout() plt.show()
def mapPerPeriod(aodperDegree, lats, longs, title, savefile, cmapname,minv=0,maxv=0): # Make plot with vertical (default) colorbar fig, ax = plt.subplots() data = aodperDegree datafile = cbook.get_sample_data('C:/Users/alex/marspython/aerosol/gr.png') img = imread(datafile) ax.imshow(img, zorder=1, alpha=0.3, extent=[float(min(longs))-0.5, float(max(longs))+0.5, float(min(lats)) - 0.5, float(max(lats))+0.5]) if minv<>0 or maxv<>0 : cax = ax.imshow(data, zorder=0, interpolation='spline16', cmap=cm.get_cmap(cmapname), extent=[float(min(longs)), float(max(longs)), float(min(lats)), float(max(lats))], vmin=minv,vmax=maxv) else: cax = ax.imshow(data, zorder=0, interpolation='spline16', cmap=cm.get_cmap(cmapname), extent=[float(min(longs)), float(max(longs)), float(min(lats)), float(max(lats))]) ax.set_title(title) # Add colorbar, make sure to specify tick locations to match desired ticklabels #cbar = fig.colorbar(cax, ticks=[-1, 0, 1]) cbar = fig.colorbar(cax) #cbar.ax.set_yticklabels(['< -1', '0', '> 1']) # vertically oriented colorbar pylab.savefig(savefile + ".png")
def __init__(self, ax, n): self.ax = ax dir=os.path.abspath(os.path.dirname(sys.argv[0])) ax.axis([0,1,0,1]) ax.axes.get_xaxis().set_visible(False) ax.axes.get_yaxis().set_visible(False) ax.set_frame_on=True ax.plot( [ 0.1, 0.2], [0.96, 0.96], color='blue', linewidth=2 ) ax.plot( [ 0.1, 0.2], [0.91, 0.91], color='green', linewidth=2 ) ax.plot( [ 0.1, 0.2], [0.86, 0.86], color='red', linewidth=1 ) self.text1 = ax.text( 0.3, self.ypos(2), '%d' % n ) fn = get_sample_data("%s/coolr-logo-poweredby-48.png" % dir, asfileobj=False) arr = read_png(fn) imagebox = OffsetImage(arr, zoom=0.4) ab = AnnotationBbox(imagebox, (0, 0), xybox=(.75, .12), xycoords='data', boxcoords="axes fraction", pad=0.5) ax.add_artist(ab)
def show(all_points_list): datafile = cbook.get_sample_data('C:/Dev/android/WifiRecord/app/src/main/res/drawable/greenstone_lower.png') lower_img = imread(datafile) lower_img_flip = lower_img[::-1, :, :] lower_img_faded = (255*0.7 + lower_img_flip*0.3).astype('uint8') datafile = cbook.get_sample_data('C:/Dev/android/WifiRecord/app/src/main/res/drawable/greenstone_upper.png') upper_img = imread(datafile) upper_img_flip = upper_img[::-1, :, :] upper_img_faded = (255*0.7 + upper_img_flip*0.3).astype('uint8') fig, (ax_upper, ax_lower) = plt.subplots(2, 1) #fig = fig = plt.gcf() #(ax_upper, ax_lower) = fig.axes #mng = plt.get_current_fig_manager() #mng.full_screen_toggle() for (i, points) in enumerate(zip(*all_points_list)): ax_upper.cla() ax_upper.imshow(upper_img_faded, zorder=0, extent=[0, 2200, 0, 1054]) ax_upper.set_xlim(400, 1800) ax_upper.set_ylim(800, 300) #ax_upper.set_xlim(1000, 1850) #ax_upper.set_ylim(750, 450) ax_lower.cla() ax_lower.imshow(lower_img_faded, zorder=0, extent=[0, 2200, 0, 760]) ax_lower.axis([300, 1000, 100, 500]) ax_lower.set_ylim(500, 100) colors = ("Black", "Red", "Blue", "Yellow") for (j, point) in enumerate(points): x = point["x"] y = point["y"] display = str(i) + "," + "{:.1f}".format(point["score"]) if point["level"]==0: ax_lower.plot([x], [y], 'o', color = colors[j]) ax_lower.text(x+1, y, display, fontsize=8) else: ax_upper.plot([x], [y], 'o', color = colors[j]) ax_upper.text(x+1, y, display, fontsize=8) plt.draw() time.sleep(0.1) plt.show()
def main(): landmarks = ['American Museum of Natural History', 'Brooklyn Bridge', 'Central Park', 'Guggenheim Museum', 'High Line', 'Rockefeller Center', 'September 11 Memorial', 'Statue of Liberty', 'Times Square', 'Mystery'] dist = distanceMatrix() adist = np.array(dist) amax = np.amax(dist) adist /= amax mds = manifold.MDS(n_components=2, dissimilarity="precomputed", random_state=6) results = mds.fit(dist) coords = results.embedding_ print coords print coords[:,1][0] for x in range (len(coords[:,1])): coords[:,1][x] = coords[:,1][x]*-1 #Can comment this out to run without background NYC MAP datafile = cbook.get_sample_data('/Users/niqson/5map.png') img = imread(datafile) plt.scatter( coords[:, 0], coords[:, 1], marker = 'o',s=25,color='cyan' ) plt.annotate('Museum of Nat. History', coords[0]) plt.annotate('Brooklyn Bridge', coords[1]) plt.annotate('Central Park', coords[2],xytext = (-20, 20),textcoords = 'offset points', ha = 'right', va = 'bottom', bbox = dict(boxstyle = 'round,pad=0.2', fc = 'yellow', alpha = 0.5), arrowprops = dict(arrowstyle = '->', connectionstyle = 'arc3,rad=0')) plt.annotate('Guggenheim Museum', coords[3],xytext = (20, 10),textcoords = 'offset points', ha = 'right', va = 'bottom', bbox = dict(boxstyle = 'round,pad=0.2', fc = 'yellow', alpha = 0.5), arrowprops = dict(arrowstyle = '->', connectionstyle = 'arc3,rad=0')) plt.annotate('High Line', coords[4],xytext = (-20, 20),textcoords = 'offset points', ha = 'right', va = 'bottom', bbox = dict(boxstyle = 'round,pad=0.2', fc = 'yellow', alpha = 0.5), arrowprops = dict(arrowstyle = '->', connectionstyle = 'arc3,rad=0')) plt.annotate('Rockefeller Center', coords[5]) plt.annotate('9/11 Memorial', coords[6]) plt.annotate('Statue of Liberty', coords[7]) plt.annotate('Times Square', coords[8],xytext = (-20, 20),textcoords = 'offset points', ha = 'right', va = 'bottom', bbox = dict(boxstyle = 'round,pad=0.2', fc = 'yellow', alpha = 0.5), arrowprops = dict(arrowstyle = '->', connectionstyle = 'arc3,rad=0')) plt.annotate('Mystery', coords[9],size = 20) rotated_img = scipy.ndimage.rotate(img, -10) plt.imshow(rotated_img, zorder=0, extent=[-32000, 30000, -30000, 19000]) plt.show() '''
def test_colorbar_example1(): with cbook.get_sample_data('grace_hopper.png') as fp: data = np.array(plt.imread(fp)) fig = plt.figure() ax = fig.add_subplot("111", aspect='equal') mappable = ax.imshow(data[..., 0], cmap='viridis') colorbar = Colorbar(mappable, location='lower left') colorbar.set_ticks([0.0, 0.5, 1.0]) ax.add_artist(colorbar)
def logo_box(self): logo_offset_image = OffsetImage(read_png(get_sample_data(logo_location, asfileobj=False)), zoom=0.25, resample=1, dpi_cor=1) text_box = TextArea(logo_text, textprops=dict(color='#444444', fontsize=50, weight='bold')) logo_and_text_box = HPacker(children=[logo_offset_image, text_box], align="center", pad=0, sep=25) anchored_box = AnchoredOffsetbox(loc=2, child=logo_and_text_box, pad=0.8, frameon=False, borderpad=0.) return anchored_box
def Date(): #!/usr/bin/env python """ Show how to make date plots in matplotlib using date tick locators and formatters. See major_minor_demo1.py for more information on controlling major and minor ticks All matplotlib date plotting is done by converting date instances into days since the 0001-01-01 UTC. The conversion, tick locating and formatting is done behind the scenes so this is most transparent to you. The dates module provides several converter functions date2num and num2date """ import datetime import numpy as np import matplotlib.pyplot as plt import matplotlib.dates as mdates import matplotlib.cbook as cbook years = mdates.YearLocator() # every year months = mdates.MonthLocator() # every month yearsFmt = mdates.DateFormatter('%Y') # load a numpy record array from yahoo csv data with fields date, # open, close, volume, adj_close from the mpl-data/example directory. # The record array stores python datetime.date as an object array in # the date column datafile = cbook.get_sample_data('goog.npy') r = np.load(datafile).view(np.recarray) fig, ax = plt.subplots() ax.plot(r.date, r.adj_close) # format the ticks ax.xaxis.set_major_locator(years) ax.xaxis.set_major_formatter(yearsFmt) ax.xaxis.set_minor_locator(months) datemin = datetime.date(r.date.min().year, 1, 1) datemax = datetime.date(r.date.max().year+1, 1, 1) ax.set_xlim(datemin, datemax) # format the coords message box def price(x): return '$%1.2f'%x ax.format_xdata = mdates.DateFormatter('%Y-%m-%d') ax.format_ydata = price ax.grid(True) # rotates and right aligns the x labels, and moves the bottom of the # axes up to make room for them fig.autofmt_xdate() plt.show()
def maritime_hall_figure(fig_num, dem_file, reference_trajectory, slam_trajectory, mis_orient = quat.quaternion(np.array([1.0,0.0,0.0,0.0])), mis_position = [0.00, 0.00, 0.00]): import os from matplotlib.cbook import get_sample_data from matplotlib._png import read_png import matplotlib.image as image matplotlib.rcParams.update({'font.size': 15, 'font.weight': 'bold'}) #fig = plt.figure(fig_num, figsize=(28, 16), dpi=120, facecolor='w', edgecolor='k') #ax = fig.add_subplot(111) fn = get_sample_data(os.getcwd()+"/data/img/maritime_hall.png", asfileobj=False) maritime_hall = image.imread(fn) fig, ax = plt.subplots() ax.imshow(maritime_hall, extent=[-1.2, 25, -2, 20]) #ax.imshow(maritime_hall, extent=[-1.2, 25, -2, 19]) # Display Ground Truth trajectory from numpy import linalg as la ref = np.column_stack((reference_trajectory[:,0][0::1], reference_trajectory[:,1][0::1], reference_trajectory[:,2][0::1])) ref[:] = [(mis_orient * i * mis_orient.conj())[1:4] for i in ref ] ref[:] = [ i + mis_position for i in ref ] x = ref[:,0] y = ref[:,1] ax.plot(x, y, marker='D', linestyle='-', lw=2, alpha=0.3, color=[1.0, 1.0, 0.0], label='ground truth', zorder=80) # Annotations from matplotlib.offsetbox import OffsetImage, AnnotationBbox ax.annotate(r'Start', xy=(x[0], y[0]), xycoords='data', xytext=(-5, 5), textcoords='offset points', fontsize=16, horizontalalignment='left', verticalalignment='bottom', zorder=101 ) ax.scatter(x[0], y[0], marker='o', facecolor='k', s=40, alpha=1.0, zorder=103) ax.annotate(r'End', xy=(x[x.shape[0]-1], y[y.shape[0]-1]), xycoords='data', xytext=(-5, 5), textcoords='offset points', fontsize=16, horizontalalignment='left', verticalalignment='bottom', zorder=101 ) ax.scatter(x[x.shape[0]-1], y[y.shape[0]-1], marker='o', facecolor='k', s=40, alpha=1.0, zorder=103) plt.xlabel(r'X [$m$]', fontsize=15, fontweight='bold') plt.ylabel(r'Y [$m$]', fontsize=15, fontweight='bold') ax.legend(loc=1, prop={'size':15}) plt.grid(True) fig.savefig("gt_maritime_hall_20180720-1644.png", dpi=fig.dpi) plt.show(block=True)
def display_wordcloud(words, counts): with tempfile.NamedTemporaryFile(suffix='.png') as tmp: temp_filename = tmp.name counts = wordcloud.make_wordcloud(words, counts, temp_filename, font_path='/Library/Fonts/Georgia.ttf',width=800, height=800, ranks_only=False) image_file = cbook.get_sample_data(temp_filename) image = plt.imread(image_file) fig, ax = plt.subplots() im = ax.imshow(image) plt.axis('off') plt.show()
def openImage(self) : texto = 'Escolha uma imagem' path = QtGui.QFileDialog.getOpenFileNameAndFilter(self, texto, self.thisDir, "Images (*.png *.jpg)") datafile = cbook.get_sample_data(str(path[0])) img = imread(datafile) self.updateCanvas(self.initializeCanvas(img)) return
def test_equalize(data): """Returns a color map which performs histogram equalization on the data. Parameters ---------- data : ndarray Returns ------- value : matplotlib colormap See Also -------- Examples -------- >>> import sunpy.cm as cm >>> cm.test_equalize() Reference --------- | http://matplotlib.sourceforge.net/api/cm_api.html .. warning:: this function is under development .. todo:: finish coding this function! """ dfile = cbook.get_sample_data('s1045.ima', asfileobj=False) im = np.fromstring(file(dfile, 'rb').read(), np.uint16).astype(float) im.shape = 256, 256 #imshow(im, ColormapJet(256)) #imshow(im, cmap=cm.jet) imvals = np.sort(im.flatten()) lo = imvals[0] hi = imvals[-1] steps = (imvals[::len(imvals)/256] - lo) / (hi - lo) num_steps = float(len(steps)) interps = [(s, idx/num_steps, idx/num_steps) for idx, s in enumerate(steps)] interps.append((1, 1, 1)) cdict = {'red': interps, 'green': interps, 'blue': interps} histeq_cmap = colors.LinearSegmentedColormap('HistEq', cdict) pylab.figure() pylab.imshow(im, cmap=histeq_cmap) pylab.title('histeq') pylab.show()
def test_img(index=0): import matplotlib.cbook as cbook from PIL import Image sample_fnames = ['grace_hopper.jpg', 'lena.png', 'ada.png'] if index <= len(sample_fnames): test_file = cbook.get_sample_data(sample_fnames[index]) else: import load_data2 chip_dir = load_data2.DEFAULT+load_data2.RDIR_CHIP test_file = chip_dir + '/CID_%d.png' % (1 + index - len(sample_fnames)) test_img = np.asarray(Image.open(test_file).convert('L')) return test_img
def get_ticker(ticker): vals = [] datafile = cbook.get_sample_data('%s.csv'%ticker, asfileobj=False) lines = file(datafile).readlines() for line in lines[1:]: vals.append([float(val) for val in line.split(',')[1:]]) M = array(vals) c = C() c.open = M[:,0] c.high = M[:,1] c.low = M[:,2] c.close = M[:,3] c.volume = M[:,4] return c
def background_image(self, file): """Set the file image as background image""" if self.bg_img: self.bg_img.remove() datafile = get_sample_data(file) img = plt.imread(datafile) im = OffsetImage(img) im.set_zoom(min(1. * self.canvas.window.get_size()[0] / len(im.properties()['data'][0]), 1. * self.canvas.window.get_size()[1] / len(im.properties()['data']))) self.bg_img = AnnotationBbox(im, (0.5, 0.5), xycoords='data', frameon=False) self.bg_img.set_zorder(-1) plt.gca().add_artist(self.bg_img) self.do_refresh()
def put_team_logo_annotationbbox(filename,xy,xybox=(40., +80.)): fn = get_sample_data(filename, asfileobj=False) arr_lena = read_png(fn) imagebox = OffsetImage(arr_lena, zoom=0.02 ) # xy = [4, 75] ab = AnnotationBbox(imagebox, xy, xybox=xybox, xycoords='data', boxcoords="offset points", pad=0.0,frameon=False, arrowprops=dict(arrowstyle="->",alpha=.75,linestyle='dashed', connectionstyle="angle,angleA=50,angleB=90,rad=3") ) ax.add_artist(ab)
def main(): # Test data x, y = np.mgrid[-5:5:0.05, -5:5:0.05] z = 5 * (np.sqrt(x**2 + y**2) + np.sin(x**2 + y**2)) filename = get_sample_data('jacksboro_fault_dem.npz', asfileobj=False) with np.load(filename) as dem: elev = dem['elevation'] fig = compare(z, plt.cm.copper) fig.suptitle('HSV Blending Looks Best with Smooth Surfaces', y=0.95) fig = compare(elev, plt.cm.gist_earth, ve=0.05) fig.suptitle('Overlay Blending Looks Best with Rough Surfaces', y=0.95) plt.show()
def openImage(self) : texto = 'Escolha uma imagem' path = QtGui.QFileDialog.getOpenFileNameAndFilter(self, texto, self.thisDir, "Images (*.png *.jpg)") datafile = cbook.get_sample_data(str(path[0])) img = imread(datafile) self.updateCanvas(self.initializeCanvas(img)) self.message.setText('Esperando a calibracao dos eixos') self.status.setText('Em espera') return
def plotTeamShots(self, teamcode): self.xshotsteam = [] self.yshotsteam = [] self.shotresteam = [] halfs = 0 for play in self.gamearr: if (play[self.etype] == 'shot' and float(play[self.y]) <= 47.0 and play[self.team] == teamcode): self.xshotsteam.append(float(play[self.x])) self.yshotsteam.append(float(play[self.y])) self.shotresteam.append(play[self.result]) elif (play[self.etype] == 'shot' and float(play[self.y]) >= 47.0 and play[self.team] == teamcode): halfs += 1 print 'Shots from ' + teamcode + ' beyond halfcourt: ' + str(halfs) mades = [] misseds = [] for i in range(len(self.shotresteam)): if(self.shotresteam[i] == 'made'): mades.append(i) else: misseds.append(i) xmades = [self.xshotsteam[i] for i in mades] ymades = [self.yshotsteam[i] for i in mades] xmisseds = [self.xshotsteam[j] for j in misseds] ymisseds = [self.yshotsteam[j] for j in misseds] courtfn = '/Users/Martin/anaconda/NBA/halfcourts/' + (self.hteam).lower() + '_halfcourt.jpg' datafile = cbook.get_sample_data(courtfn) img = misc.imread(datafile) miss = plt.scatter(xmisseds, ymisseds, marker='x', c='r', s=40, zorder=2) make = plt.scatter(xmades, ymades, marker='o', c='g', s=100, zorder=1) plt.imshow(img, zorder=0, extent=[0.0, 50.0, 0.0, 47.0]) plt.legend((make, miss), ('Make', 'Miss'), scatterpoints=1, loc='upper right', ncol=1, fontsize=10) plt.xticks([]) plt.yticks([]) plt.show() plt.title(teamcode + ' - ' + self.ateam + '@' + self.hteam + ' on ' + self.date) print len(xmades)+len(xmisseds)
def OnInit(self): xrcfile = cbook.get_sample_data('embedding_in_wx3.xrc', asfileobj=False) print 'loading', xrcfile self.res = xrc.XmlResource(xrcfile) # main frame and panel --------- self.frame = self.res.LoadFrame(None,"MainFrame") self.panel = xrc.XRCCTRL(self.frame,"MainPanel") # matplotlib panel ------------- # container for matplotlib panel (I like to make a container # panel for our panel so I know where it'll go when in XRCed.) plot_container = xrc.XRCCTRL(self.frame,"plot_container_panel") sizer = wx.BoxSizer(wx.VERTICAL) # matplotlib panel itself self.plotpanel = PlotPanel(plot_container) self.plotpanel.init_plot_data() # wx boilerplate sizer.Add(self.plotpanel, 1, wx.EXPAND) plot_container.SetSizer(sizer) # whiz button ------------------ whiz_button = xrc.XRCCTRL(self.frame,"whiz_button") wx.EVT_BUTTON(whiz_button, whiz_button.GetId(), self.plotpanel.OnWhiz) # bang button ------------------ bang_button = xrc.XRCCTRL(self.frame,"bang_button") wx.EVT_BUTTON(bang_button, bang_button.GetId(), self.OnBang) # final setup ------------------ sizer = self.panel.GetSizer() self.frame.Show(1) self.SetTopWindow(self.frame) return True
The `~matplotlib.axes.Axes.fill_between` function generates a shaded region between a min and max boundary that is useful for illustrating ranges. It has a very handy ``where`` argument to combine filling with logical ranges, e.g., to just fill in a curve over some threshold value. At its most basic level, ``fill_between`` can be used to enhance a graph's visual appearance. Let's compare two graphs of financial data with a simple line plot on the left and a filled line on the right. """ import matplotlib.pyplot as plt import numpy as np import matplotlib.cbook as cbook # load up some sample financial data r = (cbook.get_sample_data('goog.npz', np_load=True)['price_data'].view(np.recarray)) # create two subplots with the shared x and y axes fig, (ax1, ax2) = plt.subplots(1, 2, sharex=True, sharey=True) pricemin = r.close.min() ax1.plot(r.date, r.close, lw=2) ax2.fill_between(r.date, pricemin, r.close, alpha=0.7) for ax in ax1, ax2: ax.grid(True) ax1.set_ylabel('price') for label in ax2.get_yticklabels(): label.set_visible(False)
#!/usr/bin/env python from __future__ import print_function from pylab import * import matplotlib.cbook as cbook w, h = 512, 512 datafile = cbook.get_sample_data('ct.raw.gz', asfileobj=True) s = datafile.read() A = fromstring(s, uint16).astype(float) A *= 1.0 / max(A) A.shape = w, h extent = (0, 25, 0, 25) im = imshow(A, cmap=cm.hot, origin='upper', extent=extent) markers = [(15.9, 14.5), (16.8, 15)] x, y = zip(*markers) plot(x, y, 'o') #axis([0,25,0,25]) #axis('off') title('CT density') if 0: x = asum(A, 0) subplot(212) bar(arange(w), x) xlim(0, h - 1) ylabel('density')
pcm = ax[2].pcolormesh(X, Y, Z, cmap='RdBu_r', vmin=-np.max(Z), shading='auto') fig.colorbar(pcm, ax=ax[2], extend='both', orientation='vertical') plt.show() ############################################################################### # TwoSlopeNorm: Different mapping on either side of a center # ---------------------------------------------------------- # # Sometimes we want to have a different colormap on either side of a # conceptual center point, and we want those two colormaps to have # different linear scales. An example is a topographic map where the land # and ocean have a center at zero, but land typically has a greater # elevation range than the water has depth range, and they are often # represented by a different colormap. filename = cbook.get_sample_data('topobathy.npz', asfileobj=False) with np.load(filename) as dem: topo = dem['topo'] longitude = dem['longitude'] latitude = dem['latitude'] fig, ax = plt.subplots() # make a colormap that has land and ocean clearly delineated and of the # same length (256 + 256) colors_undersea = plt.cm.terrain(np.linspace(0, 0.17, 256)) colors_land = plt.cm.terrain(np.linspace(0.25, 1, 256)) all_colors = np.vstack((colors_undersea, colors_land)) terrain_map = colors.LinearSegmentedColormap.from_list('terrain_map', all_colors) # make the norm: Note the center is offset so that the land has more
import sys import matplotlib.pyplot as plt import numpy as np import matplotlib.cbook as cbook fname = cbook.get_sample_data(sys.argv[1], asfileobj=False) # test 2; use names plt.plotfile(fname, (0, 1)) plt.xlabel('Time') plt.ylabel('Current (mA)') plt.grid(True) plt.show()
"""Timeline graph comparison with aligned colored annotation. This example shows lines tracking change over time. It features dashed lines at fixed increments on the Y axis. It adds a text label at the right end of every line in the corresponding color. """ import matplotlib.pyplot as plt from matplotlib.mlab import csv2rec from matplotlib.cbook import get_sample_data fname = get_sample_data('percent_bachelors_degrees_women_usa.csv') gender_degree_data = csv2rec(fname) # These are the colors that will be used in the plot color_sequence = ['#1f77b4', '#aec7e8', '#ff7f0e', '#ffbb78', '#2ca02c', '#98df8a', '#d62728', '#ff9896', '#9467bd', '#c5b0d5', '#8c564b', '#c49c94', '#e377c2', '#f7b6d2', '#7f7f7f', '#c7c7c7', '#bcbd22', '#dbdb8d', '#17becf', '#9edae5'] # You typically want your plot to be ~1.33x wider than tall. This plot # is a rare exception because of the number of lines being plotted on it. # Common sizes: (10, 7.5) and (12, 9) fig, ax = plt.subplots(1, 1, figsize=(12, 14)) # Remove the plot frame lines. They are unnecessary here. ax.spines['top'].set_visible(False) ax.spines['bottom'].set_visible(False) ax.spines['right'].set_visible(False) ax.spines['left'].set_visible(False)
def plot_isosurface( filename=None, vlsvobj=None, filedir=None, step=None, outputdir=None, nooverwrite=None, # surf_var=None, surf_op=None, surf_level=None, color_var=None, color_op=None, surf_step=1, # title=None, cbtitle=None, draw=None, usesci=None, # boxm=[], boxre=[], colormap=None, run=None, wmark=None, nocb=None, unit=None, thick=1.0, scale=1.0, vmin=None, vmax=None, lin=None, symlog=None, ): ''' Plots a coloured plot with axes and a colour bar. :kword filename: path to .vlsv file to use for input. Assumes a bulk file. :kword vlsvobj: Optionally provide a python vlsvfile object instead :kword filedir: Optionally provide directory where files are located and use step for bulk file name :kword step: output step index, used for constructing output (and possibly input) filename :kword outputdir: path to directory where output files are created (default: $HOME/Plots/) If directory does not exist, it will be created. If the string does not end in a forward slash, the final parti will be used as a perfix for the files. :kword nooverwrite: Set to only perform actions if the target output file does not yet exist :kword surf_var: Variable to read for defining surface :kword surf_op: Operator to use for variable to read surface :kword surf_level: Level at which to define surface :kword surf_step: Vertex stepping for surface generation: larger value returns coarser surface :kword color_var: Variable to read for coloring surface :kword color_op: Operator to use for variable to color surface ('x', 'y', 'z'; if None and color_var is a vector, the magnitude is taken) :kword boxm: zoom box extents [x0,x1,y0,y1] in metres (default and truncate to: whole simulation box) :kword boxre: zoom box extents [x0,x1,y0,y1] in Earth radii (default and truncate to: whole simulation box) :kword colormap: colour scale for plot, use e.g. hot_desaturated, jet, viridis, plasma, inferno, magma, parula, nipy_spectral, RdBu, bwr :kword run: run identifier, used for constructing output filename :kword title: string to use as plot title instead of time :kword cbtitle: string to use as colorbar title instead of map name :kword unit: Plot axes using 10^{unit} m (default: Earth radius R_E) :kwird usesci: Use scientific notation for colorbar ticks? (default: 1) :kword vmin,vmax: min and max values for colour scale and colour bar. If no values are given, min and max values for whole plot (non-zero rho regions only) are used. :kword lin: Flag for using linear colour scaling instead of log :kword symlog: Use logarithmic scaling, but linear when abs(value) is below the value given to symlog. Allows symmetric quasi-logarithmic plots of e.g. transverse field components. A given of 0 translates to a threshold of max(abs(vmin),abs(vmax)) * 1.e-2. :kword wmark: If set to non-zero, will plot a Vlasiator watermark in the top left corner. :kword draw: Set to nonzero in order to draw image on-screen instead of saving to file (requires x-windowing) :kword scale: Scale text size (default=1.0) :kword thick: line and axis thickness, default=1.0 :kword nocb: Set to suppress drawing of colourbar :returns: Outputs an image to a file or to the screen. .. code-block:: python # Example usage: ''' # Verify the location of this watermark image watermarkimage = os.path.join(os.path.dirname(__file__), 'logo_color.png') # watermarkimage=os.path.expandvars('$HOME/appl_taito/analysator/pyPlot/logo_color.png') outputprefix = '' if outputdir == None: outputdir = os.path.expandvars('$HOME/Plots/') outputprefixind = outputdir.rfind('/') if outputprefixind >= 0: outputprefix = outputdir[outputprefixind + 1:] outputdir = outputdir[:outputprefixind + 1] if not os.path.exists(outputdir): os.makedirs(outputdir) # Input file or object if filename != None: f = pt.vlsvfile.VlsvReader(filename) elif vlsvobj != None: f = vlsvobj elif ((filedir != None) and (step != None)): filename = filedir + 'bulk.' + str(step).rjust(7, '0') + '.vlsv' f = pt.vlsvfile.VlsvReader(filename) else: print( "Error, needs a .vlsv file name, python object, or directory and step" ) return # Scientific notation for colorbar ticks? if usesci == None: usesci = 1 if colormap == None: # Default values colormap = "hot_desaturated" if color_op != None: colormap = "bwr" cmapuse = matplotlib.cm.get_cmap(name=colormap) fontsize = 8 * scale # Most text fontsize2 = 10 * scale # Time title fontsize3 = 5 * scale # Colour bar ticks # Plot title with time timeval = None timeval = f.read_parameter("time") if timeval == None: timeval = f.read_parameter("t") if timeval == None: print("Unknown time format encountered") # Plot title with time if title == None: if timeval == None: print("Unknown time format encountered") plot_title = '' else: #plot_title = "t="+str(np.int(timeval))+' s' plot_title = "t=" + '{:4.2f}'.format(timeval) + ' s' else: plot_title = title # step, used for file name if step != None: stepstr = '_' + str(step).rjust(7, '0') else: stepstr = '' # If run name isn't given, just put "plot" in the output file name if run == None: run = 'plot' # Verify validity of operator surf_opstr = '' color_opstr = '' if color_op != None: if color_op != 'x' and color_op != 'y' and color_op != 'z': print("Unknown operator " + color_op + ", defaulting to None/magnitude for a vector.") color_op = None else: # For components, always use linear scale, unless symlog is set color_opstr = '_' + color_op if symlog == None: lin = 1 # Verify validity of operator if surf_op != None: if surf_op != 'x' and surf_op != 'y' and surf_op != 'z': print("Unknown operator " + surf_op) surf_op = None else: surf_opstr = '_' + surf_op # Output file name surf_varstr = surf_var.replace("/", "_") if color_var != None: color_varstr = color_var.replace("/", "_") else: color_varstr = "solid" savefigname = outputdir + outputprefix + run + "_isosurface_" + surf_varstr + surf_opstr + "-" + color_varstr + color_opstr + stepstr + ".png" # Check if target file already exists and overwriting is disabled if (nooverwrite != None and os.path.exists(savefigname)): # Also check that file is not empty if os.stat(savefigname).st_size > 0: return else: print("Found existing file " + savefigname + " of size zero. Re-rendering.") Re = 6.371e+6 # Earth radius in m #read in mesh size and cells in ordinary space [xsize, ysize, zsize] = f.get_spatial_mesh_size() [xmin, ymin, zmin, xmax, ymax, zmax] = f.get_spatial_mesh_extent() cellsize = (xmax - xmin) / xsize cellids = f.read_variable("CellID") # xsize = f.read_parameter("xcells_ini") # ysize = f.read_parameter("ycells_ini") # zsize = f.read_parameter("zcells_ini") # xmin = f.read_parameter("xmin") # xmax = f.read_parameter("xmax") # ymin = f.read_parameter("ymin") # ymax = f.read_parameter("ymax") # zmin = f.read_parameter("zmin") # zmax = f.read_parameter("zmax") if (xsize == 1) or (ysize == 1) or (zsize == 1): print("Error: isosurface plotting requires 3D spatial domain!") return simext = [xmin, xmax, ymin, ymax, zmin, zmax] sizes = [xsize, ysize, zsize] # Select window to draw if len(boxm) == 6: boxcoords = boxm elif len(boxre) == 6: boxcoords = [i * Re for i in boxre] else: boxcoords = simext # If box extents were provided manually, truncate to simulation extents boxcoords[0] = max(boxcoords[0], simext[0]) boxcoords[1] = min(boxcoords[1], simext[1]) boxcoords[2] = max(boxcoords[2], simext[2]) boxcoords[3] = min(boxcoords[3], simext[3]) boxcoords[4] = max(boxcoords[4], simext[4]) boxcoords[5] = min(boxcoords[5], simext[5]) # Axes and units (default R_E) if unit != None: # Use m or km or other if unit == 0: unitstr = r'm' if unit == 3: unitstr = r'km' else: unitstr = r'$10^{' + str(int(unit)) + '}$ m' unit = np.power(10, int(unit)) else: unitstr = r'$\mathrm{R}_{\mathrm{E}}$' unit = Re # Scale data extent and plot box simext_org = simext simext = [i / unit for i in simext] boxcoords = [i / unit for i in boxcoords] if color_op == None and color_var != None: color_op = 'pass' cb_title = color_var color_data = f.read_variable(color_var, cellids=[1, 2]) # If value was vector value, take magnitude if np.size(color_data) != 2: cb_title = r"$|" + color_var + "|$" elif color_op != None and color_var != None: cb_title = r" $" + color_var + "_" + color_op + "$" else: # color_var==None cb_title = "" nocb = 1 if f.check_variable(surf_var) != True: print("Error, surface variable " + surf_var + " not found!") return if surf_op == None: surf_data = f.read_variable(surf_var) # If value was vector value, take magnitude if np.ndim(surf_data) != 1: surf_data = np.linalg.norm(np.asarray(surf_data), axis=-1) else: surf_data = f.read_variable(surf_var, operator=surf_op) if np.ndim(surf_data) != 1: print("Error reading surface variable " + surf_var + "! Exiting.") return -1 # Reshape data to ordered 3D arrays for plotting #color_data = color_data[cellids.argsort()].reshape([sizes[2],sizes[1],sizes[0]]) surf_data = surf_data[cellids.argsort()].reshape( [sizes[2], sizes[1], sizes[0]]) # The data we have now is Z,Y,X # Rotate data so it's X,Y,Z surf_data = np.swapaxes(surf_data, 0, 2) if surf_level == None: surf_level = 0.5 * (np.amin(surf_data) + np.amax(surf_data)) print("Minimum found surface value " + str(np.amin(surf_data)) + " surface level " + str(surf_level) + " max " + str(np.amax(surf_data))) # Select ploitting back-end based on on-screen plotting or direct to file without requiring x-windowing if draw != None: plt.switch_backend('TkAgg') else: plt.switch_backend('Agg') # skimage.measure.marching_cubes_lewiner(volume, level=None, spacing=(1.0, 1.0, 1.0), # gradient_direction='descent', step_size=1, # allow_degenerate=True, use_classic=False) # #Generate mask for only visible section of data # # Apparently the marching cubes method does not ignore masked values, so this doesn't directly help. # [Xmesh,Ymesh, Zmesh] = scipy.meshgrid(np.linspace(simext[0],simext[1],num=sizes[0]),np.linspace(simext[2],simext[3],num=sizes[1]),np.linspace(simext[4],simext[5],num=sizes[2])) # print("simext",simext) # print("sizes",sizes) # print("boxcoords", boxcoords) # maskgrid = np.ma.masked_where(Xmesh<(boxcoords[0]), Xmesh) # maskgrid = np.ma.masked_where(Xmesh>(boxcoords[1]), maskgrid) # maskgrid = np.ma.masked_where(Ymesh<(boxcoords[2]), maskgrid) # maskgrid = np.ma.masked_where(Ymesh>(boxcoords[3]), maskgrid) # maskgrid = np.ma.masked_where(Zmesh<(boxcoords[4]), maskgrid) # maskgrid = np.ma.masked_where(Zmesh>(boxcoords[5]), maskgrid) # surf_data = np.ma.asarray(surf_data) # surf_data.mask = maskgrid.mask # print(surf_data.count()) surf_spacing = ((xmax - xmin) / (xsize * unit), (ymax - ymin) / (ysize * unit), (zmax - zmin) / (zsize * unit)) verts, faces, normals, arrays = measure.marching_cubes_lewiner( surf_data, level=surf_level, spacing=surf_spacing, gradient_direction='descent', step_size=surf_step, allow_degenerate=True, use_classic=False) # offset with respect to simulation domain corner #print("simext",simext) verts[:, 0] = verts[:, 0] + simext[0] verts[:, 1] = verts[:, 1] + simext[2] verts[:, 2] = verts[:, 2] + simext[4] # # Crop surface to box area # verts = [] # faces = [] # for i in np.arange(len(verts_nocrop[:,0])): # if ((verts_nocrop[i,0] > boxcoords[0]) and (verts_nocrop[i,0] < boxcoords[1]) and # (verts_nocrop[i,1] > boxcoords[2]) and (verts_nocrop[i,1] < boxcoords[3]) and # (verts_nocrop[i,2] > boxcoords[4]) and (verts_nocrop[i,2] < boxcoords[5])): # verts.append(verts_nocrop[i,:]) # faces.append(faces_nocrop[i,:]) # This is now incorrect # else: # dropped = dropped+1 # verts = np.asarray(verts) # faces = np.asarray(faces) # Next find color variable values at vertices if color_var != None: nverts = len(verts[:, 0]) print("Extracting color values for " + str(nverts) + " vertices and " + str(len(faces[:, 0])) + " faces.") all_coords = np.empty((nverts, 3)) for i in np.arange(nverts): # # due to mesh generation, some coordinates may be outside simulation domain # WARNING this means it might be doing wrong things in the periodic dimension of 2.9D runs. coords = verts[i, :] * unit coords[0] = max(coords[0], simext_org[0] + 0.1 * cellsize) coords[0] = min(coords[0], simext_org[1] - cellsize) coords[1] = max(coords[1], simext_org[2] + 0.1 * cellsize) coords[1] = min(coords[1], simext_org[3] - cellsize) coords[2] = max(coords[2], simext_org[4] + 0.1 * cellsize) coords[2] = min(coords[2], simext_org[5] - cellsize) all_coords[i] = coords # Use interpolated values, WARNING periodic y (2.9 polar) hard-coded here /!\ color_data = f.read_interpolated_variable( color_var, all_coords, operator=color_op, periodic=["False", "True", "False"]) # Make sure color data is 1-dimensional (e.g. magnitude of E instead of 3 components) if np.ndim(color_data) != 1: color_data = np.linalg.norm(color_data, axis=-1) if color_var == None: # dummy norm print("No surface color given, using dummy setup") norm = BoundaryNorm([0, 1], ncolors=cmapuse.N, clip=True) vminuse = 0 vmaxuse = 1 else: # If automatic range finding is required, find min and max of array # Performs range-finding on a masked array to work even if array contains invalid values color_data = np.ma.masked_invalid(color_data) if vmin != None: vminuse = vmin else: vminuse = np.ma.amin(color_data) if vmax != None: vmaxuse = vmax else: vmaxuse = np.ma.amax(color_data) # If vminuse and vmaxuse are extracted from data, different signs, and close to each other, adjust to be symmetric # e.g. to plot transverse field components if vmin == None and vmax == None: if (vminuse * vmaxuse < 0) and ( abs(abs(vminuse) - abs(vmaxuse)) / abs(vminuse) < 0.4 ) and (abs(abs(vminuse) - abs(vmaxuse)) / abs(vmaxuse) < 0.4): absval = max(abs(vminuse), abs(vmaxuse)) if vminuse < 0: vminuse = -absval vmaxuse = absval else: vminuse = absval vmaxuse = -absval # Check that lower bound is valid for logarithmic plots if (vminuse <= 0) and (lin == None) and (symlog == None): # Drop negative and zero values vminuse = np.ma.amin(np.ma.masked_less_equal(color_data, 0)) # If symlog scaling is set: if symlog != None: if symlog > 0: linthresh = symlog else: linthresh = max(abs(vminuse), abs(vmaxuse)) * 1.e-2 # Lin or log colour scaling, defaults to log if lin == None: # Special SymLogNorm case if symlog != None: #norm = SymLogNorm(linthresh=linthresh, linscale = 0.3, vmin=vminuse, vmax=vmaxuse, ncolors=cmapuse.N, clip=True) norm = SymLogNorm(linthresh=linthresh, linscale=0.3, vmin=vminuse, vmax=vmaxuse, clip=True) maxlog = int(np.ceil(np.log10(vmaxuse))) minlog = int(np.ceil(np.log10(-vminuse))) logthresh = int(np.floor(np.log10(linthresh))) logstep = 1 ticks = ( [-(10**x) for x in range(logthresh, minlog + 1, logstep)][::-1] + [0.0] + [(10**x) for x in range(logthresh, maxlog + 1, logstep)]) else: norm = LogNorm(vmin=vminuse, vmax=vmaxuse) ticks = LogLocator(base=10, subs=list( range(10))) # where to show labels else: # Linear levels = MaxNLocator(nbins=255).tick_values(vminuse, vmaxuse) norm = BoundaryNorm(levels, ncolors=cmapuse.N, clip=True) ticks = np.linspace(vminuse, vmaxuse, num=7) print("Selected color range: " + str(vminuse) + " to " + str(vmaxuse)) # Create 300 dpi image of suitable size fig = plt.figure(figsize=[4.0, 4.0], dpi=300) #ax1 = fig.gca(projection='3d') ax1 = fig.add_subplot(111, projection='3d') # Generate virtual bounding box to get equal aspect maxrange = np.array([ boxcoords[1] - boxcoords[0], boxcoords[3] - boxcoords[2], boxcoords[5] - boxcoords[4] ]).max() / 2.0 midvals = np.array([ boxcoords[1] + boxcoords[0], boxcoords[3] + boxcoords[2], boxcoords[5] + boxcoords[4] ]) / 2.0 # Three options: # 2.9D ecliptic, 2.9D polar, or 3D if ysize < 0.2 * xsize: # 2.9D polar, perform rotation generatedsurface = ax1.plot_trisurf(verts[:, 2], verts[:, 0], verts[:, 1], triangles=faces, cmap=cmapuse, norm=norm, vmin=vminuse, vmax=vmaxuse, lw=0, shade=False, edgecolors=None, antialiased=False) ax1.set_xlabel("z [" + unitstr + "]", fontsize=fontsize3) ax1.set_ylabel("x [" + unitstr + "]", fontsize=fontsize3) ax1.set_zlabel("y [" + unitstr + "]", fontsize=fontsize3) # Set camera angle ax1.view_init(elev=30., azim=90) # Set virtual bounding box ax1.set_xlim([midvals[2] - maxrange, midvals[2] + maxrange]) ax1.set_ylim([midvals[0] - maxrange, midvals[0] + maxrange]) ax1.set_zlim([midvals[1] - maxrange, midvals[1] + maxrange]) ax1.tick_params(labelsize=fontsize3) #,width=1.5,length=3) else: # 3D or 2.9D ecliptic, leave as is generatedsurface = ax1.plot_trisurf(verts[:, 0], verts[:, 1], verts[:, 2], triangles=faces, cmap=cmapuse, norm=norm, vmin=vminuse, vmax=vmaxuse, lw=0.2, shade=False, edgecolors=None) ax1.set_xlabel("x [" + unitstr + "]", fontsize=fontsize3) ax1.set_ylabel("y [" + unitstr + "]", fontsize=fontsize3) ax1.set_zlabel("z [" + unitstr + "]", fontsize=fontsize3) # Set camera angle ax1.view_init(elev=30., azim=0) # Set virtual bounding box ax1.set_xlim([midvals[0] - maxrange, midvals[0] + maxrange]) ax1.set_ylim([midvals[1] - maxrange, midvals[1] + maxrange]) ax1.set_zlim([midvals[2] - maxrange, midvals[2] + maxrange]) ax1.tick_params(labelsize=fontsize3) #,width=1.5,length=3) # Setting per-triangle colours for plot_trisurf needs to be done # as a separate set_array call. if color_var != None: # Find face-averaged colors # (simply setting the array to color_data failed for some reason) colors = np.mean(color_data[faces], axis=1) generatedsurface.set_array(colors) # Title and plot limits if len(plot_title) != 0: ax1.set_title(plot_title, fontsize=fontsize2, fontweight='bold') # ax1.set_aspect('equal') #<<<--- this does not work for 3D plots! # for axis in ['top','bottom','left','right']: # ax1.spines[axis].set_linewidth(thick) # ax1.xaxis.set_tick_params(width=thick,length=3) # ax1.yaxis.set_tick_params(width=thick,length=3) # #ax1.xaxis.set_tick_params(which='minor',width=3,length=5) # #ax1.yaxis.set_tick_params(which='minor',width=3,length=5) if cbtitle == None: cb_title_use = cb_title else: cb_title_use = cbtitle if nocb == None: # First draw colorbar if usesci == 0: cb = fig.colorbar(generatedsurface, ticks=ticks, drawedges=False, fraction=0.023, pad=0.02) else: cb = fig.colorbar(generatedsurface, ticks=ticks, format=mtick.FuncFormatter(fmt), drawedges=False, fraction=0.046, pad=0.04) if len(cb_title_use) != 0: cb.ax.set_title(cb_title_use, fontsize=fontsize2, fontweight='bold') cb.ax.tick_params(labelsize=fontsize3) #,width=1.5,length=3) cb.outline.set_linewidth(thick) # if too many subticks: if lin == None and usesci != 0 and symlog == None: # Note: if usesci==0, only tick labels at powers of 10 are shown anyway. # For non-square pictures, adjust tick count nlabels = len(cb.ax.yaxis.get_ticklabels()) / ratio valids = ['1', '2', '3', '4', '5', '6', '7', '8', '9'] if nlabels > 10: valids = ['1', '2', '3', '4', '5', '6', '8'] if nlabels > 19: valids = ['1', '2', '5'] if nlabels > 28: valids = ['1'] # for label in cb.ax.yaxis.get_ticklabels()[::labelincrement]: for label in cb.ax.yaxis.get_ticklabels(): # labels will be in format $x.0\times10^{y}$ if not label.get_text()[1] in valids: label.set_visible(False) # Add Vlasiator watermark if wmark != None: wm = plt.imread(get_sample_data(watermarkimage)) newax = fig.add_axes([0.01, 0.90, 0.3, 0.08], anchor='NW', zorder=-1) newax.imshow(wm) newax.axis('off') plt.tight_layout() savefig_pad = 0.1 # The default is 0.1 bbox_inches = None # Save output or draw on-screen if draw == None: # Note: generated title can cause strange PNG header problems # in rare cases. This problem is under investigation, but is related to the exact generated # title string. This try-catch attempts to simplify the time string until output succedes. try: plt.savefig(savefigname, dpi=300, bbox_inches=bbox_inches, pad_inches=savefig_pad) savechange = 0 except: savechange = 1 plot_title = "t=" + '{:4.1f}'.format(timeval) + ' s ' ax1.set_title(plot_title, fontsize=fontsize2, fontweight='bold') try: plt.savefig(savefigname, dpi=300, bbox_inches=bbox_inches, pad_inches=savefig_pad) except: plot_title = "t=" + str(np.int(timeval)) + ' s ' ax1.set_title(plot_title, fontsize=fontsize2, fontweight='bold') try: plt.savefig(savefigname, dpi=300, bbox_inches=bbox_inches, pad_inches=savefig_pad) except: plot_title = "" ax1.set_title(plot_title, fontsize=fontsize2, fontweight='bold') try: plt.savefig(savefigname, dpi=300, bbox_inches=bbox_inches, pad_inches=savefig_pad) except: print("Error:", sys.exc_info()) print( "Error with attempting to save figure, sometimes due to matplotlib LaTeX integration." ) print( "Usually removing the title should work, but this time even that failed." ) savechange = -1 if savechange > 0: print("Due to rendering error, replaced image title with " + plot_title) if savechange >= 0: print(savefigname + "\n") else: plt.draw() plt.show()
import numpy as np import matplotlib.pyplot as plt from matplotlib.cbook import get_sample_data fname = get_sample_data('percent_bachelors_degrees_women_usa.csv', asfileobj=False) gender_degree_data = np.genfromtxt(fname, delimiter=',', names=True) # You typically want your plot to be ~1.33x wider than tall. This plot # is a rare exception because of the number of lines being plotted on it. # Common sizes: (10, 7.5) and (12, 9) fig, ax = plt.subplots(1, 1, figsize=(12, 14)) # These are the colors that will be used in the plot ax.set_prop_cycle(color=[ '#1f77b4', '#aec7e8', '#ff7f0e', '#ffbb78', '#2ca02c', '#98df8a', '#d62728', '#ff9896', '#9467bd', '#c5b0d5', '#8c564b', '#c49c94', '#e377c2', '#f7b6d2', '#7f7f7f', '#c7c7c7', '#bcbd22', '#dbdb8d', '#17becf', '#9edae5']) # Remove the plot frame lines. They are unnecessary here. ax.spines[:].set_visible(False) # Ensure that the axis ticks only show up on the bottom and left of the plot. # Ticks on the right and top of the plot are generally unnecessary. ax.xaxis.tick_bottom() ax.yaxis.tick_left() fig.subplots_adjust(left=.06, right=.75, bottom=.02, top=.94) # Limit the range of the plot to only where the data is.
import sys # subject_id = int(sys.argv[1]) # minimum_users = int(sys.argv[2]) subject_id = 511723 project = AggregationAPI(348, public_panoptes_connection=True) subject_image = project.__image_setup__(subject_id) for minimum_users in [8]: print minimum_users fig, ax = plt.subplots() image_file = cbook.get_sample_data(subject_image) image = plt.imread(image_file) # fig, ax = plt.subplots() im = ax.imshow(image) all_vertices = [] with open("/tmp/348/4_ComplexAMOS/vegetation_polygons_heatmap.csv", "rb") as f: polygon_reader = csv.reader(f) next(polygon_reader, None) for row in polygon_reader: if int(row[1]) == minimum_users: vertices = json.loads(row[2]) all_vertices.append(vertices)
import random import numpy as np import matplotlib.pyplot as plt import matplotlib.cbook as cbook from matplotlib import animation case = random.sample([1, 2, 3], 1)[0] if case == 1: with cbook.get_sample_data( '/home/diego/Documents/HackOxford/Hack-Oxford/Web/Images/academic_brain.png' ) as file: image = plt.imread(file) suggestions = [ 'Congratulations!', 'You are on track.', 'Stay curious and try our StudyBuddy feature.' ] elif case == 2: with cbook.get_sample_data( '/home/diego/Documents/HackOxford/Hack-Oxford/Web/Images/slacking_brain.png' ) as file: image = plt.imread(file) suggestions = [ 'You need to get more organised.', 'Check out #videos that can help you organise better.', 'Stay curious and try our StudyBuddy feature.' ] elif case == 3: with cbook.get_sample_data( '/home/diego/Documents/HackOxford/Hack-Oxford/Web/Images/anxious_tired_brain.png' ) as file:
def plot_cloud_liquid(df_site, station, station_name_file, station_name_plot, logo_path, current_dt, test): ''' Takes in a df with field variables integrated vapor, integrated liquid, cloud base (km), and a rain flag of either 0.0 or 1.0. Outputs a scatter plot of the df variables with the left axis in kilometers and the right axis in mm liquid/ cm vapor. Parameters: df_site (dataframe): pandas dataframe of profiler data for that station. station (str): string of the 4 character station name. station_name_file (str): string of station location used in filename station_name_plot (str): string of station location used in plot title logo_path (string): full path to logo file current_dt (datetime): current date & hour test (logical): if True, ftp to test location; if False, ftp to FC Returns: Scatter plot output to (plotDirBase+'/mwr/'+today_date) ''' # Make sure df_site is not full of NaN's cl_columns = [ 'integrated_vapor', 'integrated_liquid', 'cloud_base', 'rain_flag' ] empty_columns = [] for col in df_site.columns: if col in cl_columns and df_site[col].count() == 0: empty_columns.append(col) if len(empty_columns) > 0: print(' df_site missing data - no mwr cloud plot will be created.') return # --------------------------- # GET DATA READY FOR PLOTTING # --------------------------- # Get times times_df = pd.DataFrame(df_site.index.get_level_values('time')) #times_array = np.array(times_df.drop_duplicates()['time']) times_array = np.array(times_df['time']) datetimes_array = pd.to_datetime(times_array) # Get start and stop time strings for plot title and current date string graphtimestamp_start = datetimes_array[0].strftime("%H UTC %m/%d/%y") graphtimestamp_end = current_dt.strftime("%H UTC %m/%d/%y") today_date = current_dt.strftime('%Y%m%d') # Get non-zero values of rain flag which represent rain rain = df_site['rain_flag'].values rain_indices = np.where(rain != 0.0)[0] # ----------- # CREATE PLOT # ----------- fig, axL = plt.subplots(figsize=(9, 7.875)) #axL.set_title('{} ({}) Derived MWR Products\n{} - {}'.format( # station_name, station, graphtimestamp_start, graphtimestamp_end), fontsize = 24) plt.suptitle('{} ({}) Derived MWR Products'.format(station_name_plot, station), x=0.57, fontsize=24) plt.title('{} - {}'.format(graphtimestamp_start, graphtimestamp_end), ha='center', fontsize=20) # Height axis for cloud base height height_ticks = np.arange(0, 11, 1) axL.set_ylim(0, 10) axL.set_yticks(height_ticks) axL.set_yticklabels(height_ticks, fontsize=13) # 16 in field axL.set_ylabel('Cloud Base (km)', fontsize=15) # 20 in field # Right axis for integrated liquid/vapor axR = axL.twinx() axR.set_ylim(0, 10) axR.set_yticks(height_ticks) axR.set_yticklabels(height_ticks, fontsize=13) # 16 in field axR.set_ylabel('Integrated Moisture (mm liquid | cm vapor)', fontsize=15) # 20 in field # Make scatter plots cb = axL.scatter(datetimes_array.values, df_site['cloud_base'].values, c='black') #in kms iv = axR.scatter(datetimes_array.values, df_site['integrated_vapor'].values, c='red') il = axR.scatter(datetimes_array.values, df_site['integrated_liquid'].values, c='blue') # Plot vertical line for rainfall, and save last line as object for legend try: # WHY STOP AT SECOND LAST VALID INDEX? for rainy_time in datetimes_array[rain_indices][:-1]: # Set low value for alpha to get lighter color axL.axvline(rainy_time, color='g', alpha=.2) rf = axL.axvline(datetimes_array[rain_indices][-1], color='g', alpha=.5) axR.legend((cb, iv, il, rf), ("Cloud Base", "Integrated Vapor", "Integrated Liquid", "Rain Flag"), fontsize=14) # 16 in field except: axR.legend((cb, iv, il), ("Cloud Base", "Integrated Vapor", "Integrated Liquid"), fontsize=14) # 16 in field # Get the time ticks axL.set_xlabel('Time (UTC)', fontsize=15) # 20 in field # Add ticks at labeled times axL.tick_params(axis='x', which='both', bottom='on', top='off') axL.yaxis.grid(linestyle='--') # One date written per day axL.xaxis.set_major_locator(DayLocator(interval=1)) # Show date, written as 'Jul-12' axL.xaxis.set_major_formatter(DateFormatter('%b-%d')) # Hour labels every 2 hours axL.xaxis.set_minor_locator(HourLocator(byhour=range(2, 24, 2), interval=1)) # Show hour labels axL.xaxis.set_minor_formatter(DateFormatter('%H')) # Axis will squueze to size of actual data axL.set_xlim(current_dt - timedelta(hours=24), datetimes_array[-1]) axL.get_yaxis().set_label_coords(-0.04, 0.5) axL.xaxis.get_major_ticks()[0].label.set_fontsize(13) # 16 in field for tick in axL.xaxis.get_minor_ticks(): tick.label.set_fontsize(14) # 16 in field # Add mesonet logo fig.subplots_adjust(bottom=0.1, left=.05, right=1.1) # Read image from file to array im = plt.imread(get_sample_data(logo_path)) # Add axes, plot image and remove x and y axes new_ax = fig.add_axes([1.07, -0.01, 0.1, 0.1]) new_ax.imshow(im) new_ax.axis('off') # Save plot plot_path = plotDirBase + '/mwr/' + today_date if not os.path.exists(plot_path): os.makedirs(plot_path) catName = 'upperair.MWR.' + current_dt_string + '.NYSM_' + station_name_file + '_cloud.png' plt.savefig(plot_path + '/' + catName, bbox_inches='tight') print(' Plotted ' + 'cloud/liquid profile' + ' for ' + station) # Clear current figure and axes, and close window - this is probably redundant:-) plt.clf, plt.cla(), plt.close()
def lidar_field_plotting(station, station_name_file, station_name_plot, df_site, field, logo_path, current_dt, test): ''' Takes in the lidar data and will produce a plot of either CNR, Horizonal Speed or Vertical Speed for a specific station. Each plot will range from 100m to 3000m and will have wind barbs with the direction of wind. Parameters: station (str): string of the 4 character station name. station_name_file (str): string of station location used in filename station_name_plot (str): string of station location used in plot title df_site (dataframe): pandas dataframe of lidar data for that station. field (string): must be one of ['cnr', 'w', 'velocity'] logo_path (string): full path to logo file current_dt (datetime): current date & hour test (logical): if True, ftp to test location; if False, ftp to FC Returns: Plot of field data output to (plotDirBase+'/lidar/'+today_date) ''' # Make sure df_site is not full of NaN's empty_columns = [] for col in df_site.columns: if df_site[col].count() == 0: empty_columns.append(col) if len(empty_columns) > 0: #print(' df_site missing {} - no {} plot will be created.'.format(empty_columns,field)) print(' df_site missing data - no {} plot will be created.'.format( field)) return # --------------------------- # GET DATA READY FOR PLOTTING # --------------------------- # Get heights (which are one of indices) between 100-3000m heights_df = pd.DataFrame(df_site.index.get_level_values('range')) heights_df = heights_df.loc[(heights_df['range'] >= 100) & (heights_df['range'] <= 3000)] # Flip array (highest to lowest value) for plotting heights_array = np.flip(np.array(heights_df.drop_duplicates()['range'])) # Get times (which are one of indices) times_df = pd.DataFrame(df_site.index.get_level_values('time')) times_array = np.array(times_df.drop_duplicates()['time']) if len(times_array) < min_times: print( ' df_site has only {} times - no {} plot will be created.'.format( len(times_array), field)) return datetimes_array = pd.to_datetime(times_array) #pd.Timestamp(val).to_pydatetime() # Get start and stop time strings for plot title and current date string graphtimestamp_start = datetimes_array[0].strftime("%H UTC %m/%d/%y") graphtimestamp_end = current_dt.strftime("%H UTC %m/%d/%y") today_date = current_dt.strftime('%Y%m%d') # Swap df_site indices so range is first and time is second df_site = df_site.swaplevel() # Initialize field_array (contains data in 'field' input param) field_array = np.zeros([len(heights_array), len(times_array)]) # Create empty Uwind and Vwind arrays and fill with NaN's Uwind = np.full([len(heights_array), len(times_array)], np.nan) Vwind = np.full([len(heights_array), len(times_array)], np.nan) # Fill in field_array, Uwind and Vwind arrays for i in range(0, len(times_array)): for j in range(0, len(heights_array)): field_array[j, i] = df_site.loc[(heights_array[j], times_array[i]), field] direction = df_site.loc[(heights_array[j], times_array[i]), 'direction'] velocity = df_site.loc[(heights_array[j], times_array[i]), 'velocity'] """ #Take every other row and column of wind data if (j % 2 == 0) and (i % 2 == 0): # According to: # http://colaweb.gmu.edu/dev/clim301/lectures/wind/wind-uv # to convert from "wind weather direction" to "math direction" use: # md = 270 − wwd # If result < 0, add 360 if direction > 270: Uwind[j,i] = np.cos((360+(270. - direction))/180.*np.pi)*velocity Vwind[j,i] = np.sin((360+(270. - direction))/180.*np.pi)*velocity else: Uwind[j,i] = np.cos((270. - direction)/180.*np.pi)*velocity Vwind[j,i] = np.sin((270. - direction)/180.*np.pi)*velocity """ if direction > 270: Uwind[j, i] = np.cos( (360 + (270. - direction)) / 180. * np.pi) * velocity Vwind[j, i] = np.sin( (360 + (270. - direction)) / 180. * np.pi) * velocity else: Uwind[j, i] = np.cos( (270. - direction) / 180. * np.pi) * velocity Vwind[j, i] = np.sin( (270. - direction) / 180. * np.pi) * velocity # ----------- # CREATE PLOT # ----------- # Get the smallest and largest non-nan of the field_array data field_max = np.nanmax(field_array) field_min = np.nanmin(field_array) # Get the binsize based off the amount of bins defined globally binsize = (field_max - field_min) / bin_number # Round levels more precisely, define colorbar levels and choose cmap if field == 'w': levs = np.arange(-5, 5.01, 0.25) cblevs = np.arange(-5, 5.01, 1) colormap = 'bwr' extend = 'both' elif field == 'cnr': levs = np.arange(-30, 6, 1) cblevs = np.arange(-30, 6, 5) colormap = 'gist_ncar' extend = 'max' else: # for velocity levs = np.arange(0, 101, 2) # np.round(levs) cblevs = np.arange(0, 101, 10) colormap = 'nipy_spectral' #'cool' extend = 'max' # Create figure fig, ax = plt.subplots(figsize=(10, 5.625)) # Background array allows for the figure background color to be customized background = np.zeros([len(heights_array), len(times_array)]) # Plot field filled contours and Uwind and Vwind vectors # Background color ax.contourf(datetimes_array, heights_array / 1000., background, colors='aliceblue') color_plot = ax.contourf(datetimes_array, heights_array / 1000., field_array, levels=levs, extend=extend, cmap=colormap) # Use every fourth wind value; length is length of barb in points ax.barbs(datetimes_array[::4], heights_array[::4] / 1000., Uwind[::4, ::4], Vwind[::4, ::4], length=6) # Use every second wind value; length is length of barb in points #ax.barbs(datetimes_array[::2],heights_array[::2]/1000.,Uwind[::2, ::2],Vwind[::2, ::2], # length = 6) # Only plots black contour lines for vertical velocity or CNR data if field == 'w' or field == 'cnr': # Use every fourth level value contour = ax.contour(datetimes_array, heights_array / 1000., field_array, levels=levs[::4], colors='black') # Add labels to contours plt.clabel(contour, fmt='%1.1f', colors='white') # Plot colorbar cb = plt.colorbar(color_plot) cb.set_ticks(cblevs) cb.set_ticklabels(cblevs) cb.ax.tick_params(labelsize=14) # Label colorbar and get info for plot title # W and velocity have the same units if field == 'cnr': cb.set_label('CNR (dB)', fontsize=16) # 20 in field field_title = 'Carrier-to-Noise Ratio' save_name = field elif field == 'w': cb.set_label('m s$^{-1}$', fontsize=16) # 20 in field field_title = 'Vertical Velocity' save_name = 'vert_wspd' elif field == 'velocity': cb.set_label('kt', fontsize=16) # 20 in field field_title = 'Horizontal Velocity' save_name = 'horz_wspd' else: # SINCE WE ALREADY CHECKED FOR VALID FIELD THIS MIGHT NOT BE NECESSARY cb.set_label('dB', fontsize=16) # 20 in field field_title = field.upper() save_name = field # Set title & subtitle of plot #ax.set_title('{} ({}) Lidar {}\n{} - {}'.format(station_name, station, field_title, # graphtimestamp_start, # graphtimestamp_end), fontsize = 24) if field == 'cnr': plt.suptitle('{} ({}) Lidar {}'.format(station_name_plot, station, field_title), x=0.47, fontsize=22) elif field == 'w': plt.suptitle('{} ({}) Lidar {}'.format(station_name_plot, station, field_title), x=0.465, fontsize=22) elif field == 'velocity': plt.suptitle('{} ({}) Lidar {}'.format(station_name_plot, station, field_title), x=0.465, fontsize=22) plt.title('{} - {}'.format(graphtimestamp_start, graphtimestamp_end), ha='center', fontsize=18) # Set Y-axis height ticks height_ticks = np.array([0.1, 0.5, 1, 1.5, 2, 2.5, 3]) ax.set_yticks(height_ticks) ax.set_yticklabels(height_ticks, fontsize=14) # 16 in field ax.set_ylim(0.1, 3) ax.set_ylabel('Height (km)', fontsize=16) # 20 in field # Set X-axis time ticks ax.set_xlabel('Time (UTC)', fontsize=16) # 20 in field # DO WE NEED NEXT LINE? (add ticks at labeled times) ax.tick_params(axis='x', which='both', bottom='on', top='off') ax.tick_params(axis='both', which='major', length=8) ax.tick_params(axis='both', which='minor', length=4) ax.yaxis.grid(linestyle='--') ax.set_xlim(current_dt - timedelta(hours=24), datetimes_array[-1]) # One date written per day ax.xaxis.set_major_locator(DayLocator(interval=1), ) # Show date, written as 'Jul-12' ax.xaxis.set_major_formatter(DateFormatter('%b-%d')) # Hour labels every 2 hours ax.xaxis.set_minor_locator(HourLocator(byhour=range(2, 24, 2), interval=1)) # Show hour labels ax.xaxis.set_minor_formatter(DateFormatter('%H')) ax.get_yaxis().set_label_coords(-0.08, 0.5) ax.xaxis.get_major_ticks()[0].label.set_fontsize(14) # 16 in field cb.ax.tick_params(labelsize=14) # 16 in field for tick in ax.xaxis.get_minor_ticks(): tick.label.set_fontsize(14) # 16 in field # Add mesonet logo fig.subplots_adjust(bottom=0.1, left=.05, right=1.1) # Read image from file to array im = plt.imread(get_sample_data(logo_path)) # Add axes, plot image and remove x and y axes #new_ax = fig.add_axes([0.95, -0.02, 0.1, 0.1]) new_ax = fig.add_axes([0.93, -0.02, 0.1, 0.1]) new_ax.imshow(im) new_ax.axis('off') # Save plot plot_path = plotDirBase + '/lidar/' + today_date if not os.path.exists(plot_path): os.makedirs(plot_path) catName = 'lidar.DL.' + current_dt_string + '.NYSM_' + station_name_file + '_' + field + '.png' plt.savefig(plot_path + '/' + catName, bbox_inches='tight') print(' Plotted ' + field + ' Lidar' + ' for ' + station) # Clear current figure and axes, and close window - this is probably redundant:-) plt.clf, plt.cla(), plt.close()
def plot_mwr_ts(df_site, station, station_name_file, station_name_plot, logo_path, current_dt, test): ''' Given profiler dataframe and station ID, save plot of mwr profiler data Parameters: df_site (dataframe): pandas dataframe of mwr time series data for that station. station (str): string of station ID station_name_file (str): string of station location used in filename station_name_plot (str): string of station location used in plot title logo_path (string): full path to logo file current_dt (datetime): current date & hour test (logical): if True, ftp to test location; if False, ftp to FC Returns: Timeseries plot output to (plotDirBase+'/mwr/'+today_date) ''' # Make sure df_site is not full of NaN's ts_columns = [ 'temperature', 'liquid', 'vapor_density', 'relative_humidity' ] empty_columns = [] for col in df_site.columns: if col in ts_columns and df_site[col].count() == 0: empty_columns.append(col) if len(empty_columns) == len(ts_columns): #print(' df_site missing data for {} - no mwr timeseries plot will be created.'.format(ts_columns)) print( ' df_site missing data - no mwr timeseries plot will be created.') return # --------------------------- # GET DATA READY FOR PLOTTING # --------------------------- # Get times (which are first level index) times_df = pd.DataFrame(df_site.index.get_level_values('time')) times_array = np.array(times_df.drop_duplicates()['time']) datetimes_array = pd.to_datetime(times_array) # Get heights (which are second level index) heights_df = pd.DataFrame(df_site.index.get_level_values('range')) # Flip height vector since rows run from top to bottom heights_array = np.flip(np.array(heights_df.drop_duplicates()['range'])) #heights_array = np.array(heights_df.drop_duplicates()['range']) # Get start and stop time strings for plot title and current date string graphtimestamp_start = datetimes_array[0].strftime("%H UTC %m/%d/%y") graphtimestamp_end = current_dt.strftime("%H UTC %m/%d/%y") today_date = current_dt.strftime('%Y%m%d') # Create empty temperature, theta, liquid and rel humidity arrays temps_array = np.empty([len(heights_array), len(times_array)]) * np.nan lq_array = np.empty([len(heights_array), len(times_array)]) * np.nan vd_array = np.empty([len(heights_array), len(times_array)]) * np.nan rh_array = np.empty([len(heights_array), len(times_array)]) * np.nan # Fill arrays for contour plotting so heights are reversed (high to low) # & dims order = (heights,time) if df_site['temperature'].count() > 0: temps_df = pd.DataFrame(df_site['temperature']) temps_array = K_to_C( np.flip( np.transpose( np.array(temps_df).reshape( (len(times_array), len(heights_array)))), 0)) if df_site['liquid'].count() > 0: lq_df = pd.DataFrame(df_site['liquid']) lq_array = np.flip( np.transpose( np.array(lq_df).reshape( (len(times_array), len(heights_array)))), 0) if df_site['vapor_density'].count() > 0: vd_df = pd.DataFrame(df_site['vapor_density']) vd_array = np.flip( np.transpose( np.array(vd_df).reshape( (len(times_array), len(heights_array)))), 0) if df_site['relative_humidity'].count() > 0: rh_df = pd.DataFrame(df_site['relative_humidity']) rh_array = np.flip( np.transpose( np.array(rh_df).reshape( (len(times_array), len(heights_array)))), 0) # ----------- # CREATE PLOT # ----------- fig = plt.figure(figsize=(10, 7.875)) axes = [] # TEMPERATURE ax1 = fig.add_subplot(4, 1, 1) # 4x1 grid, 1st subplot # QUESTION - shouldn't temps_array be (times x range) instead of (range x times)? if np.count_nonzero( np.isnan(temps_array)) != len(heights_array) * len(times_array): temp = ax1.contourf( datetimes_array, heights_array / 1000., temps_array, #levels=np.arange(-50,21,2),extend='both', cmap='viridis') levels=np.arange(-50, 21, 2), extend='both', cmap='jet') contour = ax1.contour(datetimes_array, heights_array / 1000., temps_array, levels=np.arange(-50, 21, 10), colors='grey') else: ax1.text(0.5, 0.20, 'NO DATA AVAILABLE', horizontalalignment='center') # Make labels plt.clabel(contour, fmt='%1.f', colors='green') # plot contour labels cb = plt.colorbar(temp) cb.set_ticks(np.arange(-50, 21, 10)) cb.set_ticklabels(np.arange(-50, 21, 10)) cb.ax.tick_params(labelsize=13) # 16 in field cb.set_label('Temp. ($^\circ$C)', fontsize=13) # 16 in field ax1.tick_params(axis='x', which='both', bottom='off', top='off') ax1.set_xticks([]) #ax1.set_title('{} ({}) MWR Products\n{} - {}'.format(station_name, station, graphtimestamp_start, # graphtimestamp_end), fontsize = 24) plt.suptitle('{} ({}) MWR Products'.format(station_name_plot, station), x=0.465, fontsize=24) plt.title('{} - {}'.format(graphtimestamp_start, graphtimestamp_end), ha='center', fontsize=20) axes.append(ax1) #LIQUID ax2 = fig.add_subplot(4, 1, 2) # 4x1 grid, 2nd subplot # Get lower and upper ends of log of data levs = np.power(10, np.arange(-3, 0.01, 0.125)) # These are powers of 10 for y-axis if np.count_nonzero( np.isnan(lq_array)) != len(heights_array) * len(times_array): lq = ax2.contourf(datetimes_array, heights_array / 1000., lq_array, levels=levs, extend='both', cmap='rainbow') # Contour only every 8th level (10^-2,10^-1,10^0) contour = ax2.contour(datetimes_array, heights_array / 1000., lq_array, levels=levs[8::8], colors='black') else: ax2.text(0.5, 0.20, 'NO DATA AVAILABLE', horizontalalignment='center') # Make labels in log format fmt = matplotlib.ticker.LogFormatterMathtext() plt.clabel(contour, contour.levels, fmt=fmt, colors='white') norm = matplotlib.colors.LogNorm(vmin=.001, vmax=1) sm = plt.cm.ScalarMappable(norm=norm, cmap=lq.cmap) sm.set_array([]) cb = plt.colorbar(sm) cb.set_ticks(levs[::8]) #cb.set_ticklabels(['$10^-3$','$10^-2$','$10^-1$','$10^0$']) cb.set_ticklabels(['$10^{-3}$', '$10^{-2}$', '$10^{-1}$', '$10^{0}$']) cb.ax.tick_params(labelsize=13) # 16 in field cb.set_label('Liquid (g m$^{-3}$)', fontsize=13) # 16 in field ax2.tick_params(axis='x', which='both', bottom='off', top='off') ax2.set_xticks([]) axes.append(ax2) # VAPOR DENSITY ax3 = fig.add_subplot(4, 1, 3) # 4x1 grid, 3rd subplot if np.count_nonzero( np.isnan(vd_array)) != len(heights_array) * len(times_array): vd = ax3.contourf(datetimes_array, heights_array / 1000., vd_array, levels=np.arange(0, 11, 1), extend='both', cmap='gist_ncar') contour = ax3.contour(datetimes_array, heights_array / 1000., vd_array, levels=np.arange(0, 11, 2), colors='grey') else: ax3.text(0.5, 0.20, 'NO DATA AVAILABLE', horizontalalignment='center') plt.clabel(contour, fmt='%1.f', colors='green') cb = plt.colorbar(vd) cb.set_ticks(np.arange(0, 11, 2)) cb.set_ticklabels(np.arange(0, 11, 2)) cb.ax.tick_params(labelsize=13) # 16 in field cb.set_label('Vap Den (g m$^{-3}$)', fontsize=13) # 16 in field ax3.tick_params(axis='x', which='both', bottom='off', top='off') ax3.set_xticks([]) axes.append(ax3) # RH ax4 = fig.add_subplot(4, 1, 4) if np.count_nonzero( np.isnan(rh_array)) != len(heights_array) * len(times_array): rh = ax4.contourf(datetimes_array, heights_array / 1000., rh_array, levels=np.arange(0, 110, 5), cmap='BrBG') contour = ax4.contour(datetimes_array, heights_array / 1000., rh_array, levels=np.array([40, 60, 80, 90, 99])) else: ax4.text(0.5, 0.20, 'NO DATA AVAILABLE', horizontalalignment='center') plt.clabel(contour, contour.levels, fmt='%1.f') cb = plt.colorbar(rh) cb.set_ticks(np.arange(0, 110, 20)) cb.set_ticklabels(np.arange(0, 110, 20)) cb.ax.tick_params(labelsize=13) # 16 in field cb.set_label('RH (%)', fontsize=13) # 16 in field ax4.set_xlabel('Time (UTC)', fontsize=15) # 16 in field # Place x-label away from figure ax4.get_xaxis().set_label_coords(0.5, -0.25) # Add ticks at labeled times ax4.tick_params(axis='x', which='both', bottom='on', top='off') ax4.tick_params(axis='x', which='major', length=8) ax4.tick_params(axis='x', which='minor', length=4) ax4.set_xlim(current_dt - timedelta(hours=24), datetimes_array[-1]) # One date written per day ax4.xaxis.set_major_locator(DayLocator(interval=1)) # Show date, written as 'Jul-12' ax4.xaxis.set_major_formatter(DateFormatter('%b-%d')) # Hour labels every 2 hours ax4.xaxis.set_minor_locator(HourLocator(byhour=range(2, 24, 2), interval=1)) # Show hour labels ax4.xaxis.set_minor_formatter(DateFormatter('%H')) ax4.xaxis.get_major_ticks()[0].label.set_fontsize(13) # 16 in field for tick in ax4.xaxis.get_minor_ticks(): tick.label.set_fontsize(13) # 16 in field axes.append(ax4) # Plot times from x-axis of each plot for ax in axes: ax.set_ylabel('Height (km)', fontsize=15) # 16 in field ax.tick_params(axis='y', which='both', left='on', right='off', labelsize=13) # 16 in field ax.tick_params(axis='y', which='major', length=8) ax.tick_params(axis='y', which='minor', length=4) ax.yaxis.grid(linestyle='--') # Place y-labels away from figure ax.get_yaxis().set_label_coords(-0.05, 0.5) # Add mesonet logo fig.subplots_adjust(bottom=0.1, left=.05, right=1.1) # Read image from file to array im = plt.imread(get_sample_data(logo_path)) # Add axes, plot image and remove x and y axes #new_ax = fig.add_axes([0.94, -0.01, 0.1, 0.1]) new_ax = fig.add_axes([0.93, -0.01, 0.1, 0.1]) new_ax.imshow(im) new_ax.axis('off') # Save plot plot_path = plotDirBase + '/mwr/' + today_date if not os.path.exists(plot_path): os.makedirs(plot_path) catName = 'upperair.MWR.' + current_dt_string + '.NYSM_' + station_name_file + '_timeseries.png' plt.savefig(plot_path + '/' + catName, bbox_inches='tight') print(' Plotted MWR for ' + station) # Clear current figure and axes, and close window - this is probably redundant:-) plt.clf, plt.cla(), plt.close()
def render(self): image_path_ego = get_sample_data('car-red.png') image_path_cars = get_sample_data('car-blue.png') local = np.argwhere(self.observation_grid[:, :, 0] == 1) plt.figure(1) ax1 = plt.subplot(2, 1, 1) ax2 = plt.subplot(2, 1, 2) ego = self.vehicle_list[0] ax1.plot([ego.x], [ego.y], 'ro') ax2.plot([ego.x], [ego.y], 'ro') # Car Pictures #imscatter([ego.x], [ego.y],image_path_ego,zoom=0.03,ax=ax1) #imscatter([ego.x], [ego.y], image_path_ego, zoom=0.03, ax=ax2) #ax2 = plt.step for lane in range(1, self.n_lanes + 1): ax1.axhline((lane - 1) * self.road_width + self.road_width * 0.5, color="g", linestyle="-", linewidth=1) ax2.axhline((lane - 1) * self.road_width + self.road_width * 0.5, color="g", linestyle="-", linewidth=1) ax1.axvline(ego.x - self.x_view, color="b", linestyle="-", linewidth=1) ax1.axvline(ego.x + self.x_view, color="b", linestyle="-", linewidth=1) x_cars = [] y_cars = [] x_cars_o = [] y_cars_o = [] for n in range(1, self.n_cars + 1): vehicle = self.vehicle_list[n] ax1.plot([vehicle.x], [vehicle.y], color='b', marker='x') #ax2.plot([vehicle.x], [vehicle.y], color='b', marker='x') x_cars.append(vehicle.x) y_cars.append(vehicle.y) if (len(local) > 0): for n in range(0, len(local)): x = int((local[n, 0] - self.x_view) + ego.x) y = int((local[n, 1] - self.y_view) + ego.y) if (y > 2): print(y) x_cars_o.append(x) y_cars_o.append(y) ax2.plot(x, y, color='y', marker='o') #### First picture #### #imscatter(x_cars, y_cars, image_path_cars, zoom=0.03, ax=ax1) ax1.grid() ax1.set_ylim( [1, (lane - 1) * self.road_width + self.road_width * 0.5 + 1]) ax1.set_title("Global Map") ax1.set_ylabel("Y-Position in [m]") ax1.set_xlabel("X-Position in [m]") #imscatter([ego.x], [ego.y], image_path_ego, zoom=0.03, ax=ax1) #### Second Picture ### #ax2.set_ylim([0,(lane-1)*self.road_width + self.road_width*0.5+2]) imscatter(x_cars_o, y_cars_o, image_path_cars, zoom=0.05, ax=ax2) imscatter([ego.x], [ego.y], image_path_ego, zoom=0.05, ax=ax2) ax2.set_ylim( [0, (lane - 1) * self.road_width + self.road_width * 0.5 + 2]) ax2.set_xlim([ego.x - self.x_view - 50, ego.x + self.x_view + 50]) ax2.text( ego.x + 10, ego.y + 0.5, "Ego-velocity:" + str(round(ego.v, 2)) + "\n" + "Distance: " + str(round(self.dist_to_front, 2))) ax2.set_title("Local Map") ax2.set_ylabel("Y-position in [m]") ax2.set_xlabel("X-position in [m]") plt.tight_layout() #img = plt.imread("images/road_2.jpg") #ax2.imshow(img) # Show plt.tight_layout() plt.show(block=False) plt.pause(self.dt) plt.clf()
# cell_rows = [(1267,1370),(1370,1428),(1428,1488),(1488,1547),(1547,1606),(1606,1665),(1665,1723),(1723,1781),(1781,1840),(1840,1899),(1899,1957),(1957,2016)] cell_columns = [(713, 821), (821, 890), (1067, 1252), (1527, 1739), (1739, 1837), (1837, 1949), (1949, 2053), (2053, 2156)] #(510,713), cell_rows = [(1226, 1320), (1320, 1377)] # s3://zooniverse-static/old-weather-2015/War_in_the_Arctic/Greenland_Patrol/Navy/Bear_AG-29_/ log_pages = list(os.listdir(image_directory)) for f_count, f_name in enumerate(log_pages): if not f_name.endswith(".JPG"): continue image_file = cbook.get_sample_data(image_directory + f_name) image = plt.imread(image_file) p_index = f_name.rfind(".") base_fname = f_name[:p_index] for row_index, (row_lb, row_ub) in enumerate(cell_rows): for column_index, (column_lb, column_ub) in enumerate(cell_columns): offset = 8 r = range(row_lb - offset, row_ub + offset) c = range(column_lb - offset, column_ub + offset) # print column_lb,column_ub # fig, ax = plt.subplots() sub_image = image[np.ix_(r, c)]
#ax.annotate('Date: '+cday+' '+chour+':00', xy=(0.785, 0.015), xycoords='figure fraction', **cfont_clock) ax.annotate('Date: '+cday+' '+chour+':00', xy=(0.3, 0.01), xycoords='figure fraction', **cfont_clock) ry0 = 0.78 #ry0 = 0.9 ax.annotate(cxtra_info1, xy=(0.02, ry0+0.05), xycoords='figure fraction', **cfont_titl1) if ctitle != "": ax.annotate(ctitle, xy=(0.03, ry0-0.01), xycoords='figure fraction', **cfont_titl2) # if l_show_logos: datafile = cbook.get_sample_data(dir_logos+'/'+f_logo_ige, asfileobj=False) im = image.imread(datafile) fig.figimage(im, 1010, 855, zorder=9) del datafile, im datafile = cbook.get_sample_data(dir_logos+'/'+f_logo_nersc, asfileobj=False) im = image.imread(datafile) fig.figimage(im, 990, 775, zorder=9) del datafile, im datafile = cbook.get_sample_data(dir_logos+'/'+f_logo_ifrmr, asfileobj=False) im = image.imread(datafile) if vp[0] == 'nanuk1': fig.figimage(im, 999, 722, zorder=9) elif vp[0] == 'nanuk2': fig.figimage(im, 1010, 722, zorder=9)
def get_demo_image(): from matplotlib.cbook import get_sample_data f = get_sample_data("axes_grid/bivariate_normal.npy", asfileobj=False) z = np.load(f) # z is a numpy array of 15x15 return z, (-3, 4, -4, 3)
app = QApplication(sys.argv) fig = Figure(figsize=(8, 6)) canvas = FigureCanvas(fig) canvas.resize(640, 480) canvas.show() years = mdates.YearLocator() # every year months = mdates.MonthLocator() # every month years_fmt = mdates.DateFormatter('%Y') # Load a numpy structured array from yahoo csv data with fields date, open, # close, volume, adj_close from the mpl-data/example directory. This array # stores the date as an np.datetime64 with a day unit ('D') in the 'date' # column. with cbook.get_sample_data('goog.npz') as datafile: data = np.load(datafile)['price_data'] ax = fig.subplots() ax.plot('date', 'adj_close', data=data) # format the ticks ax.xaxis.set_major_locator(years) ax.xaxis.set_major_formatter(years_fmt) ax.xaxis.set_minor_locator(months) # round to nearest years. datemin = np.datetime64(data['date'][0], 'Y') datemax = np.datetime64(data['date'][-1], 'Y') + np.timedelta64(1, 'Y') ax.set_xlim(datemin, datemax)
#> [<matplotlib.lines.Line2D at 0x10edbab70>] # 1D Data import numpy as np x = np.linspace(0, 10, 100) y = np.cos(x) z = np.sin(x) #2D Data data = 2 * np.random.random((10, 10)) data2 = 3 * np.random.random((10, 10)) Y, X = np.mgrid[-3:3:100j, -3:3:100j] U = -1 - X**2 + Y V = 1 + X - Y**2 from matplotlib.cbook import get_sample_data img = np.load(get_sample_data('axes_grid/bivariate_normal.npy')) # Creating plot import matplotlib.pyplot as plt fig = plt.figure() fig2 = plt.figure(figsize=plt.figaspect(2.0)) fig.add_axes() ax1 = fig.add_subplot(221) # row-col-num ax3 = fig.add_subplot(212) fig3, axes = plt.subplots(nrows=2,ncols=2) fig4, axes2 = plt.subplots(ncols=3) #1D Data ploting lines = ax.plot(x,y) # Draw points with lines or markers connecting them ax.scatter(x,y) # Draw unconnected points, scaled or colored axes[0,0].bar([1,2,3],[3,4,5]) # Plot vertical rectangles (constant width)
import numpy as np import matplotlib.pyplot as plt import matplotlib.dates as mdates import matplotlib.cbook as cbook years = mdates.YearLocator() # every year months = mdates.MonthLocator() # every month yearsFmt = mdates.DateFormatter('%Y') # Load a numpy record array from yahoo csv data with fields date, open, close, # volume, adj_close from the mpl-data/example directory. The record array # stores the date as an np.datetime64 with a day unit ('D') in the date column. with cbook.get_sample_data('../data/td3500.csv') as datafile: r = np.load(datafile)['cyan_data'].view(np.recarray) fig, ax = plt.subplots() ax.plot(r.date, r.cyan) # format the ticks ax.xaxis.set_major_locator(years) ax.xaxis.set_major_formatter(yearsFmt) ax.xaxis.set_minor_locator(months) # round to nearest years... datemin = np.datetime64(r.date[0], 'Y') datemax = np.datetime64(r.date[-1], 'Y') + np.timedelta64(1, 'Y') ax.set_xlim(datemin, datemax) # format the coords message box def price(x):
def render(self): image_path_ego = get_sample_data('car-red.png') image_path_cars = get_sample_data('car-blue.png') plt.figure(1) ax1 = plt.subplot(2, 1, 1) ax2 = plt.subplot(2, 1, 2) ego = self.vehicle_list[0] ax1.plot([ego.x], [ego.y], 'ro') ax2.plot([ego.x], [ego.y], 'ro') # Car Pictures #imscatter([ego.x], [ego.y],image_path_ego,zoom=0.03,ax=ax1) #imscatter([ego.x], [ego.y], image_path_ego, zoom=0.03, ax=ax2) #ax2 = plt.step for lane in range(1, self.n_lanes + 1): ax1.axhline((lane - 1) * self.road_width + self.road_width * 0.5, color="g", linestyle="-", linewidth=1) ax2.axhline((lane - 1) * self.road_width + self.road_width * 0.5, color="g", linestyle="-", linewidth=1) ax1.axvline(ego.x - self.x_view, color="b", linestyle="-", linewidth=1) ax1.axvline(ego.x + self.x_view, color="b", linestyle="-", linewidth=1) x_cars = [] y_cars = [] for n in range(1, self.n_cars + 1): vehicle = self.vehicle_list[n] ax1.plot([vehicle.x], [vehicle.y], color='b', marker='x') ax2.plot([vehicle.x], [vehicle.y], color='b', marker='x') x_cars.append(vehicle.x) y_cars.append(vehicle.y) #### First picture #### #imscatter(x_cars, y_cars, image_path_cars, zoom=0.03, ax=ax1) ax1.grid() ax1.set_ylim( [1, (lane - 1) * self.road_width + self.road_width * 0.5 + 1]) ax1.set_xlim([0, 2500]) ax1.set_title("Global Map") ax1.set_ylabel("Y-Position in [m]") ax1.set_xlabel("X-Position in [m]") #imscatter([ego.x], [ego.y], image_path_ego, zoom=0.03, ax=ax1) #### Second Picture ### #ax2.set_ylim([0,(lane-1)*self.road_width + self.road_width*0.5+2]) imscatter(x_cars, y_cars, image_path_cars, zoom=0.05, ax=ax2) imscatter([ego.x], [ego.y], image_path_ego, zoom=0.05, ax=ax2) ax2.set_ylim( [0, (lane - 1) * self.road_width + self.road_width * 0.5 + 2]) ax2.set_xlim([ego.x - self.x_view, ego.x + self.x_view]) ax2.text( ego.x - 60, ego.y, "Ego-velocity:" + str(round(ego.v, 2)) + "\n" + "Distance: " + str(round(self.dist_to_front, 2)) + "\n" + "Timestep: " + str(self.timestep)) ax2.set_title("Local Map") ax2.set_ylabel("Y-position in [m]") ax2.set_xlabel("X-position in [m]") plt.tight_layout() #img = plt.imread("images/road_2.jpg") #ax2.imshow(img) # Show plt.tight_layout() plt.show(block=False) plt.pause(self.dt) plt.clf()
def thresh(): global previous_unique, only, included, excluded, gits try: print('') print('previous unique list') print(previous_unique) print('') except: pass global_lists() seeds = test_seeds() # INCLUDE and EXCLUDE custom nodes if not INCLUDE: included = [] if not EXCLUDE: excluded = [] # gather list of nodes from github blockPrint() begin = time.time() utc_offset = (datetime.fromtimestamp(begin) - datetime.utcfromtimestamp(begin)).total_seconds() print('=====================================') print(('found %s nodes stored in script' % len(included))) urls = [] # scrape from github git = 'https://raw.githubusercontent.com' # my ISP is currently blocking github so... git = 'https://www.textise.net/showText.aspx?strURL=https%253A//raw.githubusercontent.com' # Bitshares Master url = git + '/bitshares/bitshares-ui/master/app/api/apiConfig.js' urls.append(url) if MASTER: gits = [] else: for g in gits: url = git + g urls.append(url) del gits # INCLUDE manually entered sites for Bitshares nodes validated = [] + included if UNIVERSE: validated = universe print('Testing the known universe...') else: if not ONLY: if MASTER: print('searching github Bitshares UI master for nodes...') else: print('scraping github for Bitshares nodes...') for u in urls: attempts = 3 while attempts > 0: try: raw = requests.get(u).text v = validate(parse(clean(raw))) del raw u = u.replace(git, '') u = "/".join(u.split("/", 3)[:3]) print(('found %s nodes at %s' % (len(v), u))) validated += v attempts = 0 except: print(('failed to connect to %s' % u)) attempts -= 1 pass # remove known bad nodes from test if len(excluded): excluded = sorted(excluded) print(('remove %s known bad nodes' % len(excluded))) validated = [i for i in validated if i not in excluded] if ONLY and len(only): validated = only if not TESTNET: print('skipping known testnet nodes') validated = [i for i in validated if 'test' not in i] # final sanitization validated = sorted(list(set(validate(parse(clean(validated)))))) # test triplicate; add /ws and /wss suffixes to all validated websockets no_suffix = validated validated = suffix(validated) validated = validated[:PINGS] # attempt to contact each websocket print('=====================================') print(('found %s total nodes' % len(no_suffix))) print('=====================================') print(no_suffix) pinging = min(PINGS, len(validated)) if pinging: print('=====================================') enablePrint() print(('%s pinging %s nodes; TIMEOUT %s sec; est %.1f minutes' % (time.ctime(), pinging, TIMEOUT, TIMEOUT * len(validated) / 120.0))) blockPrint() print('=====================================') pinged, timed, down = [], [], [] stale, expired, testnet = [], [], [] i = 0 for n in validated: if len(pinged) < pinging: i += 1 # use multiprocessing module to enforce TIMEOUT num = Value('d', 999999) arr = Array('i', list(range(0))) p = Process(target=ping, args=(n, num, arr)) p.start() p.join(TIMEOUT) if p.is_alive() or (num.value > TIMEOUT): p.terminate() p.join() if num.value == 111111: # head block is stale stale.append(n) elif num.value == 222222: # connect failed down.append(n) elif num.value == 333333: # connect failed testnet.append(n) elif num.value == 999999: # TIMEOUT reached expired.append(n) else: pinged.append(n) # connect success timed.append(num.value) # connect success time print(('ping:', ('%.2f' % num.value), n)) # sort websockets by latency pinged = [x for _, x in sorted(zip(timed, pinged))] timed = sorted(timed) unknown = sorted( list( set(validated).difference(pinged + down + stale + expired + testnet))) unique = [] speed = [] geo = [] for i in range(len(pinged)): geolocate = 'http://ip-api.com/json/' if pinged[i].strip('/ws') not in [j.strip('/ws') for j in unique]: unique.append(pinged[i]) speed.append((pinged[i], int(timed[i] * 1000) / 1000.0)) time.sleep(1) if IPAPI: print('geolocating...') ip = (validate( [pinged[i]])[0])[6:] # strip wws://, /wss, /ws, and / ip = ip.split(":")[0] ip = ip.split("/")[0] # ip-api.com has trouble with these # parsed manually at ipinfo.info instead if (ip == 'freedom.bts123.cc'): ip = '121.42.8.104' if (ip == 'ws.gdex.top'): ip = '106.15.82.97' if (ip == 'bitshares.dacplay.org'): ip = '120.55.181.181' if (ip == 'crazybit.online'): ip = '39.108.95.236' if (ip == 'citadel.li'): ip = '37.228.129.75' if (ip == 'bts.liuye.tech'): ip = '27.195.68.51' geolocate += ip print(geolocate) req = requests.get(geolocate, headers={}) ret = json_loads(req.text) entriesToRemove = ('isp', 'regionName', 'org', 'countryCode', 'timezone', 'region', 'as', 'status', 'zip') for k in entriesToRemove: ret.pop(k, None) ret['ip'] = ret.pop('query') print(ret) geo.append((pinged[i], ret)) speeds = [] for i in range(len(speed)): speeds.append(speed[i][1]) mean_speed = sum(speeds) / len(speeds) # report outcome print('') print((len(pinged), 'of', len(validated), 'nodes are active with latency less than', TIMEOUT)) print('') print(('fastest node', pinged[0], 'with latency', ('%.2f' % timed[0]))) print('mean latency', mean_speed) if len(excluded): for i in range(len(excluded)): print(((i + 1), 'EXCLUDED', excluded[i])) if len(unknown): for i in range(len(unknown)): print(((i + 1), 'UNTESTED', unknown[i])) if len(testnet): for i in range(len(testnet)): print(((i + 1), 'TESTNET', testnet[i])) if len(expired): for i in range(len(expired)): print(((i + 1), 'TIMEOUT', expired[i])) if len(stale): for i in range(len(stale)): print(((i + 1), 'STALE', stale[i])) if len(down): for i in range(len(down)): print(((i + 1), 'DOWN', down[i])) if len(pinged): for i in range(len(pinged)): print(((i + 1), 'GOOD PING', '%.2f' % timed[i], pinged[i])) if len(unique): for i in range(len(unique)): print(((i + 1), 'UNIQUE:', unique[i])) print('UNIQUE LIST:') print(unique) del excluded del unknown del testnet del expired del stale del down del pinged print('') enablePrint() elapsed = time.time() - begin print('elapsed:', ('%.1f' % elapsed), 'fastest:', ('%.3f' % timed[0]), unique[0]) if WRITE: race_write(doc='nodes.txt', text=str(unique)) del timed if PLOT: try: plt.close() except: pass print('plotting...') def download_img(imageUrl, localFileName): while 1: r = requests.get(imageUrl, stream=True) if r.status_code == 200: with open(localFileName, 'wb') as f: for chunk in r.iter_content(1024): f.write(chunk) break path = os.path.dirname(os.path.abspath(__file__)) im = '/basemap.png' path = path + im print(path) try: basemap = cbook.get_sample_data(path) except: url = 'https://i.imgur.com/yIVogZH.png' download_img(url, 'basemap.png') basemap = cbook.get_sample_data(path) img = plt.imread(basemap) fig, ax = plt.subplots(figsize=(12, 24)) plt.xticks([]) plt.yticks([]) ax.imshow(img, extent=[-180, 180, -90, 90]) fig.tight_layout() plt.pause(0.1) xs = [] ys = [] for i in range(len(geo)): try: x = float(geo[i][1]['lon']) y = float(geo[i][1]['lat']) xs.append(x) ys.append(y) l = geo[i][0] try: s = float(speed[i][1]) / mean_speed m = 20 / s except: m = 10 pass print(x, y, l, s, m) plt.plot([x], [y], 'mo', markersize=m, alpha=0.25) except: print('skipping', geo[i]) pass plt.plot(xs, ys, 'wo', markersize=4, alpha=0.25) del x del y del xs del ys # PLOT SEED NODES if SEEDS: xs = [] ys = [] for i in range(len(seeds)): if float(seeds[i][1]) > 0: try: x = float(seeds[i][2]['lon']) y = float(seeds[i][2]['lat']) xs.append(x) ys.append(y) except: print('skipping', seeds[i]) pass plt.plot(xs, ys, 'yo', markersize=4, alpha=1.0) utc = str(time.strftime("%a, %d %b %Y %H:%M:%S", time.gmtime())) + ' UTC' plt.text(0, -60, utc, alpha=0.5, color='w', size=15) location = '/home/oracle/extinction-event/EV/nodemap.png' plt.savefig(location, dpi=100, bbox_inches='tight', pad_inches=0) # SAVE HISTORY if 1: location = '/home/oracle/extinction-event/EV/HISTORY/nodemap_' + \ str(int(time.time())) + '.png' plt.savefig(location, dpi=100, bbox_inches='tight', pad_inches=0) if UPLOAD: image_url = '' try: url = 'https://vgy.me/upload' files = {'file': open('nodemap.png', 'rb')} r = requests.post(url, files=files) del files image_url = json_loads(r.text)['image'] except: print('vgy failed') pass print(image_url) if JSONBIN: jsonbin(no_suffix, unique, speed, geo, urls, image_url, seeds) del no_suffix del speed del geo del urls del image_url del seeds try: print('') print('live now, not live last round') print([i for i in unique if i not in previous_unique]) print('live last round, not live now') print([i for i in previous_unique if i not in unique]) except: pass previous_unique = unique[:] del unique
# return x_,y_intersect def line_segment((x1, y1), (x2, y2)): assert x1 < x2 m = (y2 - y1) / float(x2 - x1) b = y1 - m * x1 for x_i in range(int(x1), int(x2)): y_i = m * x_i + b yield (x_i, y_i) raise StopIteration() image_file = cbook.get_sample_data( "/home/greg/Databases/old_weather/images/Bear-AG-29-1939-0173.JPG") image = plt.imread(image_file) # fig = plt.figure() # axes = fig.add_subplot(1, 1, 1) # im = axes.imshow(image) # for y_l in horizontal_lines: # for x in vertical_lines: # x_intersect,y_intersect = intersection((y_l,(start_x,end_x)),x) # plt.plot(x_intersect,y_intersect,"o",color="red") # # plt.show() ref1 = [218, 219, 213]
def plot_prediction(background_filename, traj, goal_probabilities, predicted_trajs, intervention_samples, solutions, robot_states, robot_plans, object_states, goals, env, trial): matplotlib.use("Agg") fig = plt.figure() ax = fig.gca() ax.set_xlabel('x (m)') ax.set_ylabel('y (m)') ax.set_xlim(1.5, 7) ax.set_ylim(3, 7) # ax.set_title('Intention Prediction') dt = 0.5 n = len(traj) time_pred = np.linspace(0, dt * n, n) datafile = cbook.get_sample_data(background_filename, asfileobj=False) im = image.imread(datafile) ax.imshow(im, aspect='auto', extent=(0, 10, 0, 10), alpha=0.5, zorder=-1) x = [traj[i][0][1] for i in range(len(traj))] y = [traj[i][0][0] for i in range(len(traj))] x_r = [robot_states[i].point.y for i in range(len(robot_states))] y_r = [robot_states[i].point.x for i in range(len(robot_states))] x_plan = [] y_plan = [] for j in range(len(robot_plans)): x_plan.append( [robot_plans[j][i][1] for i in range(len(robot_plans[j]))]) y_plan.append( [robot_plans[j][i][0] for i in range(len(robot_plans[j]))]) data = [] n_samples = [] for j in range(len(intervention_samples)): if not n_samples: n_samples.append(len(intervention_samples[j])) else: n_samples.append(len(intervention_samples[j]) + n_samples[j - 1]) samples = [] for k in range(len(intervention_samples[j])): points = [[ intervention_samples[j][k][i][1], intervention_samples[j][k][i][0] ] for i in range(len(intervention_samples[j][k]))] samples.append(points) data.append(samples) goal_markers = [] predicted_traj_lines = [] for goal in goals: center = env.sample_zones[goal].centroid goal_markers.append( ax.scatter(center.y, center.x, s=120, marker="X", color='darkmagenta', alpha=0.1)) predicted_traj_line, = ax.plot([], [], 'b--', lw=3, alpha=0.1) predicted_traj_lines.append(predicted_traj_line) # sampled_interventions = ax.scatter([],[], s= 50, marker=".", color='blue', alpha = 0.5) # robot_marker = ax.scatter([],[], s= 150, marker="o", color='green', alpha = 1) patient_marker = ax.scatter([], [], s=100, marker="D", color='k', alpha=1) # solution_marker = ax.scatter([],[], s= 100, marker="o", facecolors='none', edgecolors='r', alpha = 1 , linewidth=2) # corners = find_corners(object_states[0].point.y, object_states[0].point.x, object_states[0].point.z, 0.2, 0.3) # Walker = plt.Polygon(corners, closed=None, fill=None, edgecolor='k', alpha = 1, linewidth=2) # ax.add_artist(Walker) traj_line, = ax.plot([], [], lw=3, color='b') robot_traj_line, = ax.plot([], [], lw=3, color='g') plan_line, = ax.plot([], [], 'g--', lw=3, alpha=0.5) def animate(k): # lb = 0 # for k in range(len(n_samples)): # if i>=lb and i<n_samples[k]: # break # else: # lb = n_samples[k] traj_line.set_data(x[0:k + 1], y[0:k + 1]) # robot_traj_line.set_data(x_r[0:k+1], y_r[0:k+1]) # plan_line.set_data(x_plan[k], y_plan[k]) # sampled_interventions.set_offsets(data[k][i-lb]) # robot_marker.set_offsets([robot_states[k].point.y, robot_states[k].point.x]) patient_marker.set_offsets([x[k], y[k]]) # solution_marker.set_offsets([solutions[k][1], solutions[k][0]]) # corners = find_corners(object_states[k].point.y, object_states[k].point.x, object_states[k].point.z, 0.2, 0.3) # Walker.set_xy(corners) for j in range(len(goals)): goal_markers[j].set_alpha(0.1 + 0.9 * goal_probabilities[k][j]) x_p = [ predicted_trajs[k][j][l][1] for l in range(len(predicted_trajs[k][j]) - 1) ] y_p = [ predicted_trajs[k][j][l][0] for l in range(len(predicted_trajs[k][j]) - 1) ] predicted_traj_lines[j].set_data(x_p, y_p) if goal_probabilities[k][j] < 0.1: # al = 0 al = 0.1 + 0.5 * goal_probabilities[k][j] else: al = 0.1 + 0.5 * goal_probabilities[k][j] predicted_traj_lines[j].set_alpha(al) return predicted_traj_lines + [traj_line] anim = FuncAnimation(fig, animate, frames=len(solutions), interval=100) plt.show() anim.save('results/test-{}.mp4'.format(trial), writer='ffmpeg', fps=1)
def plot_energy_spectrum(filedir=None, filetype='bulk', pop='proton', start=1, stop=20, outputdir=None, emin=None, emax=None, enum=None, plotE=None, colormap=None, title=None, draw=None, usesci=1, run=None, wmark=None, notre=None, thick=1.0, cbtitle=None, lin=None, fmin=None, fmax=None, cellcoordplot=None, cellidplot=None, numproc=8 ): ''' Plots a time/energy spectrum during time interval (colour plot). :kword filedir: Directory where files are located :kword filetype: Type of file to be used [default = 'bulk'] :kword start: File number (step) for starting the plot :kword stop: File number (step) for ending the plot :kword outputdir: Path to directory where output files are created (default: $HOME/Plots/) If directory does not exist, it will be created. If the string does not end in a forward slash, the final parti will be used as a perfix for the files. :kword emin,emax,enum: min and max values (edges) for energy levels [keV] and number of energy bins :kword plotE: Plots an overlaid line plot of the plasma energy :kword colormap: colour scale for plot, use e.g. jet, viridis, plasma, inferno, magma, nipy_spectral, RdBu :kword title: string to use as title instead of map name :kword draw: Draw image on-screen instead of saving to file (requires x-windowing) :kword usesci: Use scientific notation for colorbar ticks? (default: 1) :kword run: run identifier, used for some default vmin,vmax values and for constructing output filename :kword wmark: If set to non-zero, will plot a Vlasiator watermark in the top left corner. :kword cbtitle: string to use as colour bar title instead of map name :kword notre: flag to use metres (if ==1) or kilometres as axis unit :kword thick: line and axis thickness, default=1.0 :kword lin: flag for using linear colour scaling instead of log :kword fmin,fmax: min and max values for colour scale and colour bar of the PSD. :kword cellcoordplot: Coordinates of cell to be plottedd (3-D array) :kword cellidplot: cellID be plotted (list) :kword numproc: Number of processes for parallelisation (default: 8) :returns: Outputs an image to a file or to the screen. # Example usage: import pytools as pt pt.plot.plot_energy_spectrum(filedir='./', start=0, stop=100, emin=1, emax=50, enum=16, cellidplot=[300100]) ''' global filedir_global, filetype_global, cellid_global, pop_global global emin_global, emax_global, enum_global, plotE_global # TODO do not use global variables, check that variables are valid filedir_global=filedir filetype_global=filetype emin_global=emin emax_global=emax enum_global=enum if not plotE == None: plotE_global = True else: plotE_global = False # Verify the location of this watermark image watermarkimage=os.path.join(os.path.dirname(__file__), 'logo_color.png') # watermarkimage=os.path.expandvars('$HOME/appl_taito/analysator/pyPlot/logo_color.png') # watermarkimage='/homeappl/home/marbat/appl_taito/analysator/logo_color.png' if outputdir==None: outputdir=os.path.expandvars('$HOME/Plots/') if not os.path.exists(outputdir): os.makedirs(outputdir) # Input file list if ((filedir!=None) and (start!=None) and (stop!=None)): filelist = [] for step in range(start,stop+1): filename = filedir+filetype+'.'+str(step).rjust(7,'0')+'.vlsv' filelist.append(filename) else: print("ERROR: needs a bulk file directory and start/stop steps") return # Scientific notation for colorbar ticks? if usesci==None: usesci=1 if colormap==None: #colormap="YlOrRd" colormap="hot_desaturated" cmapuse=matplotlib.cm.get_cmap(name=colormap) fontsize=8 # Most text fontsize2=10 # Time title fontsize3=5 # Colour bar ticks # TODO check if files have VDFs # Stop and start times f=pt.vlsvfile.VlsvReader(filelist[-1]) tstop=None tstop=f.read_parameter("time") if tstop==None: tstop=f.read_parameter("t") if tstop==None: print("Unknown time format encountered for stop file") return f=pt.vlsvfile.VlsvReader(filelist[0]) tstart=None tstart=f.read_parameter("time") if tstart==None: tstart=f.read_parameter("t") if tstart==None: print("Unknown time format encountered for start file") return # Plot title if title==None: plot_title = '' else: plot_title = title # stepstr, used for file name stepstr = '_t'+str(np.int(tstart))+'s' # If run name isn't given, just put "plot" in the output file name if run==None: run='plot' # Output file name savefigname = outputdir+run+"_ener_time_spec"+stepstr+"_"+str(cellidplot[0])+".png" # If population isn't defined i.e. defaults to protons, check if # instead should use old version "avgs" if pop=="proton": if not f.check_population(pop): if f.check_population("avgs"): pop="avgs" print("Auto-switched to population avgs") else: print("Unable to detect population "+pop+" in .vlsv file!") sys.exit() else: if not f.check_population(pop): print("Unable to detect population "+pop+" in .vlsv file!") sys.exit() pop_global = pop #if fmin!=None and fmax!=None: # TODO how to handle fmin and fmax # Lin or log colour scaling, defaults to log if lin==None: norm = LogNorm(vmin=fmin,vmax=fmax) ticks = LogLocator(base=10,subs=range(10)) # where to show labels else: # Linear levels = MaxNLocator(nbins=255).tick_values(fmin,fmax) norm = BoundaryNorm(levels, ncolors=cmapuse.N, clip=True) ticks = np.linspace(fmin,fmax,num=7) # Select plotting back-end based on on-screen plotting or direct to file without requiring x-windowing if draw!=None: plt.switch_backend('TkAgg') else: plt.switch_backend('Agg') # Checking if CellID exists if cellidplot==None and cellcoordplot==None : print("ERROR: No cell ID or coordinate given as input") return #TODO find cellid from coordinates cellid_global = cellidplot datamap = np.array([]) time_ar = np.array([]) # Parallel construction of the spectrum if __name__ == 'plot_energy': pool = Pool(numproc) return_array = pool.map(make_timemap, range(start,stop+1)) else: print("Problem with parallelization") # Creating datamap for j in return_array: time_ar = np.append(time_ar,j[0]) datamap = np.append(datamap,j[1]) energy = return_array[0][2] #Serial construction of spectrum (for debugging) #for step in range(start,stop+1): # func_return = make_timemap(step) # time_ar = np.append(time_ar,func_return[0]) # datamap = np.append(datamap,func_return[1]) #energy = func_return[2] # Reshape data to an ordered 2D array that can be plotted if plotE_global == True: sizes=[time_ar.size,energy.size+1] else: sizes=[time_ar.size,energy.size] if np.ndim(datamap) != 2: datamap = datamap.reshape([sizes[0],sizes[1]]) datamap = np.transpose(datamap) # Select figure size ratio=1. #TODO calculate this figsize = [4.0,3.15] # Create 300 dpi image of suitable size fig = plt.figure(figsize=figsize,dpi=300) # Generates the mesh to map the data to. # Note, datamap is still of shape [ysize,xsize] (?) [XmeshXY,YmeshXY] = scipy.meshgrid(time_ar,energy) if plotE_global == True: fig1 = plt.pcolormesh(XmeshXY,YmeshXY,datamap[:-1,:], cmap=colormap,norm=norm) plt.plot(time_ar,datamap[-1,:], '--w', linewidth=2) else: fig1 = plt.pcolormesh(XmeshXY,YmeshXY,datamap, cmap=colormap,norm=norm) ax1 = plt.gca() ax1.set_yscale("log") # Title and plot limits ax1.set_title(plot_title,fontsize=fontsize2,fontweight='bold') plt.xlim([time_ar[0],time_ar[-1]]) plt.ylim([emin,emax]) plt.xlabel('Time [s]',fontsize=fontsize,weight='black') plt.ylabel('E [keV]',fontsize=fontsize,weight='black') plt.xticks(fontsize=fontsize,fontweight='black') plt.yticks(fontsize=fontsize,fontweight='black') for axis in ['top','bottom','left','right']: ax1.spines[axis].set_linewidth(thick) ax1.xaxis.set_tick_params(width=thick,length=3) ax1.yaxis.set_tick_params(width=thick,length=3) # Limit ticks, slightly according to ratio #ax1.xaxis.set_major_locator(plt.MaxNLocator(int(7/np.sqrt(ratio)))) #ax1.yaxis.set_major_locator(plt.MaxNLocator(int(7*np.sqrt(ratio)))) # Colourbar title cbtitle = 'Flux\n [1/cm$^2$/s/sr/eV]' cbtitle = 'PSD [s$^3$/m$^6$]' # TODO: make this flexible plt.text(1.0, 1.04, cbtitle, fontsize=fontsize3+1,weight='black', transform=ax1.transAxes) # Witchcraft used to place colourbar divider = make_axes_locatable(ax1) cax = divider.append_axes("right", size="5%", pad=0.1) # First draw colorbar if usesci==0: cb = plt.colorbar(fig1,ticks=ticks,cax=cax, drawedges=False) else: cb = plt.colorbar(fig1,ticks=ticks,format=mtick.FuncFormatter(fmt),cax=cax, drawedges=False) cb.ax.tick_params(labelsize=fontsize3)#,width=1.5,length=3) cb.outline.set_linewidth(thick) # if too many subticks: if lin==None and usesci!=0: # Note: if usesci==0, only tick labels at powers of 10 are shown anyway. # For non-square pictures, adjust tick count nlabels = len(cb.ax.yaxis.get_ticklabels()) / ratio valids = ['1','2','3','4','5','6','7','8','9'] if nlabels > 10: valids = ['1','2','3','4','5','6','8'] if nlabels > 19: valids = ['1','2','5'] if nlabels > 28: valids = ['1'] # for label in cb.ax.yaxis.get_ticklabels()[::labelincrement]: for label in cb.ax.yaxis.get_ticklabels(): # labels will be in format $x.0\times10^{y}$ if not label.get_text()[1] in valids: label.set_visible(False) # Grid #plt.grid(color='grey',linestyle='-') # set axis exponent offset font sizes ax1.yaxis.offsetText.set_fontsize(fontsize) ax1.xaxis.offsetText.set_fontsize(fontsize) # Add Vlasiator watermark if wmark!=None: wm = plt.imread(get_sample_data(watermarkimage)) newax = fig.add_axes([0.01, 0.90, 0.3, 0.08], anchor='NW', zorder=-1) newax.imshow(wm) newax.axis('off') # adjust layout plt.tight_layout(pad=1.5) # Save output or draw on-screen if draw==None: print(savefigname+"\n") plt.savefig(savefigname,dpi=300) else: plt.draw() plt.show()
""" make a scatter plot with varying color and size arguments """ import matplotlib import numpy as np import matplotlib.pyplot as plt import matplotlib.mlab as mlab import matplotlib.cbook as cbook # load a numpy record array from yahoo csv data with fields date, # open, close, volume, adj_close from the mpl-data/example directory. # The record array stores python datetime.date as an object array in # the date column datafile = cbook.get_sample_data('goog.npy') r = np.load(datafile).view(np.recarray) r = r[-250:] # get the most recent 250 trading days delta1 = np.diff(r.adj_close) / r.adj_close[:-1] # size in points ^2 volume = (15 * r.volume[:-2] / r.volume[0])**2 close = 0.003 * r.close[:-2] / 0.003 * r.open[:-2] fig = plt.figure() ax = fig.add_subplot(111) ax.scatter(delta1[:-1], delta1[1:], c=close, s=volume, alpha=0.75) #ticks = arange(-0.06, 0.061, 0.02) #xticks(ticks) #yticks(ticks)
from __future__ import print_function import numpy as np import matplotlib.mlab as mlab import matplotlib.cbook as cbook datafile = cbook.get_sample_data('msft.csv', asfileobj=False) print('loading', datafile) r = mlab.csv2rec(datafile) r.sort() r1 = r[-10:] # Create a new array r2 = np.empty(12, dtype=[('date', '|O4'), ('high', float), ('marker', float)]) r2 = r2.view(np.recarray) r2.date = r.date[-17:-5] r2.high = r.high[-17:-5] r2.marker = np.arange(12) print("r1:") print(mlab.rec2txt(r1)) print("r2:") print(mlab.rec2txt(r2)) defaults = {'marker': -1, 'close': np.NaN, 'low': -4444.} for s in ('inner', 'outer', 'leftouter'): rec = mlab.rec_join(['date', 'high'], r1, r2, jointype=s,
def get_demo_image(): z = cbook.get_sample_data("axes_grid/bivariate_normal.npy", np_load=True) # z is a numpy array of 15x15 return z, (-3, 4, -4, 3)
def annotated_plot(self, key, zoom=0.2, rep=0, pad=0, xybox=(0, 50), max_hight=None, fd=None, figposx=None, figposy=None, xlim=None, ylim=None, ylabel=None, n_datapoints=None, add_points=False): pth = self._curr_path + "imgs/" if not os.path.exists(pth): raise VIS_EXCEPTION("No image directory found in path " + pth) imgs = os.listdir(pth) imgs.sort() data = self._curr_data[key][rep] l = len(data) if len(imgs) != l: raise VIS_EXCEPTION( "Number of images must match the number of data points") x = None if n_datapoints is None: x = range(len(data)) else: if n_datapoints < len(data): data = data[:n_datapoints] x = range(n_datapoints) if not fd is None: data = fd(data) #fig, ax = plt.subplots() _, ax = plt.subplots() ax.plot(x, data, linewidth=2.0) if add_points: ax.plot(x, data, "k*", mew=0.5, ms=10) if figposy is None: figposy = data if figposx is None: figposx = x i = 0 for pos in zip(figposx, figposy): imgpth = pth + imgs[i] i += 1 fn = get_sample_data(imgpth, asfileobj=False) arr_img = plt.imread(fn, format='png') im = OffsetImage(arr_img, zoom=zoom) im.image.axes = ax ab = AnnotationBbox( im, pos, xybox=xybox, xycoords='axes fraction', boxcoords="offset points", #pad=pad, arrowprops=dict(arrowstyle="<-")) ax.add_artist(ab) mi = np.min(data) ma = np.max(data) r = ma - mi if not xlim is None: ax.set_xlim(xlim[0], xlim[1]) if not ylim is None: ax.set_ylim(ylim[0], ylim[1]) if ylabel is None: plt.ylabel(key, fontsize=15) else: plt.ylabel(ylabel, fontsize=15) labs = range(len(data)) labs = list(map(lambda x: str(x), labs)) ax.set_xticklabels(labs) plt.xlabel("disturbance level", fontsize=15) plt.xticks(x) plt.show()
""" Demo of image that's been clipped by a circular patch. """ import matplotlib.pyplot as plt import matplotlib.patches as patches import matplotlib.cbook as cbook image_file = cbook.get_sample_data('grace_hopper.png') image = plt.imread(image_file) fig, ax = plt.subplots() im = ax.imshow(image) patch = patches.Circle((260, 200), radius=200, transform=ax.transData) im.set_clip_path(patch) plt.axis('off') plt.show()
# # but this doesn't help center the label between ticks. One solution # is to "face it". Use the minor ticks to place a tick centered # between the major ticks. Here is an example that labels the months, # centered between the ticks import datetime import numpy as np import matplotlib import matplotlib.cbook as cbook import matplotlib.dates as dates import matplotlib.ticker as ticker import matplotlib.pyplot as plt # load some financial data; apple's stock price fh = cbook.get_sample_data('aapl.npy') r = np.load(fh) fh.close() r = r[-250:] # get the last 250 days fig = plt.figure() ax = fig.add_subplot(111) ax.plot(r.date, r.adj_close) ax.xaxis.set_major_locator(dates.MonthLocator()) ax.xaxis.set_minor_locator(dates.MonthLocator(bymonthday=15)) ax.xaxis.set_major_formatter(ticker.NullFormatter()) ax.xaxis.set_minor_formatter(dates.DateFormatter('%b')) for tick in ax.xaxis.get_minor_ticks():