def example1(): import sys import scipy as sp import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt import pyfits #Path to fits file to be imported data1 = "/Users/destry/Documents/Github/truffles_examples/GALFA_HI_RA+DEC_092.00+10.35_W.fits" #Read out basic info pyfits.info(data1) #Load file header into keys header = pyfits.getheader(data1) header.keys() #Load actual data data_cube = pyfits.getdata(data1, 0) print 'Type: ', type(data_cube) print 'Shape:', data_cube.shape #I'm just going to look at a random slice slice1 = data_cube[45, :, :] #Show the slice plt.imshow(slice1) plt.winter() plt.show()
def scatterd(a): clrs = a.nlab().flatten() sz = a.data.shape if (sz[1] > 1): plt.scatter(a.data[:, 0], a.data[:, 1], c=clrs) ylab = a.featlab[1] else: plt.scatter(a.data[:, 0], numpy.zeros((sz[0], 1)), c=clrs) ylab = '' plt.title(a.name) plt.xlabel('Feature ' + str(a.featlab[0])) plt.ylabel('Feature ' + str(ylab)) plt.winter()
def scatter3d(a): clrs = a.nlab().flatten() sz = a.data.shape if (sz[1]>2): ax = plt.axes(projection='3d') ax.scatter3D(a.data[:,0],a.data[:,1],a.data[:,2],c=clrs) ylab = a.featlab[1] zlab = a.featlab[2] else: raise ValueError('Please supply at least 3D data.') plt.title(a.name) ax.set_xlabel('Feature '+str(a.featlab[0])) ax.set_ylabel('Feature '+str(ylab)) ax.set_zlabel('Feature '+str(zlab)) plt.winter()
def main(): #Get the raster from the disk rast_data, x_cellsize, y_cellsize = get_array("./data/elevation.tif") slope = generic_filter(rast_data, calc_slope, size=3, extra_arguments=(x_cellsize, y_cellsize)) plt.imshow(ma.masked_equal(slope, -9999), cmap=plt.winter(), origin="lower") plt.show()
def Cp_plot(): """範囲指定""" plt.xlim(-3.0, 3.0) plt.ylim(-3.0, 3.0) """翼を描く(翼はξ、ηの配列のr=0の部分)""" plt.plot(xi[:, 0], eta[:, 0]) """等圧線を描く""" plt.contour(xi[:, :], eta[:, :], Cp0[:, :], locator=plt.MultipleLocator(0.1)) plt.winter() plt.suptitle = 'Kutta' plt.colorbar() plt.show()
def scatterr(a): sz = a.data.shape if (sz[1]==1): plt.scatter(a.data[:,0],a.targets) plt.title(a.name) plt.xlabel('Feature '+str(a.featlab[0])) plt.ylabel('Target') plt.winter() elif (sz[1]==2): ax = plt.axes(projection='3d') ax.scatter3D(a.data[:,0],a.data[:,1],a.targets) ylab = a.featlab[1] plt.title(a.name) ax.set_xlabel('Feature '+str(a.featlab[0])) ax.set_ylabel('Feature '+str(ylab)) ax.set_zlabel('Targets') else: raise ValueError('Please supply at least 2D data.')
def Cp_plot(): """範囲指定""" plt.xlim(-3.0, 3.0) plt.ylim(-3.0, 3.0) """翼を描く(翼はξ、ηの配列のr=0の部分)""" plt.plot(xi[:, 0], eta[:, 0]) """等圧線を描く""" plt.contour(xi[:, :], eta[:, :], Cp0[:, :], locator=plt.MultipleLocator(0.1)) plt.winter() plt.title('Isobar') plt.xlabel("ξ") plt.ylabel("η") cbar = plt.colorbar() cbar.set_label("Cp") plt.show()
def plot4DGraph(clusters): fig = plt.figure() ax = fig.add_subplot(111, projection='3d') iter = 0 for cluster in clusters: u_val = [obj[0] for obj in clusters[cluster]] v_val = [obj[1] for obj in clusters[cluster]] w_val = [obj[2] for obj in clusters[cluster]] x_val = [obj[3] for obj in clusters[cluster]] if iter == 0: img1 = ax.scatter(u_val, v_val, w_val, s=75, c=x_val, cmap=plt.winter(), label='cluster1') cbar = fig.colorbar(img1, shrink=0.5, aspect=10) elif iter == 1: img2 = ax.scatter(u_val, v_val, w_val, s=75, c=x_val, cmap=plt.spring(), label='cluster2') cbar = fig.colorbar(img2, shrink=0.5, aspect=10) else: img3 = ax.scatter(u_val, v_val, w_val, s=75, c=x_val, cmap=plt.gray(), label='cluster3') cbar = fig.colorbar(img3, shrink=0.5, aspect=10) iter += 1 cbar.ax.get_yaxis().labelpad = 15 cbar.ax.set_ylabel('petal width in cm') cbar.ax.get_xaxis().labelpad = 15 cbar.ax.set_xlabel('cluster' + str(iter)) ax.set_xlabel('sepal length in cm', rotation=150) ax.set_ylabel('sepal width in cm') ax.set_zlabel(r'petal length in cm', rotation=60) plt.title("4D representation of clustering solution") plt.show()
def play_plot(days=365): plays = link.get_plays(days) by_game = {} for p in plays: if p['name'] in by_game: by_game[p['name']].extend([std(p['date'])] * p['plays']) else: by_game[p['name']] = [std(p['date'])] fig, ax = plt.subplots() plt.title( f"Game Plays, Past {'Year' if -5 <= days - 365 <= 5 else f'{days} Day'+('s' if days != 1 else '')} [Size ∝ Plays]" ) plt.winter() plt.xticks(rotation=45) plt.yticks(weight='bold') plt.xlabel("Date") colors = ['red', 'orange', '#FADA5e', 'green', 'blue', 'indigo', 'violet'] for i, [game, dates] in enumerate(by_game.items()): date_count = Counter(dates) for date, count in sorted(list(date_count.items()), key=lambda c: c[1])[::-1]: ax.plot_date( date, game, ms=5 + count, alpha=1 if count == 1 else max(1 / (0.8 * count), 0.5), color=colors[i % len(colors)]) for i, ytick in enumerate(ax.get_yticklabels()): ytick.set_color(colors[i % len(colors)]) ax.set_xlim(right=datetime.today()) gcf = plt.gcf() gcf.autofmt_xdate() plt.show()
def scatterr(a): plt.scatter(a.data[:, 0], a.targets) plt.title(a.name) plt.xlabel('Feature ' + str(a.featlab[0])) plt.ylabel('Target') plt.winter()
def labelPlot(xName, yName, labelName='Part #', **kwargs): plt.ioff() cmap = plt.winter() x = np.array(oap[xName]) y = np.array(oap[yName]) c = np.array(oap.get(kwargs.get('cName', None), np.zeros(np.shape(x)))) try: d = c + 1 except: d = list(set(c)) d.sort() c = np.array(map(lambda a: d.index(a), c)) + 1 names = oap.get(labelName, 'Part #') xscale = kwargs.get('xscale', 'linear') yscale = kwargs.get('yscale', 'linear') cscale = kwargs.get('cscale', 'linear') xlim = kwargs.get('xlim', (0, np.Inf) if xscale == 'log' else (-np.Inf, np.Inf)) ylim = kwargs.get('ylim', (0, np.Inf) if yscale == 'log' else (-np.Inf, np.Inf)) clim = kwargs.get('clim', (0, np.Inf) if cscale == 'log' else (-np.Inf, np.Inf)) mask = np.array(kwargs.get('mask', np.array( [False] * np.shape(x)[0]))) | filterMask( kwargs['filter']) | (x <= xlim[0]) | (x > xlim[1]) | ( y <= ylim[0]) | (y > ylim[1]) | (c <= clim[0]) | (c > clim[1]) xm = np.ma.masked_array(x, mask) ym = np.ma.masked_array(y, mask) cm = np.ma.masked_array(c, mask) sm = np.ma.masked_array(kwargs.get('s', 17 * np.ones(np.shape(x))), mask) namesm = np.ma.masked_array(names, mask) xp = np.log10(xm) if xscale == "log" else xm yp = np.log10(ym) if yscale == "log" else ym cp = np.log10(cm) if cscale == "log" else cm fig, ax = plt.subplots(figsize=(8, 4.5), dpi=128) sc = ax.scatter(xp, yp, c=cp, s=sm, cmap=cmap, alpha=0.7) sc.set_clim(np.min(cp), np.max(cp)) cb = plt.colorbar(sc) if xscale == "log": xMinorTicks, xMinorTickLabels = logTicks(np.min(xp), np.max(xp)) ax.set_xticks(xMinorTicks) ax.set_xticklabels(xMinorTickLabels) if yscale == "log": yMinorTicks, yMinorTickLabels = logTicks(np.min(yp), np.max(yp)) ax.set_yticks(yMinorTicks) ax.set_yticklabels(yMinorTickLabels) if cscale == "log": cMinorTicks, cMinorTickLabels = logTicks(np.min(cp), np.max(cp)) cb.set_ticks(cMinorTicks) cb.set_ticklabels(cMinorTickLabels) sc.set_clim(np.min(cMinorTicks), np.max(cMinorTicks)) ax.grid(which="both") tooltipLabels = [ '<span>{label}</span>'.format(label=l) for l in namesm.compressed().ravel().tolist() ] css = "span {background-color: white; font-weight: bold;}" tooltip = mpld3.plugins.PointHTMLTooltip(sc, tooltipLabels, css=css) mpld3.plugins.connect(fig, tooltip) ret = mpld3.fig_to_html(fig, figid="figure") plt.close(fig) return ret
""" An example of processing as an n-dimensional array. """ import numpy as np from scipy import ndimage import matplotlib.pyplot as plt from glob import glob lsat = None try: import arcpy lsat = np.dstack(arcpy.RasterToNumPyArray(in_raster) for in_raster in glob("./data/lsat7_2002_*.tif")) except: lsat = np.dstack(np.mean(plt.imread(in_raster, format="TIFF"), axis=2) for in_raster in glob("./data/lsat7_2002_*.tif")) print lsat.shape median = ndimage.median_filter(lsat, size=9) print median[:, :, 5].shape plt.subplot(211) plt.imshow(lsat[:, :, 5], cmap=plt.winter(), origin="lower") plt.title("Original") plt.subplot(212) plt.imshow(median[:, :, 5], cmap=plt.winter(), origin="lower") plt.title("Filtered") plt.show()
""" An example of processing as an n-dimensional array. """ import numpy as np from scipy import ndimage import matplotlib.pyplot as plt from glob import glob lsat = None try: import arcpy lsat = np.dstack(arcpy.RasterToNumPyArray(in_raster) for in_raster in glob("./data/lsat7_2002_*.tif")) except: lsat = np.dstack( np.mean(plt.imread(in_raster, format="TIFF"), axis=2) for in_raster in glob("./data/lsat7_2002_*.tif") ) print lsat.shape median = ndimage.median_filter(lsat, size=9) print median[:, :, 5].shape plt.subplot(211) plt.imshow(lsat[:, :, 5], cmap=plt.winter(), origin="lower") plt.title("Original") plt.subplot(212) plt.imshow(median[:, :, 5], cmap=plt.winter(), origin="lower") plt.title("Filtered") plt.show()
standard_deviation = standard_deviation_t else: break if len(x) > len(x1): f, ax = plt.subplots() ax.set_title("KL-Divergence (%s)" % len(d1)) ax.set_ylabel('density') ax.set_xlabel('q_value') points = ax.scatter(x1, y1, c=d1, s=10, cmap=cmap) f.colorbar(points) plt.ylim((y_min, y_max)) plt.show() print("") cmap = plt.winter() avg_0 = np.average(d) d_l = list() d_u = list() x_l = list() x_u = list() y_l = list() y_u = list() for index in range(len(d)): if d[index] < avg_0: x_l.append(x[index]) y_l.append(y[index]) d_l.append(d[index]) elif d[index] > avg_0: x_u.append(x[index])
plons.append (sum ([float(hotel["lng"]) for hotel in hotels]) / len (hotels)) else: plons.append ((sum ([float(hotel["lng"]) for hotel in hotels]) / len (hotels))-0.05) # Special case because of the shape of this department # Calculating mean of latitudes plats.append (sum ([float(hotel["lat"]) for hotel in hotels]) / len (hotels)) # Calculating total capacity pcap.append (sum ([int(hotel[HIST_KEY]) for hotel in hotels])) # Calculating mean of rankings (in stars) pstars.append (sum ([int(hotel["classement"].split()[0]) for hotel in hotels]) / len (hotels)) # Calculating size and color of points (values between 0 and 1) plt.winter() psizes = [s / 85 for s in pcap] # Displaying map background bmap = basemap (projection = "merc", llcrnrlon = BMAP_LONMIN, llcrnrlat = BMAP_LATMIN, urcrnrlon = BMAP_LONMAX, urcrnrlat = BMAP_LATMAX) # Displaying shape boundaries bmap.readshapefile ("map_bounds/geoflar-departements", "map_bounds", drawbounds = True) # Displaying points plons, plats = bmap (plons, plats) bmap.scatter (plons, plats, s = psizes, c= pstars, alpha = BMAP_ALPHA, marker = BMAP_MARKER) # Displaying keys leg_etoilefaible= mpatches.Rectangle((1,2), height = 1, width = 2, facecolor = (89/255,89/255,1)) leg_etoileeleve = mpatches.Rectangle((1,3), height = 1, width = 2, facecolor=(89/255,1,172/255)) plt.legend([leg_etoilefaible,leg_etoileeleve],["Nombre moyen d'étoiles faible","Nombre moyen d'étoiles élevé"] , loc =4)
df = pd.read_csv('ML_Data_Insight_121016.csv', header=1) from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt fig = plt.figure() ax2 = fig.add_subplot(111, projection='3d') x1 = df.ix[0:, 'x1'] x2 = df.ix[0:, 'x2'] x3 = df.ix[0:, 'x3'] y = df.ix[0:, 'y'] if sys.argv[1:] == ['winter']: p = ax2.scatter(x1, x2, x3, c=y, cmap=plt.winter()) elif sys.argv[1:] == ['cool']: p = ax2.scatter(x1, x2, x3, c=y, cmap=plt.cool()) elif sys.argv[1:] == ['viridis']: p = ax2.scatter(x1, x2, x3, c=y, cmap=plt.viridis()) elif sys.argv[1:] == ['plasma']: p = ax2.scatter(x1, x2, x3, c=y, cmap=plt.plasma()) elif sys.argv[1:] == ['inferno']: p = ax2.scatter(x1, x2, x3, c=y, cmap=plt.inferno()) elif sys.argv[1:] == ['jet']: p = ax2.scatter(x1, x2, x3, c=y, cmap=plt.jet()) elif sys.argv[1:] == ['gist_ncar']: p = ax2.scatter(x1, x2, x3, c=y, cmap=plt.gist_ncar()) elif sys.argv[1:] == ['rainbow']: p = ax2.scatter(x1, x2, x3, c=y, cmap=plt.nipy_spectral()) else: