2014-03-05 5 views
1

ggplot2에 무작위 테스트 점수 데이터를 플로팅하려고합니다. 점수는 시험, 연도 및 학년별로 나뉩니다. 아래 스크립트를 실행하면 Y 축에 원하지 않는 범위가 표시됩니다. 즉, 범위는 순서가 지정되지 않은 반면 고정 간격으로 낮게 높게 주문해야합니다. 일반적으로 ggplot2는 기본적으로이 순서 지정을 수행하지만, 데이터 프레임이나 내가 인식하지 못하는 설정에 대해서는이 문제가 발생하지 않았습니다.ggplot2 : ggplot2가 올바른 y 축 범위를 표시하는 방법

grade <- rep(c(5,6,7,8,9),times=6) 
years <- rep(c(2008,2009,2010), each=10) 
tests <- rep(c("English","Math"),times=3,each=5) 
scores <- c(3.3,7.6,10.8,4.8,3.0,-2.8,14.8,12.4,0.3,6.0,7.0,3.1,3.7,-0.5,0.6,6.2,9.6,5.3,1.9,1.3,1.1,0.0,5.5,6.2,0.3,-0.4,2.2,4.9,4.7,2.6) 

data2 <- data.frame(cbind(years,grade,tests,scores)) 

graph_2 <- ggplot(data=data2, aes(x=years, y=scores)) + 
     geom_point(aes(color=factor(interaction(grade,tests)),size=1)) + 
     geom_line(aes(group=interaction(tests,grade), color=factor(interaction(grade,tests)))) + 
     facet_grid(. ~ grade) 

graph_2 

나는 생각 ggplot2 아마 생각 데이터가 분리 된 것입니다,하지만 내가 is.factor(scores)을 시도 할 때 R 콘솔 FALSE를 반환했습니다.

+1

당신은 최상위'ggplot' 객체에'color' 미학을 이동할 수는 (코드 짧은하게) 나는 '에는 NcoI = 1'과'facet_wrap'을 사용합니다 :'graph_2 <- (ggplot geom_point (size = 1) + geom_line (aes (그룹 = 상호 작용 (테스트, 성적))) + data = data2, aes (x = 연도, y = 점수, 색상 = facet_wrap (~ 등급, nrow = 1) ' –

답변

3

데이터에 문제가있는 경우 ggplot()이 아닙니다. 데이터 프레임을 만들었을 때 안에 함수 cbind()을 사용했습니다. 함수 cbind()은이 경우 모든 데이터가 동일한 유형의 문자를 가진 행렬을 생성하기 때문에 모든 열을 요인으로 사용했습니다. 함수 data.frame()은 데이터 프레임을 만들지 만 모든 문자 열은 인수로 변환됩니다.

data2 <- data.frame(cbind(years,grade,tests,scores)) 
str(data2) 
'data.frame': 30 obs. of 4 variables: 
$ years : Factor w/ 3 levels "2008","2009",..: 1 1 1 1 1 1 1 1 1 1 ... 
$ grade : Factor w/ 5 levels "5","6","7","8",..: 1 2 3 4 5 1 2 3 4 5 ... 
$ tests : Factor w/ 2 levels "English","Math": 1 1 1 1 1 2 2 2 2 2 ... 
$ scores: Factor w/ 28 levels "-0.4","-0.5",..: 17 27 10 20 15 3 12 11 5 24 ... 

당신이 cbind()을 제거하면

는 숫자 열은 숫자로 취급하고 예상대로 플롯 보인다.

data2 <- data.frame(years,grade,tests,scores) 
str(data2) 
'data.frame': 30 obs. of 4 variables: 
$ years : num 2008 2008 2008 2008 2008 ... 
$ grade : num 5 6 7 8 9 5 6 7 8 9 ... 
$ tests : Factor w/ 2 levels "English","Math": 1 1 1 1 1 2 2 2 2 2 ... 
$ scores: num 3.3 7.6 10.8 4.8 3 -2.8 14.8 12.4 0.3 6 ... 
+0

완벽한! 여기'cbind()'가 필요하다고 생각했는데, 이것은 훨씬 더 좋습니다. – Jefftopia

+1

이미'data.frame()'을 사용하여 하나의 데이터 프레임에 변수를 넣었으므로'cbind()'는 필요 없습니다. –

관련 문제