2016-03-02 535 views
1

我试图修改一些现有的代码,原来是在这里(https://stats.stackexchange.com/questions/76999/simulating-longitudinal-lognormal-data-in-r)中发现的问题,并用在以下网站展示R中的散点图:https://hopstat.wordpress.com/2014/10/30/my-commonly-done-ggplot2-graphs/在GGPLOT2散点图更改色彩

这是一个简单和愚蠢的问题,但我整个上午一直在努力。下面的代码给出了一个很好的黑白分布图。我想修改代码以使线条非常浅灰色。

library(MASS) 
library(nlme) 
library(plyr) 
library(ggplot2) 

### set number of individuals 
n <- 200 

### average intercept and slope 
beta0 <- 1.0 
beta1 <- 6.0 

### true autocorrelation 
ar.val <- .4 

### true error SD, intercept SD, slope SD, and intercept-slope cor 
sigma <- 1.5 
tau0 <- 2.5 
tau1 <- 2.0 
tau01 <- 0.3 

### maximum number of possible observations 
m <- 10 

### simulate number of observations for each individual 
p <- round(runif(n,4,m)) 

### simulate observation moments (assume everybody has 1st obs) 
obs <- unlist(sapply(p, function(x) c(1, sort(sample(2:m, x-1, 
replace=FALSE))))) 

### set up data frame 
dat <- data.frame(id=rep(1:n, times=p), obs=obs) 

### simulate (correlated) random effects for intercepts and slopes 
mu <- c(0,0) 
S <- matrix(c(1, tau01, tau01, 1), nrow=2) 
tau <- c(tau0, tau1) 
S <- diag(tau) %*% S %*% diag(tau) 
U <- mvrnorm(n, mu=mu, Sigma=S) 

### simulate AR(1) errors and then the actual outcomes 
dat$eij <- unlist(sapply(p, function(x) arima.sim(model=list(ar=ar.val), 
n=x) * sqrt(1-ar.val^2) * sigma)) 
dat$yij <- (beta0 + rep(U[,1], times=p)) + (beta1 + rep(U[,2], times=p)) *  
log(dat$obs) + dat$eij 

dat = ddply(dat, .(id), function(x){ 
    x$alpha = ifelse(runif(n = 1) > 0.9, 1, 0.1) 
    x$grouper = factor(rbinom(n=1, size =3 ,prob=0.5), levels=0:3) 
    x 
}) 
tspag = ggplot(dat, aes(x=obs, y=yij)) + 
    geom_line() + guides(colour=FALSE) + xlab("Observation Time Point") + 
    ylab("Y") 
spag = tspag + aes(colour = factor(id)) 
spag 
bwspag = tspag + aes(group=factor(id)) 
bwspag 

我已经试过scale_colour_manual,我已经试过定义在bwspag线...没有运气的AES语句中的颜色。我对R相对缺乏经验。我很感激任何帮助!

回答

1

是否要在灰度级中设置行?如果是的话,那么colourgeom_line()的功能应该足够了。例如:

ggplot(iris, aes(Sepal.Length, Sepal.Width)) + geom_line(colour = "gray40") 

您可以选择其他值与灰:从0到100 More info here.

+0

完美,正是我需要的。谢谢! –