¿Por qué R?
Directamente desde: The R Project for Statistical Computing
Ver también RStudio (RStudio 2022.12.0 ÚLTIMO)
https://www.filehorse.com/es/descargar-rstudio/
R install
Paquetes en R
Paquetes en R
> a = 1
> A = 2
> a == A
[1] FALSE
>help.start() # abre ventana con web para ayuda
>help("pp") # ayuda con la función "pp"
>?pp # ayuda con la función "pp"
>help.search("pp") # busca apariciones de la cadena "pp"
>??pp # busca apariciones de la cadena "pp"
>apropos("pp", mode="function") # lista funciones con "pp" en el nombre
>example(topic) # corre el código en R con ejemplos en un tópico
# determinado (por ejemplo “example(plot)”)
O usar directamente el buscador del sistema de ayuda de *RStudio*
R.home() # vuelve al directorio raíz de R
[1] “/usr/lib64/R”
getwd() # vuelve al directorio de trabajo
[1] “/home/user/R”
setwd(“/home/user/newRdir”) # establece un nuevo directorio de trabajo
dir() # muestra el contenido del directorio actual
ls()… # muestra el contenido del espacio de trabajo
history(n) # muestra los últimos n comandos
source(“filename.R”) # ejecuta comandos en el script filename.R
sink(“register.txt”) # envía la salida de R a un fichero externo
sink() # termina el envío anterior (vuelve a terminal)
save.image(“filename”) # guarda espacio de trabajo
load(“filename”) # carga espacio de trabajo
save(objectlist,file=“filename”) # guarda objetos específicos
options() # muestra las opciones
options(opt=…) # fija una opción
R es un lenguaje orientado a objetos (un objeto es algo que puede ser asignado a una variable)
Vectores (unidimensionales)
Matrices (bidimensionales)
Arrays (multidimensionales)
Factores (vectores de variables categóricas, para agrupar los componentes de otro vector)
Listas (colección de objetos, cada uno puede ser de un tipo)
Data Frames (generalización de matrices; cada fila es un elemento, cada columna una variable de diferente tipo)
Funciones (objetos creados para hacer operaciones)
Vectores y Arrays
a<-1.7
a #Muestra el resultado
## [1] 1.7
a=1.7
a #Muestra el resultado
## [1] 1.7
assign("a",1.7)
a #Imprime el valor de "a"
## [1] 1.7
b<-c(10,11,12,15,19)
b #Imprime el valor de "b"
## [1] 10 11 12 15 19
b*b
## [1] 100 121 144 225 361
1/b
## [1] 0.10000000 0.09090909 0.08333333 0.06666667 0.05263158
c <- b-1
c
## [1] 9 10 11 14 18
x[n] # elemento en la posición n
x[c(n1,n2)] # elemento en las posiciones n1 y n2
x[n1:n2] # elemento en las posiciones de n1 a n2
2:10 # Imprime números del 2 al 10
## [1] 2 3 4 5 6 7 8 9 10
5:1 # Imprime números del 5 al 1
## [1] 5 4 3 2 1
seq(from=1, to=10, by=3) # Imprime números del 1 al 10 de 3 en 3
## [1] 1 4 7 10
seq(1, 10, 3) # Imprime números del 1 al 10 de 3 en 3
## [1] 1 4 7 10
seq(length=10, from=1, by=3)# Imprime 10 números empezando del 1 de 3 en 3
## [1] 1 4 7 10 13 16 19 22 25 28
a <- 1:3; b <- rep(a, times=3); c <- rep(a, each=3)
a #Imprime números del 1 al 3
## [1] 1 2 3
b #Imprime números del 1 al 3 dos veces
## [1] 1 2 3 1 2 3 1 2 3
c #Imprime números del 1 al 3 pero cada cifra 3 veces
## [1] 1 1 1 2 2 2 3 3 3
a <- seq(1:10)
a
## [1] 1 2 3 4 5 6 7 8 9 10
b <- (a>5) # asigna valores TRUE o FALSE a partir de una desigualdad
b
## [1] FALSE FALSE FALSE FALSE FALSE TRUE TRUE TRUE TRUE TRUE
a[b] # muestra los valores que cumplen una condición
## [1] 6 7 8 9 10
a[a>5] # igual, pero evitando variables intermedias
## [1] 6 7 8 9 10
a <- "Esto es un ejemplo"
a
## [1] "Esto es un ejemplo"
x <- 1.5
y <- -2.7
paste("los puntos son (",x,",",y,")", sep="") # concatenando x, y más un texto usando 'paste'
## [1] "los puntos son (1.5,-2.7)"
a <- "Esto es un ejemplo" # extrayendo una parte de la cadena
a <- matrix(1:12, nrow=3, ncol=4)
a
## [,1] [,2] [,3] [,4]
## [1,] 1 4 7 10
## [2,] 2 5 8 11
## [3,] 3 6 9 12
b <- matrix(1:8, nrow=4, ncol=4, byrow=TRUE)
b
## [,1] [,2] [,3] [,4]
## [1,] 1 2 3 4
## [2,] 5 6 7 8
## [3,] 1 2 3 4
## [4,] 5 6 7 8
Los elementos se reciclan si hay menos elementos que espacios a a rellenar.
Si no se dice lo contrario, se rellenan por columnas,para hacerlo por filas incluir “byrow=TRUE”
z <- array(1:24, dim=c(2,3,4))
z
## , , 1
##
## [,1] [,2] [,3]
## [1,] 1 3 5
## [2,] 2 4 6
##
## , , 2
##
## [,1] [,2] [,3]
## [1,] 7 9 11
## [2,] 8 10 12
##
## , , 3
##
## [,1] [,2] [,3]
## [1,] 13 15 17
## [2,] 14 16 18
##
## , , 4
##
## [,1] [,2] [,3]
## [1,] 19 21 23
## [2,] 20 22 24
dim(z)
## [1] 2 3 4
Vectores que contienen información categórica útil para agrupar los elementos de otros vectores del mismo tamaño
bv <- c(0.92,0.97,0.87,0.91,0.92,1.04,0.91,0.94,0.96,0.90,0.96,0.86,0.85)
# colores (B-V) para 13 galaxias
morfo <- c("Sab","E","Sab","S0","E","E","S0","S0","E", "Sab","E","Sab","S0") # información morfológica
length(morfo) # comprobamos que es el mismo tamaño
## [1] 13
fmorfo <- factor(morfo) # se crea el factor con 'factor()'
fmorfo
## [1] Sab E Sab S0 E E S0 S0 E Sab E Sab S0
## Levels: E S0 Sab
# muestra los diferentes factores
levels(fmorfo) # muestra los niveles
## [1] "E" "S0" "Sab"
bv[fmorfo=="E"]
## [1] 0.97 0.92 1.04 0.96 0.96
# separa un determinado nivel
mean(bv[fmorfo=="E"]) # hace una operación sobre un nivel
## [1] 0.97
Útil para identificar submuestras y realizar operaciones sólo sobre sus elementos
Colección ordenadas de objetos, donde se pueden agrupar objetos de diferentes tipos (por ejemplo una combinación de vectores, matrices, factores, otras listas, etc.)
gal <- list(name="NGC3379", morf="E", T.RC3=-5, colours=c(0.53,0.96))
gal
## $name
## [1] "NGC3379"
##
## $morf
## [1] "E"
##
## $T.RC3
## [1] -5
##
## $colours
## [1] 0.53 0.96
length(gal) # muestra cuántos elementos tiene
## [1] 4
names(gal) # muestra los nombres de los elementos
## [1] "name" "morf" "T.RC3" "colours"
gal$radio <- TRUE # pueden añadirse nuevos elementos
gal$redshift <- 0.002922 # add a numeric element
names(gal)
## [1] "name" "morf" "T.RC3" "colours" "radio" "redshift"
# se pueden concatenar varias listas para producir otra
Muy versátiles porque pueden almacenar cualquier tipo de información, pero pueden convertirse en estructuras muy complejas.
Tipo especial de lista de gran utilidad estadística. Sus componente son vectores, o factores, de igual longitud.
La información se organiza en una tabla. Típicamente, cada fila corresponde a un elemento de la muestra. Cada columna a una variable medida en toda (o parte de) la muestra.
Los elementos dentro de cada columna son del mismo tipo. Cada columna puede ser de un tipo diferente.
Cuidado: Al crearse, los caracteres se convierten automáticamente en factores. Para evitarlo usar: “options(stringsAsFactors = FALSE)”
Se crean con la función: “data.frame(…)”
Cada columna (variable) tiene un título o nombre
options(stringsAsFactors = FALSE)
df <- data.frame(numbers=c(10,20,30,40),text=c("a","b","c","a"))
df
## numbers text
## 1 10 a
## 2 20 b
## 3 30 c
## 4 40 a
options(stringsAsFactors = TRUE)
## Warning in options(stringsAsFactors = TRUE): 'options(stringsAsFactors = TRUE)'
## is deprecated and will be disabled
df <-data.frame(numbers=c(10,20,30,40),text=c("a","b","c","a"))
df$text
## [1] "a" "b" "c" "a"
x<-data.frame(vector1, vector2, vector3) #Vectores para cada columna
# Los nombres de cada variable (Columna) seran "vector1", etc.
Para referirse a las columnas,x[n],x[n1,n2], x[c(n1,n2)]
O por el nombre:x[c(“vector1”,“vector2”)], x$vector1
Se pueden generar factores a partir de una variable continua usando el comando cut. Si el parámetro break, es un número, indica el número de intervalos. Con table, se construye una tabla de frecuencias:
bv<-c(0.92,0.97,0.87,0.91,0.92,1.04,0.91,0.94,0.96,0.90,0.96,0.86,0.85) #Colores (B-V) para 13 galaxias
fbv<-cut(bv,breaks=3) #divide "bv" en 3 intervalos de igual longitud
fbv # Muestra el intervalo de cada galaxia
## [1] (0.913,0.977] (0.913,0.977] (0.85,0.913] (0.85,0.913] (0.913,0.977]
## [6] (0.977,1.04] (0.85,0.913] (0.913,0.977] (0.913,0.977] (0.85,0.913]
## [11] (0.913,0.977] (0.85,0.913] (0.85,0.913]
## Levels: (0.85,0.913] (0.913,0.977] (0.977,1.04]
table(fbv) #Genera una tabla contando el numero de galaxias
## fbv
## (0.85,0.913] (0.913,0.977] (0.977,1.04]
## 6 6 1
# (frecuencias) en cada intervalo
Si el parámetro break es un vector, indica los extremos de los intervalos:
ffbv<-cut(bv,breaks = c(0.80,0.90,1.00,1.10))
table(ffbv)
## ffbv
## (0.8,0.9] (0.9,1] (1,1.1]
## 4 8 1
Para dividir por cuantiles, usar la opción quantile:
ffffbv<-cut(bv,quantile(bv,(0:4)/4))
table(ffffbv)
## ffffbv
## (0.85,0.9] (0.9,0.92] (0.92,0.96] (0.96,1.04]
## 3 4 3 2
Se puede usar la opción pretty para dividir en n intervalos más o menos redondeados:
fffbv<-cut(bv,pretty(bv,3))
Construcción de tablas multidimensionales
heights<-c(1.64,1.76,1.79,1.65,1.68,1.65,1.86,1.82,1.73,1.75,1.59,1.87,1.73,1.57,1.63,1.71,1.68,1.73,1.53,1.82)
weights<-c(64,77,82,62,71,72,85,68,72,75,81,88,72,71,74,69,81,67,65,73)
ages<-c(12,34,23,53,23,12,53,38,83,28,28,58,38,63,72,44,33,27,32,38)
fheights<-cut(heights,c(1.50,1.60,1.70,1.80,1.90))
fweights<-cut(weights,c(60,70,80,90))
fages<-cut(ages,seq(10,90,10))
Tabla entre dos variables:
ta<-table(fheights,fweights);ta
## fweights
## fheights (60,70] (70,80] (80,90]
## (1.5,1.6] 1 1 1
## (1.6,1.7] 2 3 1
## (1.7,1.8] 2 4 1
## (1.8,1.9] 1 1 2
Añadiendo frecuencias marginales:
addmargins(ta)
## fweights
## fheights (60,70] (70,80] (80,90] Sum
## (1.5,1.6] 1 1 1 3
## (1.6,1.7] 2 3 1 6
## (1.7,1.8] 2 4 1 7
## (1.8,1.9] 1 1 2 4
## Sum 6 9 5 20
Frecuencias relativas (con el comando prop.table):
tta<-prop.table(ta)
addmargins(tta)
## fweights
## fheights (60,70] (70,80] (80,90] Sum
## (1.5,1.6] 0.05 0.05 0.05 0.15
## (1.6,1.7] 0.10 0.15 0.05 0.30
## (1.7,1.8] 0.10 0.20 0.05 0.35
## (1.8,1.9] 0.05 0.05 0.10 0.20
## Sum 0.30 0.45 0.25 1.00
De la misma forma se pueden crear tablas tridimensionales, etc
table(fheights,fweights,fages)
## , , fages = (10,20]
##
## fweights
## fheights (60,70] (70,80] (80,90]
## (1.5,1.6] 0 0 0
## (1.6,1.7] 1 1 0
## (1.7,1.8] 0 0 0
## (1.8,1.9] 0 0 0
##
## , , fages = (20,30]
##
## fweights
## fheights (60,70] (70,80] (80,90]
## (1.5,1.6] 0 0 1
## (1.6,1.7] 0 1 0
## (1.7,1.8] 1 1 1
## (1.8,1.9] 0 0 0
##
## , , fages = (30,40]
##
## fweights
## fheights (60,70] (70,80] (80,90]
## (1.5,1.6] 1 0 0
## (1.6,1.7] 0 0 1
## (1.7,1.8] 0 2 0
## (1.8,1.9] 1 1 0
##
## , , fages = (40,50]
##
## fweights
## fheights (60,70] (70,80] (80,90]
## (1.5,1.6] 0 0 0
## (1.6,1.7] 0 0 0
## (1.7,1.8] 1 0 0
## (1.8,1.9] 0 0 0
##
## , , fages = (50,60]
##
## fweights
## fheights (60,70] (70,80] (80,90]
## (1.5,1.6] 0 0 0
## (1.6,1.7] 1 0 0
## (1.7,1.8] 0 0 0
## (1.8,1.9] 0 0 2
##
## , , fages = (60,70]
##
## fweights
## fheights (60,70] (70,80] (80,90]
## (1.5,1.6] 0 1 0
## (1.6,1.7] 0 0 0
## (1.7,1.8] 0 0 0
## (1.8,1.9] 0 0 0
##
## , , fages = (70,80]
##
## fweights
## fheights (60,70] (70,80] (80,90]
## (1.5,1.6] 0 0 0
## (1.6,1.7] 0 1 0
## (1.7,1.8] 0 0 0
## (1.8,1.9] 0 0 0
##
## , , fages = (80,90]
##
## fweights
## fheights (60,70] (70,80] (80,90]
## (1.5,1.6] 0 0 0
## (1.6,1.7] 0 0 0
## (1.7,1.8] 0 1 0
## (1.8,1.9] 0 0 0
Se pueden crear tablas bidimensionales a partir de matrices:
mtab<-matrix(c(30,12,47,58,25,32),ncol=2,byrow=TRUE)
colnames(mtab)<-c("ellipticals","spirals")
rownames(mtab)<-c("sample1","sample2","new sample")
mtab
## ellipticals spirals
## sample1 30 12
## sample2 47 58
## new sample 25 32
Pero no son “tablas reales”. Para transformarlas hacer:
rtab<-as.table(mtab)
class(mtab);class(rtab)
## [1] "matrix" "array"
## [1] "table"
El comando summary devuelve información diferente para una matriz y para una tabla:
summary(mtab)
## ellipticals spirals
## Min. :25.0 Min. :12
## 1st Qu.:27.5 1st Qu.:22
## Median :30.0 Median :32
## Mean :34.0 Mean :34
## 3rd Qu.:38.5 3rd Qu.:45
## Max. :47.0 Max. :58
summary(rtab)
## Number of cases in table: 204
## Number of factors: 2
## Test for independence of all factors:
## Chisq = 9.726, df = 2, p-value = 0.007726
Objetos que pueden ser creados por el usuario para hacer, y repetir, operaciones específicas:
Ejemplo: función para calcular la desviación típica de un vector:
stddev <- function(x){
res=sqrt(sum((x-mean(x))^2)/(length(x)-1))
return(res)
}
Se pueden usar y definir funciones dentro de funciones.
El valor devuelto por una función es el resultado de la última expresión evaluada o el especificado con el comando return
Los argumentos de las funciones pueden especificarse por su posición o por su nombre.
Puede haber argumentos con valores por defecto.
mynumbers<-c(1,2,3,4,5)
stddev(mynumbers)
## [1] 1.581139
stddev(x=mynumbers)
## [1] 1.581139
Ej. Función sd de R (calcula la desviación típica):
sd(x=mynumbers)
## [1] 1.581139
sd(x=mynumbers,na.rm=TRUE)
## [1] 1.581139
sd(mynumbers,na.rm=TRUE)
## [1] 1.581139
sd(na.rm=TRUE,x=mynumbers)
## [1] 1.581139
bv.list<-list(
colsSab=c(0.92,0.87,0.90,0.86),
colsE=c(0.97,0.92,1.04,0.96,0.96),
colsSO=c(0.91,0.91,0.94,0.85))
lapply(bv.list,mean)
## $colsSab
## [1] 0.8875
##
## $colsE
## [1] 0.97
##
## $colsSO
## [1] 0.9025
sapply(bv.list,mean)# devuelve un vector
## colsSab colsE colsSO
## 0.8875 0.9700 0.9025
a<-matrix(1:12,nrow=3,ncol=4)
a
## [,1] [,2] [,3] [,4]
## [1,] 1 4 7 10
## [2,] 2 5 8 11
## [3,] 3 6 9 12
apply(a,1,mean) #media por filas (“1”)
## [1] 5.5 6.5 7.5
rowMeans(a)
## [1] 5.5 6.5 7.5
apply(a,1,sum)
## [1] 22 26 30
rowSums(a)
## [1] 22 26 30
apply(a,2,mean) #medias por columnas (“2”)
## [1] 2 5 8 11
apply(a,2,sum)
## [1] 6 15 24 33
bv<-c(0.92,0.97,0.87,0.91,0.92,1.04,0.91,0.94,0.96,0.90,0.96,0.86,0.85)
morfo<-c("Sab","E","Sab","S0","E","E","S0","S0","E","Sab","E","Sab","S0")
fmorfo<-factor(morfo) # crea factor
tapply(bv,fmorfo,mean)
## E S0 Sab
## 0.9700 0.9025 0.8875
library(grid)
colors() # Lista de los 657 colores activos
## [1] "white" "aliceblue" "antiquewhite"
## [4] "antiquewhite1" "antiquewhite2" "antiquewhite3"
## [7] "antiquewhite4" "aquamarine" "aquamarine1"
## [10] "aquamarine2" "aquamarine3" "aquamarine4"
## [13] "azure" "azure1" "azure2"
## [16] "azure3" "azure4" "beige"
## [19] "bisque" "bisque1" "bisque2"
## [22] "bisque3" "bisque4" "black"
## [25] "blanchedalmond" "blue" "blue1"
## [28] "blue2" "blue3" "blue4"
## [31] "blueviolet" "brown" "brown1"
## [34] "brown2" "brown3" "brown4"
## [37] "burlywood" "burlywood1" "burlywood2"
## [40] "burlywood3" "burlywood4" "cadetblue"
## [43] "cadetblue1" "cadetblue2" "cadetblue3"
## [46] "cadetblue4" "chartreuse" "chartreuse1"
## [49] "chartreuse2" "chartreuse3" "chartreuse4"
## [52] "chocolate" "chocolate1" "chocolate2"
## [55] "chocolate3" "chocolate4" "coral"
## [58] "coral1" "coral2" "coral3"
## [61] "coral4" "cornflowerblue" "cornsilk"
## [64] "cornsilk1" "cornsilk2" "cornsilk3"
## [67] "cornsilk4" "cyan" "cyan1"
## [70] "cyan2" "cyan3" "cyan4"
## [73] "darkblue" "darkcyan" "darkgoldenrod"
## [76] "darkgoldenrod1" "darkgoldenrod2" "darkgoldenrod3"
## [79] "darkgoldenrod4" "darkgray" "darkgreen"
## [82] "darkgrey" "darkkhaki" "darkmagenta"
## [85] "darkolivegreen" "darkolivegreen1" "darkolivegreen2"
## [88] "darkolivegreen3" "darkolivegreen4" "darkorange"
## [91] "darkorange1" "darkorange2" "darkorange3"
## [94] "darkorange4" "darkorchid" "darkorchid1"
## [97] "darkorchid2" "darkorchid3" "darkorchid4"
## [100] "darkred" "darksalmon" "darkseagreen"
## [103] "darkseagreen1" "darkseagreen2" "darkseagreen3"
## [106] "darkseagreen4" "darkslateblue" "darkslategray"
## [109] "darkslategray1" "darkslategray2" "darkslategray3"
## [112] "darkslategray4" "darkslategrey" "darkturquoise"
## [115] "darkviolet" "deeppink" "deeppink1"
## [118] "deeppink2" "deeppink3" "deeppink4"
## [121] "deepskyblue" "deepskyblue1" "deepskyblue2"
## [124] "deepskyblue3" "deepskyblue4" "dimgray"
## [127] "dimgrey" "dodgerblue" "dodgerblue1"
## [130] "dodgerblue2" "dodgerblue3" "dodgerblue4"
## [133] "firebrick" "firebrick1" "firebrick2"
## [136] "firebrick3" "firebrick4" "floralwhite"
## [139] "forestgreen" "gainsboro" "ghostwhite"
## [142] "gold" "gold1" "gold2"
## [145] "gold3" "gold4" "goldenrod"
## [148] "goldenrod1" "goldenrod2" "goldenrod3"
## [151] "goldenrod4" "gray" "gray0"
## [154] "gray1" "gray2" "gray3"
## [157] "gray4" "gray5" "gray6"
## [160] "gray7" "gray8" "gray9"
## [163] "gray10" "gray11" "gray12"
## [166] "gray13" "gray14" "gray15"
## [169] "gray16" "gray17" "gray18"
## [172] "gray19" "gray20" "gray21"
## [175] "gray22" "gray23" "gray24"
## [178] "gray25" "gray26" "gray27"
## [181] "gray28" "gray29" "gray30"
## [184] "gray31" "gray32" "gray33"
## [187] "gray34" "gray35" "gray36"
## [190] "gray37" "gray38" "gray39"
## [193] "gray40" "gray41" "gray42"
## [196] "gray43" "gray44" "gray45"
## [199] "gray46" "gray47" "gray48"
## [202] "gray49" "gray50" "gray51"
## [205] "gray52" "gray53" "gray54"
## [208] "gray55" "gray56" "gray57"
## [211] "gray58" "gray59" "gray60"
## [214] "gray61" "gray62" "gray63"
## [217] "gray64" "gray65" "gray66"
## [220] "gray67" "gray68" "gray69"
## [223] "gray70" "gray71" "gray72"
## [226] "gray73" "gray74" "gray75"
## [229] "gray76" "gray77" "gray78"
## [232] "gray79" "gray80" "gray81"
## [235] "gray82" "gray83" "gray84"
## [238] "gray85" "gray86" "gray87"
## [241] "gray88" "gray89" "gray90"
## [244] "gray91" "gray92" "gray93"
## [247] "gray94" "gray95" "gray96"
## [250] "gray97" "gray98" "gray99"
## [253] "gray100" "green" "green1"
## [256] "green2" "green3" "green4"
## [259] "greenyellow" "grey" "grey0"
## [262] "grey1" "grey2" "grey3"
## [265] "grey4" "grey5" "grey6"
## [268] "grey7" "grey8" "grey9"
## [271] "grey10" "grey11" "grey12"
## [274] "grey13" "grey14" "grey15"
## [277] "grey16" "grey17" "grey18"
## [280] "grey19" "grey20" "grey21"
## [283] "grey22" "grey23" "grey24"
## [286] "grey25" "grey26" "grey27"
## [289] "grey28" "grey29" "grey30"
## [292] "grey31" "grey32" "grey33"
## [295] "grey34" "grey35" "grey36"
## [298] "grey37" "grey38" "grey39"
## [301] "grey40" "grey41" "grey42"
## [304] "grey43" "grey44" "grey45"
## [307] "grey46" "grey47" "grey48"
## [310] "grey49" "grey50" "grey51"
## [313] "grey52" "grey53" "grey54"
## [316] "grey55" "grey56" "grey57"
## [319] "grey58" "grey59" "grey60"
## [322] "grey61" "grey62" "grey63"
## [325] "grey64" "grey65" "grey66"
## [328] "grey67" "grey68" "grey69"
## [331] "grey70" "grey71" "grey72"
## [334] "grey73" "grey74" "grey75"
## [337] "grey76" "grey77" "grey78"
## [340] "grey79" "grey80" "grey81"
## [343] "grey82" "grey83" "grey84"
## [346] "grey85" "grey86" "grey87"
## [349] "grey88" "grey89" "grey90"
## [352] "grey91" "grey92" "grey93"
## [355] "grey94" "grey95" "grey96"
## [358] "grey97" "grey98" "grey99"
## [361] "grey100" "honeydew" "honeydew1"
## [364] "honeydew2" "honeydew3" "honeydew4"
## [367] "hotpink" "hotpink1" "hotpink2"
## [370] "hotpink3" "hotpink4" "indianred"
## [373] "indianred1" "indianred2" "indianred3"
## [376] "indianred4" "ivory" "ivory1"
## [379] "ivory2" "ivory3" "ivory4"
## [382] "khaki" "khaki1" "khaki2"
## [385] "khaki3" "khaki4" "lavender"
## [388] "lavenderblush" "lavenderblush1" "lavenderblush2"
## [391] "lavenderblush3" "lavenderblush4" "lawngreen"
## [394] "lemonchiffon" "lemonchiffon1" "lemonchiffon2"
## [397] "lemonchiffon3" "lemonchiffon4" "lightblue"
## [400] "lightblue1" "lightblue2" "lightblue3"
## [403] "lightblue4" "lightcoral" "lightcyan"
## [406] "lightcyan1" "lightcyan2" "lightcyan3"
## [409] "lightcyan4" "lightgoldenrod" "lightgoldenrod1"
## [412] "lightgoldenrod2" "lightgoldenrod3" "lightgoldenrod4"
## [415] "lightgoldenrodyellow" "lightgray" "lightgreen"
## [418] "lightgrey" "lightpink" "lightpink1"
## [421] "lightpink2" "lightpink3" "lightpink4"
## [424] "lightsalmon" "lightsalmon1" "lightsalmon2"
## [427] "lightsalmon3" "lightsalmon4" "lightseagreen"
## [430] "lightskyblue" "lightskyblue1" "lightskyblue2"
## [433] "lightskyblue3" "lightskyblue4" "lightslateblue"
## [436] "lightslategray" "lightslategrey" "lightsteelblue"
## [439] "lightsteelblue1" "lightsteelblue2" "lightsteelblue3"
## [442] "lightsteelblue4" "lightyellow" "lightyellow1"
## [445] "lightyellow2" "lightyellow3" "lightyellow4"
## [448] "limegreen" "linen" "magenta"
## [451] "magenta1" "magenta2" "magenta3"
## [454] "magenta4" "maroon" "maroon1"
## [457] "maroon2" "maroon3" "maroon4"
## [460] "mediumaquamarine" "mediumblue" "mediumorchid"
## [463] "mediumorchid1" "mediumorchid2" "mediumorchid3"
## [466] "mediumorchid4" "mediumpurple" "mediumpurple1"
## [469] "mediumpurple2" "mediumpurple3" "mediumpurple4"
## [472] "mediumseagreen" "mediumslateblue" "mediumspringgreen"
## [475] "mediumturquoise" "mediumvioletred" "midnightblue"
## [478] "mintcream" "mistyrose" "mistyrose1"
## [481] "mistyrose2" "mistyrose3" "mistyrose4"
## [484] "moccasin" "navajowhite" "navajowhite1"
## [487] "navajowhite2" "navajowhite3" "navajowhite4"
## [490] "navy" "navyblue" "oldlace"
## [493] "olivedrab" "olivedrab1" "olivedrab2"
## [496] "olivedrab3" "olivedrab4" "orange"
## [499] "orange1" "orange2" "orange3"
## [502] "orange4" "orangered" "orangered1"
## [505] "orangered2" "orangered3" "orangered4"
## [508] "orchid" "orchid1" "orchid2"
## [511] "orchid3" "orchid4" "palegoldenrod"
## [514] "palegreen" "palegreen1" "palegreen2"
## [517] "palegreen3" "palegreen4" "paleturquoise"
## [520] "paleturquoise1" "paleturquoise2" "paleturquoise3"
## [523] "paleturquoise4" "palevioletred" "palevioletred1"
## [526] "palevioletred2" "palevioletred3" "palevioletred4"
## [529] "papayawhip" "peachpuff" "peachpuff1"
## [532] "peachpuff2" "peachpuff3" "peachpuff4"
## [535] "peru" "pink" "pink1"
## [538] "pink2" "pink3" "pink4"
## [541] "plum" "plum1" "plum2"
## [544] "plum3" "plum4" "powderblue"
## [547] "purple" "purple1" "purple2"
## [550] "purple3" "purple4" "red"
## [553] "red1" "red2" "red3"
## [556] "red4" "rosybrown" "rosybrown1"
## [559] "rosybrown2" "rosybrown3" "rosybrown4"
## [562] "royalblue" "royalblue1" "royalblue2"
## [565] "royalblue3" "royalblue4" "saddlebrown"
## [568] "salmon" "salmon1" "salmon2"
## [571] "salmon3" "salmon4" "sandybrown"
## [574] "seagreen" "seagreen1" "seagreen2"
## [577] "seagreen3" "seagreen4" "seashell"
## [580] "seashell1" "seashell2" "seashell3"
## [583] "seashell4" "sienna" "sienna1"
## [586] "sienna2" "sienna3" "sienna4"
## [589] "skyblue" "skyblue1" "skyblue2"
## [592] "skyblue3" "skyblue4" "slateblue"
## [595] "slateblue1" "slateblue2" "slateblue3"
## [598] "slateblue4" "slategray" "slategray1"
## [601] "slategray2" "slategray3" "slategray4"
## [604] "slategrey" "snow" "snow1"
## [607] "snow2" "snow3" "snow4"
## [610] "springgreen" "springgreen1" "springgreen2"
## [613] "springgreen3" "springgreen4" "steelblue"
## [616] "steelblue1" "steelblue2" "steelblue3"
## [619] "steelblue4" "tan" "tan1"
## [622] "tan2" "tan3" "tan4"
## [625] "thistle" "thistle1" "thistle2"
## [628] "thistle3" "thistle4" "tomato"
## [631] "tomato1" "tomato2" "tomato3"
## [634] "tomato4" "turquoise" "turquoise1"
## [637] "turquoise2" "turquoise3" "turquoise4"
## [640] "violet" "violetred" "violetred1"
## [643] "violetred2" "violetred3" "violetred4"
## [646] "wheat" "wheat1" "wheat2"
## [649] "wheat3" "wheat4" "whitesmoke"
## [652] "yellow" "yellow1" "yellow2"
## [655] "yellow3" "yellow4" "yellowgreen"
demo(colors) # Demostración
##
##
## demo(colors)
## ---- ~~~~~~
##
## > ### ----------- Show (almost) all named colors ---------------------
## >
## > ## 1) with traditional 'graphics' package:
## > showCols1 <- function(bg = "gray", cex = 0.75, srt = 30) {
## + m <- ceiling(sqrt(n <- length(cl <- colors())))
## + length(cl) <- m*m; cm <- matrix(cl, m)
## + ##
## + require("graphics")
## + op <- par(mar=rep(0,4), ann=FALSE, bg = bg); on.exit(par(op))
## + plot(1:m,1:m, type="n", axes=FALSE)
## + text(col(cm), rev(row(cm)), cm, col = cl, cex=cex, srt=srt)
## + }
##
## > showCols1()
##
## > ## 2) with 'grid' package:
## > showCols2 <- function(bg = "grey", cex = 0.75, rot = 30) {
## + m <- ceiling(sqrt(n <- length(cl <- colors())))
## + length(cl) <- m*m; cm <- matrix(cl, m)
## + ##
## + require("grid")
## + grid.newpage(); vp <- viewport(width = .92, height = .92)
## + grid.rect(gp=gpar(fill=bg))
## + grid.text(cm, x = col(cm)/m, y = rev(row(cm))/m, rot = rot,
## + vp=vp, gp=gpar(cex = cex, col = cm))
## + }
##
## > showCols2()
##
## > showCols2(bg = "gray33")
##
## > ###
## >
## > ##' @title Comparing Colors
## > ##' @param col
## > ##' @param nrow
## > ##' @param ncol
## > ##' @param txt.col
## > ##' @return the grid layout, invisibly
## > ##' @author Marius Hofert, originally
## > plotCol <- function(col, nrow=1, ncol=ceiling(length(col) / nrow),
## + txt.col="black") {
## + stopifnot(nrow >= 1, ncol >= 1)
## + if(length(col) > nrow*ncol)
## + warning("some colors will not be shown")
## + require(grid)
## + grid.newpage()
## + gl <- grid.layout(nrow, ncol)
## + pushViewport(viewport(layout=gl))
## + ic <- 1
## + for(i in 1:nrow) {
## + for(j in 1:ncol) {
## + pushViewport(viewport(layout.pos.row=i, layout.pos.col=j))
## + grid.rect(gp= gpar(fill=col[ic]))
## + grid.text(col[ic], gp=gpar(col=txt.col))
## + upViewport()
## + ic <- ic+1
## + }
## + }
## + upViewport()
## + invisible(gl)
## + }
##
## > ## A Chocolate Bar of colors:
## > plotCol(c("#CC8C3C", paste0("chocolate", 2:4),
## + paste0("darkorange", c("",1:2)), paste0("darkgoldenrod", 1:2),
## + "orange", "orange1", "sandybrown", "tan1", "tan2"),
## + nrow=2)
##
## > ##' Find close R colors() to a given color {original by Marius Hofert)
## > ##' using Euclidean norm in (HSV / RGB / ...) color space
## > nearRcolor <- function(rgb, cSpace = c("hsv", "rgb255", "Luv", "Lab"),
## + dist = switch(cSpace, "hsv" = 0.10, "rgb255" = 30,
## + "Luv" = 15, "Lab" = 12))
## + {
## + if(is.character(rgb)) rgb <- col2rgb(rgb)
## + stopifnot(length(rgb <- as.vector(rgb)) == 3)
## + Rcol <- col2rgb(.cc <- colors())
## + uniqC <- !duplicated(t(Rcol)) # gray9 == grey9 (etc)
## + Rcol <- Rcol[, uniqC] ; .cc <- .cc[uniqC]
## + cSpace <- match.arg(cSpace)
## + convRGB2 <- function(Rgb, to)
## + t(convertColor(t(Rgb), from="sRGB", to=to, scale.in=255))
## + ## the transformation, rgb{0..255} --> cSpace :
## + TransF <- switch(cSpace,
## + "rgb255" = identity,
## + "hsv" = rgb2hsv,
## + "Luv" = function(RGB) convRGB2(RGB, "Luv"),
## + "Lab" = function(RGB) convRGB2(RGB, "Lab"))
## + d <- sqrt(colSums((TransF(Rcol) - as.vector(TransF(rgb)))^2))
## + iS <- sort.list(d[near <- d <= dist])# sorted: closest first
## + setNames(.cc[near][iS], format(zapsmall(d[near][iS]), digits=3))
## + }
##
## > nearRcolor(col2rgb("tan2"), "rgb")
## 0.0 21.1 25.8 29.5
## "tan2" "tan1" "sandybrown" "sienna1"
##
## > nearRcolor(col2rgb("tan2"), "hsv")
## 0.0000 0.0410 0.0618 0.0638 0.0667 0.0766
## "tan2" "sienna2" "coral2" "tomato2" "tan1" "coral"
## 0.0778 0.0900 0.0912 0.0918
## "sienna1" "sandybrown" "coral1" "tomato"
##
## > nearRcolor(col2rgb("tan2"), "Luv")
## 0.00 7.42 7.48 12.41 13.69
## "tan2" "tan1" "sandybrown" "orange3" "orange2"
##
## > nearRcolor(col2rgb("tan2"), "Lab")
## 0.00 5.56 8.08 11.31
## "tan2" "tan1" "sandybrown" "peru"
##
## > nearRcolor("#334455")
## 0.0867
## "darkslategray"
##
## > ## Now, consider choosing a color by looking in the
## > ## neighborhood of one you know :
## >
## > plotCol(nearRcolor("deepskyblue", "rgb", dist=50))
##
## > plotCol(nearRcolor("deepskyblue", dist=.1))
##
## > plotCol(nearRcolor("tomato", "rgb", dist= 50), nrow=3)
##
## > plotCol(nearRcolor("tomato", "hsv", dist=.12), nrow=3)
##
## > plotCol(nearRcolor("tomato", "Luv", dist= 25), nrow=3)
##
## > plotCol(nearRcolor("tomato", "Lab", dist= 18), nrow=3)
Especificar un color
col=92 #de 1 a 657
col="orange"
col=rgb(1,2,3)
col=hsv(299,92,552)
plot(x,y,col=)
Paletas de color con n colores contiguos:
n<-456
col=rainbow(n)
col=heat.colors(n)
col=terrain.colors(n)
col=topo.colors(n)
col=cm.colors(n)
col=gray(1:n/n)
demo(graphics)
##
##
## demo(graphics)
## ---- ~~~~~~~~
##
## > # Copyright (C) 1997-2009 The R Core Team
## >
## > require(datasets)
##
## > require(grDevices); require(graphics)
##
## > ## Here is some code which illustrates some of the differences between
## > ## R and S graphics capabilities. Note that colors are generally specified
## > ## by a character string name (taken from the X11 rgb.txt file) and that line
## > ## textures are given similarly. The parameter "bg" sets the background
## > ## parameter for the plot and there is also an "fg" parameter which sets
## > ## the foreground color.
## >
## >
## > x <- stats::rnorm(50)
##
## > opar <- par(bg = "white")
##
## > plot(x, ann = FALSE, type = "n")
##
## > abline(h = 0, col = gray(.90))
##
## > lines(x, col = "green4", lty = "dotted")
##
## > points(x, bg = "limegreen", pch = 21)
##
## > title(main = "Simple Use of Color In a Plot",
## + xlab = "Just a Whisper of a Label",
## + col.main = "blue", col.lab = gray(.8),
## + cex.main = 1.2, cex.lab = 1.0, font.main = 4, font.lab = 3)
##
## > ## A little color wheel. This code just plots equally spaced hues in
## > ## a pie chart. If you have a cheap SVGA monitor (like me) you will
## > ## probably find that numerically equispaced does not mean visually
## > ## equispaced. On my display at home, these colors tend to cluster at
## > ## the RGB primaries. On the other hand on the SGI Indy at work the
## > ## effect is near perfect.
## >
## > par(bg = "gray")
##
## > pie(rep(1,24), col = rainbow(24), radius = 0.9)
##
## > title(main = "A Sample Color Wheel", cex.main = 1.4, font.main = 3)
##
## > title(xlab = "(Use this as a test of monitor linearity)",
## + cex.lab = 0.8, font.lab = 3)
##
## > ## We have already confessed to having these. This is just showing off X11
## > ## color names (and the example (from the postscript manual) is pretty "cute".
## >
## > pie.sales <- c(0.12, 0.3, 0.26, 0.16, 0.04, 0.12)
##
## > names(pie.sales) <- c("Blueberry", "Cherry",
## + "Apple", "Boston Cream", "Other", "Vanilla Cream")
##
## > pie(pie.sales,
## + col = c("purple","violetred1","green3","cornsilk","cyan","white"))
##
## > title(main = "January Pie Sales", cex.main = 1.8, font.main = 1)
##
## > title(xlab = "(Don't try this at home kids)", cex.lab = 0.8, font.lab = 3)
##
## > ## Boxplots: I couldn't resist the capability for filling the "box".
## > ## The use of color seems like a useful addition, it focuses attention
## > ## on the central bulk of the data.
## >
## > par(bg="cornsilk")
##
## > n <- 10
##
## > g <- gl(n, 100, n*100)
##
## > x <- rnorm(n*100) + sqrt(as.numeric(g))
##
## > boxplot(split(x,g), col="lavender", notch=TRUE)
##
## > title(main="Notched Boxplots", xlab="Group", font.main=4, font.lab=1)
##
## > ## An example showing how to fill between curves.
## >
## > par(bg="white")
##
## > n <- 100
##
## > x <- c(0,cumsum(rnorm(n)))
##
## > y <- c(0,cumsum(rnorm(n)))
##
## > xx <- c(0:n, n:0)
##
## > yy <- c(x, rev(y))
##
## > plot(xx, yy, type="n", xlab="Time", ylab="Distance")
##
## > polygon(xx, yy, col="gray")
##
## > title("Distance Between Brownian Motions")
##
## > ## Colored plot margins, axis labels and titles. You do need to be
## > ## careful with these kinds of effects. It's easy to go completely
## > ## over the top and you can end up with your lunch all over the keyboard.
## > ## On the other hand, my market research clients love it.
## >
## > x <- c(0.00, 0.40, 0.86, 0.85, 0.69, 0.48, 0.54, 1.09, 1.11, 1.73, 2.05, 2.02)
##
## > par(bg="lightgray")
##
## > plot(x, type="n", axes=FALSE, ann=FALSE)
##
## > usr <- par("usr")
##
## > rect(usr[1], usr[3], usr[2], usr[4], col="cornsilk", border="black")
##
## > lines(x, col="blue")
##
## > points(x, pch=21, bg="lightcyan", cex=1.25)
##
## > axis(2, col.axis="blue", las=1)
##
## > axis(1, at=1:12, lab=month.abb, col.axis="blue")
##
## > box()
##
## > title(main= "The Level of Interest in R", font.main=4, col.main="red")
##
## > title(xlab= "1996", col.lab="red")
##
## > ## A filled histogram, showing how to change the font used for the
## > ## main title without changing the other annotation.
## >
## > par(bg="cornsilk")
##
## > x <- rnorm(1000)
##
## > hist(x, xlim=range(-4, 4, x), col="lavender", main="")
##
## > title(main="1000 Normal Random Variates", font.main=3)
##
## > ## A scatterplot matrix
## > ## The good old Iris data (yet again)
## >
## > pairs(iris[1:4], main="Edgar Anderson's Iris Data", font.main=4, pch=19)
##
## > pairs(iris[1:4], main="Edgar Anderson's Iris Data", pch=21,
## + bg = c("red", "green3", "blue")[unclass(iris$Species)])
##
## > ## Contour plotting
## > ## This produces a topographic map of one of Auckland's many volcanic "peaks".
## >
## > x <- 10*1:nrow(volcano)
##
## > y <- 10*1:ncol(volcano)
##
## > lev <- pretty(range(volcano), 10)
##
## > par(bg = "lightcyan")
##
## > pin <- par("pin")
##
## > xdelta <- diff(range(x))
##
## > ydelta <- diff(range(y))
##
## > xscale <- pin[1]/xdelta
##
## > yscale <- pin[2]/ydelta
##
## > scale <- min(xscale, yscale)
##
## > xadd <- 0.5*(pin[1]/scale - xdelta)
##
## > yadd <- 0.5*(pin[2]/scale - ydelta)
##
## > plot(numeric(0), numeric(0),
## + xlim = range(x)+c(-1,1)*xadd, ylim = range(y)+c(-1,1)*yadd,
## + type = "n", ann = FALSE)
##
## > usr <- par("usr")
##
## > rect(usr[1], usr[3], usr[2], usr[4], col="green3")
##
## > contour(x, y, volcano, levels = lev, col="yellow", lty="solid", add=TRUE)
##
## > box()
##
## > title("A Topographic Map of Maunga Whau", font= 4)
##
## > title(xlab = "Meters North", ylab = "Meters West", font= 3)
##
## > mtext("10 Meter Contour Spacing", side=3, line=0.35, outer=FALSE,
## + at = mean(par("usr")[1:2]), cex=0.7, font=3)
##
## > ## Conditioning plots
## >
## > par(bg="cornsilk")
##
## > coplot(lat ~ long | depth, data = quakes, pch = 21, bg = "green3")
##
## > par(opar)
demo(image)
##
##
## demo(image)
## ---- ~~~~~
##
## > # Copyright (C) 1997-2009 The R Core Team
## >
## > require(datasets)
##
## > require(grDevices); require(graphics)
##
## > x <- 10*(1:nrow(volcano)); x.at <- seq(100, 800, by=100)
##
## > y <- 10*(1:ncol(volcano)); y.at <- seq(100, 600, by=100)
##
## > # Using Terrain Colors
## >
## > image(x, y, volcano, col=terrain.colors(100),axes=FALSE)
##
## > contour(x, y, volcano, levels=seq(90, 200, by=5), add=TRUE, col="brown")
##
## > axis(1, at=x.at)
##
## > axis(2, at=y.at)
##
## > box()
##
## > title(main="Maunga Whau Volcano", sub = "col=terrain.colors(100)", font.main=4)
##
## > # Using Heat Colors
## >
## > image(x, y, volcano, col=heat.colors(100), axes=FALSE)
##
## > contour(x, y, volcano, levels=seq(90, 200, by=5), add=TRUE, col="brown")
##
## > axis(1, at=x.at)
##
## > axis(2, at=y.at)
##
## > box()
##
## > title(main="Maunga Whau Volcano", sub = "col=heat.colors(100)", font.main=4)
##
## > # Using Gray Scale
## >
## > image(x, y, volcano, col=gray(100:200/200), axes=FALSE)
##
## > contour(x, y, volcano, levels=seq(90, 200, by=5), add=TRUE, col="black")
##
## > axis(1, at=x.at)
##
## > axis(2, at=y.at)
##
## > box()
##
## > title(main="Maunga Whau Volcano \n col=gray(100:200/200)", font.main=4)
##
## > ## Filled Contours are even nicer sometimes :
## > example(filled.contour)
##
## flld.c> require("grDevices") # for colours
##
## flld.c> filled.contour(volcano, asp = 1) # simple
##
## flld.c> x <- 10*1:nrow(volcano)
##
## flld.c> y <- 10*1:ncol(volcano)
##
## flld.c> filled.contour(x, y, volcano,
## flld.c+ color.palette = function(n) hcl.colors(n, "terrain"),
## flld.c+ plot.title = title(main = "The Topography of Maunga Whau",
## flld.c+ xlab = "Meters North", ylab = "Meters West"),
## flld.c+ plot.axes = { axis(1, seq(100, 800, by = 100))
## flld.c+ axis(2, seq(100, 600, by = 100)) },
## flld.c+ key.title = title(main = "Height\n(meters)"),
## flld.c+ key.axes = axis(4, seq(90, 190, by = 10))) # maybe also asp = 1
##
## flld.c> mtext(paste("filled.contour(.) from", R.version.string),
## flld.c+ side = 1, line = 4, adj = 1, cex = .66)
##
## flld.c> # Annotating a filled contour plot
## flld.c> a <- expand.grid(1:20, 1:20)
##
## flld.c> b <- matrix(a[,1] + a[,2], 20)
##
## flld.c> filled.contour(x = 1:20, y = 1:20, z = b,
## flld.c+ plot.axes = { axis(1); axis(2); points(10, 10) })
##
## flld.c> ## Persian Rug Art:
## flld.c> x <- y <- seq(-4*pi, 4*pi, length.out = 27)
##
## flld.c> r <- sqrt(outer(x^2, y^2, `+`))
##
## flld.c> filled.contour(cos(r^2)*exp(-r/(2*pi)), axes = FALSE)
##
## flld.c> ## rather, the key *should* be labeled:
## flld.c> filled.contour(cos(r^2)*exp(-r/(2*pi)), frame.plot = FALSE,
## flld.c+ plot.axes = {})
demo(persp)
##
##
## demo(persp)
## ---- ~~~~~
##
## > ### Demos for persp() plots -- things not in example(persp)
## > ### -------------------------
## >
## > require(datasets)
##
## > require(grDevices); require(graphics)
##
## > ## (1) The Obligatory Mathematical surface.
## > ## Rotated sinc function.
## >
## > x <- seq(-10, 10, length.out = 50)
##
## > y <- x
##
## > rotsinc <- function(x,y)
## + {
## + sinc <- function(x) { y <- sin(x)/x ; y[is.na(y)] <- 1; y }
## + 10 * sinc( sqrt(x^2+y^2) )
## + }
##
## > sinc.exp <- expression(z == Sinc(sqrt(x^2 + y^2)))
##
## > z <- outer(x, y, rotsinc)
##
## > oldpar <- par(bg = "white")
##
## > persp(x, y, z, theta = 30, phi = 30, expand = 0.5, col = "lightblue")
##
## > title(sub=".")## work around persp+plotmath bug
##
## > title(main = sinc.exp)
##
## > persp(x, y, z, theta = 30, phi = 30, expand = 0.5, col = "lightblue",
## + ltheta = 120, shade = 0.75, ticktype = "detailed",
## + xlab = "X", ylab = "Y", zlab = "Z")
##
## > title(sub=".")## work around persp+plotmath bug
##
## > title(main = sinc.exp)
##
## > ## (2) Visualizing a simple DEM model
## >
## > z <- 2 * volcano # Exaggerate the relief
##
## > x <- 10 * (1:nrow(z)) # 10 meter spacing (S to N)
##
## > y <- 10 * (1:ncol(z)) # 10 meter spacing (E to W)
##
## > persp(x, y, z, theta = 120, phi = 15, scale = FALSE, axes = FALSE)
##
## > ## (3) Now something more complex
## > ## We border the surface, to make it more "slice like"
## > ## and color the top and sides of the surface differently.
## >
## > z0 <- min(z) - 20
##
## > z <- rbind(z0, cbind(z0, z, z0), z0)
##
## > x <- c(min(x) - 1e-10, x, max(x) + 1e-10)
##
## > y <- c(min(y) - 1e-10, y, max(y) + 1e-10)
##
## > fill <- matrix("green3", nrow = nrow(z)-1, ncol = ncol(z)-1)
##
## > fill[ , i2 <- c(1,ncol(fill))] <- "gray"
##
## > fill[i1 <- c(1,nrow(fill)) , ] <- "gray"
##
## > par(bg = "lightblue")
##
## > persp(x, y, z, theta = 120, phi = 15, col = fill, scale = FALSE, axes = FALSE)
##
## > title(main = "Maunga Whau\nOne of 50 Volcanoes in the Auckland Region.",
## + font.main = 4)
##
## > par(bg = "slategray")
##
## > persp(x, y, z, theta = 135, phi = 30, col = fill, scale = FALSE,
## + ltheta = -120, lphi = 15, shade = 0.65, axes = FALSE)
##
## > ## Don't draw the grid lines : border = NA
## > persp(x, y, z, theta = 135, phi = 30, col = "green3", scale = FALSE,
## + ltheta = -120, shade = 0.75, border = NA, box = FALSE)
##
## > ## `color gradient in the soil' :
## > fcol <- fill ; fcol[] <- terrain.colors(nrow(fcol))
##
## > persp(x, y, z, theta = 135, phi = 30, col = fcol, scale = FALSE,
## + ltheta = -120, shade = 0.3, border = NA, box = FALSE)
##
## > ## `image like' colors on top :
## > fcol <- fill
##
## > zi <- volcano[ -1,-1] + volcano[ -1,-61] +
## + volcano[-87,-1] + volcano[-87,-61] ## / 4
##
## > fcol[-i1,-i2] <-
## + terrain.colors(20)[cut(zi,
## + stats::quantile(zi, seq(0,1, length.out = 21)),
## + include.lowest = TRUE)]
##
## > persp(x, y, 2*z, theta = 110, phi = 40, col = fcol, scale = FALSE,
## + ltheta = -120, shade = 0.4, border = NA, box = FALSE)
##
## > ## reset par():
## > par(oldpar)
# install.packages("car")
library(car)
## Warning: package 'car' was built under R version 4.2.3
## Loading required package: carData
## Warning: package 'carData' was built under R version 4.2.3
attach(mtcars)