2013-05-06 47 views
7

Tôi đã mượn mã này từ lưới thống kê [chấm]. Kết quả là một vùng màu theo phân phối bình thường.Đặt hình ảnh làm màu của đa giác

mean=100; sd=15 
lb=80; ub=120 

x <- seq(-4,4,length=100)*sd + mean 
hx <- dnorm(x,mean,sd) 

plot(x, hx, type="n", xlab="IQ Values", ylab="Density", 
    main="Normal Distribution", axes=FALSE) 

i <- x >= lb & x <= ub 
lines(x, hx) 
polygon(c(lb,x[i],ub), c(0,hx[i],0), col="red") 

area <- pnorm(ub, mean, sd) - pnorm(lb, mean, sd) 
result <- paste("P(",lb,"< IQ <",ub,") =", 
    signif(area, digits=3)) 
mtext(result,2) 

enter image description here

Tôi đã tự hỏi nếu chúng ta có thể chọn một hình ảnh như màu sắc của đa giác màu đỏ?

Rất cám ơn!

Trả lời

10

Làm việc với mã của bạn, về cơ bản tôi đề xuất vẽ hình ảnh (tôi đã sử dụng hình ảnh ngẫu nhiên bên dưới) bằng cách sử dụng gói png (dựa trên lời khuyên từ In R, how to plot with a png as background?) và sau đó vẽ đường của bạn lên đó.

mean=100; sd=15 
lb=80; ub=120 

x <- seq(-4,4,length=100)*sd + mean 
hx <- dnorm(x,mean,sd) 

# load package and an image 
library(png) 
ima <- readPNG("Red_Hot_Sun.PNG") 

# plot an empty plot with your labels, etc. 
plot(1,xlim=c(min(x),max(x)), type="n", xlab="IQ Values", ylab="Density", 
    main="Normal Distribution", axes=FALSE) 
# put in the image 
lim <- par() 
rasterImage(ima, lim$usr[1], lim$usr[3], lim$usr[2], lim$usr[4]) 

# add your plot 
par(new=TRUE) 
plot(x, hx, xlim=c(min(x),max(x)), type="l", xlab="", ylab="", axes=FALSE) 
i <- x >= lb & x <= ub 
lines(x, hx) 
# add a polygon to cover the background above plot 
polygon(c(x,180,180,20,20), c(hx,0,1,1,0), col="white") 
# add polygons to cover the areas under the plot you don't want visible 
polygon(c(-20,-20,x[x<=lb],lb), c(-10,min(hx),hx[x<=lb],-10), col="white") 
polygon(c(ub,x[x>=ub],200,200), c(-1,hx[x>=ub],min(hx),-1), col="white") 

# add your extra text 
area <- pnorm(ub, mean, sd) - pnorm(lb, mean, sd) 
result <- paste("P(",lb,"< IQ <",ub,") =", 
    signif(area, digits=3)) 
mtext(result,2) 

Cung cấp cho bạn:

An image

+0

Awesome! Cảm ơn rất nhiều! –

Các vấn đề liên quan