2013-02-01 29 views
19

Tôi có một khung dữ liệu được tạo ra với mã này:Làm thế nào để tạo một biểu đồ dạng đường bằng ggplot?

require(reshape2) 
foo <- data.frame(abs(cbind(rnorm(3),rnorm(3, mean=.8),rnorm(3, mean=.9),rnorm(3, mean=1)))) 
qux <- data.frame(abs(cbind(rnorm(3),rnorm(3, mean=.3),rnorm(3, mean=.4),rnorm(1, mean=2)))) 
bar <- data.frame(abs(cbind(rnorm(3,mean=.4),rnorm(3, mean=.3),rnorm(3, mean=.9),rnorm(3, mean=1)))) 

colnames(foo) <- c("w","x","y","z") 
colnames(qux) <- c("w","x","y","z") 
colnames(bar) <- c("w","x","y","z") 

rownames(foo) <- c("n","q","r") 
rownames(qux) <- c("n","q","r") 
rownames(bar) <- c("n","q","r") 

foo <- cbind(ID=rownames(foo),foo) 
bar <- cbind(ID=rownames(bar),qux) 
qux <- cbind(ID=rownames(bar),qux) 

foo$fn <- "foo" 
qux$fn <- "qux" 
bar$fn <- "bar" 

alldf<-rbind(foo,qux,bar) 
alldf.m <- melt(alldf) 

Những gì tôi muốn làm là để tạo ra một đường cong ggplot dòng trong khía cạnh định dạng, vì vậy nó tạo ra một biểu đồ như thế này:

enter image description here

Biểu đồ thực tế không chứa các dòng hướng lên - đây chỉ là bản phác thảo để tách biệt đường kẻ rõ ràng.

mã hiện tại của tôi không hoạt động:

library(ggplot2) 
    p <- ggplot(data=alldf.m, aes(x=variable)) + 
      geom_line(aes(colour=ID),alpha=0.4) 
    p <- p + facet_wrap(~ fn) 
    p 

cách tốt nhất để làm điều đó là gì?

+8

+1 để sử dụng đồ họa vẽ tay – SlowLearner

Trả lời

16

Hãy thử điều này:

ggplot(data=alldf.m, aes(x=variable, y = value, colour = ID, group = ID)) + 
    geom_line() + facet_wrap(~fn) 

enter image description here

6

Thậm chí nó là một ggplot2 được yêu cầu của OP, nhưng tôi nghĩ rằng ví dụ này là thích hợp cho lattice thêm:

library(lattice) 
xyplot(data=alldf.m, value~variable|fn, type ='b', groups = ID, auto.key = T) 

enter image description here

và sử dụng latticeExtra chúng ta có thể có được một cái gì đó colse đến giải pháp ggplot2:

p <- xyplot(data=alldf.m, value~variable|fn, type ='b', groups = ID, auto.key = T) 
update(p , par.settings = ggplot2like()) 

enter image description here

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