def funcion(dato,opciones): from rpy import r diccionario={} if opciones.has_key("Cuantiles"): if opciones["Cuantiles"][u"DirecciónCola"]=='izquierda': sentido=True else: sentido=False diccionario["cuantiles"]=r.qnorm([float(opciones["Cuantiles"]["Probabilidad"])],mean=float(opciones["Cuantiles"]["Media"]),sd=float(opciones["Cuantiles"][u"Desviación"]),lower_tail=sentido) if opciones.has_key("Probabilidades"): if opciones["Probabilidades"][u"DirecciónCola"]=='izquierda': sentido=True else: sentido=False diccionario["probabilidades"]=r.pnorm([float(opciones["Probabilidades"]["Valores"])],mean=float(opciones["Probabilidades"]["Media"]),sd=float(opciones["Probabilidades"][u"Desviación"]),lower_tail=sentido) if opciones.has_key(u"Gráfica"): import random nombrefichero="/tmp/driza"+str(random.randint(1,99999))+".png" diccionario["ruta"]=nombrefichero r.png(nombrefichero) #Directorio temporal de la config lista=r.seq(-3.291, 3.291, length=100) if opciones[u"Gráfica"]["Tipografica"]=="Densidad": etiquetay="Densidad" mifuncion=r.dnorm else: etiquetay="Probabilidad acumulada" mifuncion=r.pnorm r.plot(lista, mifuncion(lista, mean=float(opciones[u"Gráfica"]["Media"]), sd=float(opciones[u"Gráfica"][u"Desviación"])), xlab="x", ylab=etiquetay, main=r.expression(r.paste("Normal Distribution: ", "mu", " = 0, ", "sigma", " = 1")), type="l") r.abline(h=0, col="gray") r.dev_off() return diccionario
def qqplot_density(samples, density_x, density_y): from rpy import r # LAME: should do better quantile calculation. r.quantile() returns a # hard-to-use dictionary unfortunately. r.approx() as per ?quantile, maybe. percs = list(np.arange(1,100, .1)) data_perc=np.percentile(samples, percs) real_perc=np.percentile(r.sample(density_x, len(samples)*10, prob=density_y, replace=True), percs) r.plot(real_perc, data_perc, xlab='',ylab='',main=''); r.abline(a=0,b=1,col='blue')
def trace_plots(history, burnin): from rpy import r h = np.array(history) print "{} total, {} burning, {} remaining".format(len(history), burnin, len(history)-burnin) r.par(mfrow=[2,2]) r.acf(h[burnin:]) r.plot(h,xlab='',ylab='',main='') r.abline(v=burnin, col='blue') #r.hist(h[burnin:],breaks=30,xlab='',ylab='',main='histogram') r.plot(r.density(h[burnin:]), xlab='',ylab='',main='density')
def qqplot_density(samples, density_x, density_y): from rpy import r # LAME: should do better quantile calculation. r.quantile() returns a # hard-to-use dictionary unfortunately. r.approx() as per ?quantile, maybe. percs = list(np.arange(1, 100, .1)) data_perc = np.percentile(samples, percs) real_perc = np.percentile( r.sample(density_x, len(samples) * 10, prob=density_y, replace=True), percs) r.plot(real_perc, data_perc, xlab='', ylab='', main='') r.abline(a=0, b=1, col='blue')
def trace_plots(history, burnin): from rpy import r h = np.array(history) print "{} total, {} burning, {} remaining".format(len(history), burnin, len(history) - burnin) r.par(mfrow=[2, 2]) r.acf(h[burnin:]) r.plot(h, xlab='', ylab='', main='') r.abline(v=burnin, col='blue') #r.hist(h[burnin:],breaks=30,xlab='',ylab='',main='histogram') r.plot(r.density(h[burnin:]), xlab='', ylab='', main='density')
def plots(regression_o, getData_o): """Plots the dataset with a regression line and a boxplot using R.""" fname1 = 'car_regress.pdf' r.pdf(fname1) r.plot(getData_o, ylab='dist', xlab='speed') r.abline(regression_o['(Intercept)'], regression_o['y'], col='red') r.dev_off() fname2 = 'car_hist.pdf' r.pdf(fname2) r.boxplot(getData_o, names=['dist', 'speed']) r.dev_off() return fname1, fname2
def plotArray(self, hitDataParam, filename, plotDir=None, labeledPosD=None, title='', type='png', label_colors = True, colVecL=None, legend_plot = False, legend_filename=None, control_color='black', numeric_as_int = False, grid=True, max_val=0.3, min_val=0.0, cut_data = True): if plotDir is None: plotDir = self.plotDir full_filename = os.path.join(plotDir, filename) #hitData = copy.deepcopy(hitDataParam) hitData = hitDataParam #nrow = len(hitData) #ncol = len(hitData[0]) nrow = self.nb_row ncol = self.nb_col xL = range(1, self.nb_col + 1) yL = range(1, self.nb_row + 1) rdev = plot_utilities.RDevice(name = full_filename, title=title, plotType=type, width=640, height=250) if label_colors: # in this case, the data is considered to consist of labels labelL = [] for i in range(nrow): for j in range(ncol): if hitData[i][j] not in labelL: labelL.append(hitData[i][j]) if colVecL is None: colVecL = r.rainbow(len(labelL)) colBreaksL = range(len(colVecL) + 1) if legend_plot: self.plotLabelLegend(colVecL, plotType=type, filename=legend_filename) else: # in this case, the data is numeric. if cut_data: max_rel_cell_count = max_val min_rel_cell_count = 0.0 for i in range(nrow): for j in range(ncol): hitData[i][j] = max(min_rel_cell_count, min(max_rel_cell_count, hitData[i][j])) else: max_rel_cell_count = max([max(x) for x in hitData.tolist() ]) min_rel_cell_count = min([min(x) for x in hitData.tolist() ]) if numeric_as_int: nb_colors = max_rel_cell_count else: nb_colors = 500 if colVecL is None: pattern = [(0,0,0),(0.7,0,0),(1,1,0),(1,1,1)] colVecL = colors.make_colors(pattern, nb_colors) colBreaksL = [1.0/ (len(colVecL) - 1) * x * (max_rel_cell_count - min_rel_cell_count) + min_rel_cell_count for x in range(len(colVecL) + 1)] if legend_plot: self.plotNumLegend(colVecL, colBreaksL, 16, filename=legend_filename, type=type, int_labels=numeric_as_int, legendDir = plotDir) axisSize = .8 r("par(mar=c(1.6,1.6,0.1,0.1))") r.image(xL, yL, r.t(hitData), axes = False, ann=False, cex=1, col=colVecL, breaks=colBreaksL) r.box() if not labeledPosD is None: for label in labeledPosD.keys(): posL = labeledPosD[label] if len(posL) > 0: xlL = [(int(x)-1) % self.nb_col + 1 for x in posL] ylL = [(int(x)-1) / self.nb_col + 1 for x in posL] r.points(xlL, ylL, pch=label, col=control_color, cex=axisSize) print print xlL print ylL print # grid if grid: for i in range(self.nb_col): r.abline(h=i+.5, lty=3, lwd=1, col='grey') for i in range(self.nb_row): r.abline(v=i+.5, lty=3, lwd=1, col='grey') r.axis(1, at=xL, labels=[str(x) for x in xL], tick=False, line=-1.0, cex_axis=axisSize) r.axis(2, at=yL, labels=[str(y) for y in yL], tick=False, line=-1.0, cex_axis=axisSize) rdev.close() return
from rpy import r my_x = [5.05, 6.75, 3.21, 2.66] my_y = [1.65, 26.5, -5.93, 7.96] ls_fit = r.lsfit(my_x,my_y) gradient = ls_fit['coefficients']['X'] yintercept= ls_fit['coefficients']['Intercept'] r.png("scatter_regression.png", width=400, height=350) r.plot(x=my_x, y=my_y, xlab="x", ylab="y", xlim=(0,7), ylim=(-16,27), main="Example Scatter with regression") r.abline(a=yintercept, b=gradient, col="red") r.dev_off()
def plotVertical(self, lty=3, col='lightgray', **other): from rpy import r for kmag in self.kmags(): r.abline(v=kmag, lty=lty, col=col, **other)
#thisRun.sort() print "top modes:" print "%6s %6s %7s %9s"%('kmag', 'Sk', 'kmag/L', 'L/kmag') for Sk, kmag in zip(v_sk, v_kmag)[-10:]: print "%6.3f %6.3f %7.5f %9.5f"%(kmag, Sk, kmag/L, L/kmag) r.plot(v_kmag, v_sk, xlab="", ylab="", type="l", ylim=(0., 15) #ylim=(0., 15000) ) # plots a line at each k-vector point. for kmag in v_kmag: r.abline(v=kmag, lty=3, col="lightgray") # plots each individual k-vector for kmag, SkArray in zip(v_kmag, StructCorr.SkArrays()): r.points(x=[kmag]*len(SkArray), y=SkArray, col="blue", pch="x") # plots the standard deviation of the by-kvector lists. for kmag, SkArray in zip(v_kmag, StructCorr.SkArrays()): r.points(x=kmag, y=numpy.std(SkArray), col="red", pch="s") # plots it using the average of all k-vectors -- this should line up # exactly #for kmag, SkArray in zip(v_kmag, StructCorr.SkArrays()): # r.points(x=kmag, y=numpy.average(SkArray), # col="green", pch="x")