2013-03-09 3 views
6

열의 요인에 따라 기본 범례가 있습니다. 다른 열의 요소를 기반으로 x 축을 채색했습니다.플롯에 두 번째 범례 추가 R

이 x 축 색상에 대한 범례를 추가 할 수 있습니까?

enter image description here

은 ( https://dl.dropbox.com/u/81597211/Untitled.pdf)

데이터를 합병
row.names LCA_CASE_WORKLOC1_CITY LCA_CASE_JOB_TITLE LCA_CASE_WORKLOC1_STATE LCA_CASE_WAGE_RATE_FROM Company 
    4726 REDWOOD SHORES SOFTWARE DEVELOPER - ARCHITECT CA 263500.00 ORACLE 
    102663 DENVER SOFTWARE ENGINEER (SOFTWARE DEVELOPER 5) CO 170000.00 ORACLE 
    103621 DENVER SOFTWARE ENGINEER (SOFTWARE DEVELOPER 5) CO 170000.00 ORACLE 
    95210 SANTA CLARA SOFTWARE ENGINEER (SOFTWARE DEVELOPER 4) CA 155000.00 ORACLE 
    18858 SANTA CLARA SOFTWARE ENGINEER (CONSULTING SOLUTION DIRECTOR) CA 150000.00 ORACLE 
    19514 IRVING CONSULTING TECHNICAL MANAGER TX 150000.00 ORACLE 
    57054 REDWOOD SHORES SOFTWARE ENGINEER (SOFTWARE DEVELOPER 4) CA 150000.00 ORACLE 
    76335 REDWOOD SHORES SOFTWARE ENGINEER (APPLICATIONS DEVELOPER 4) CA 150000.00 ORACLE 
    79964 REDWOOD SHORES SOFTWARE ENGINEER (SOFTWARE DEVELOPER 5) CA 150000.00 ORACLE 

코드

library("ggplot2") 
colour = factor(merged$Company) 
xcolor = factor(merged$LCA_CASE_WORKLOC1_STATE) 
qplot(merged[[2]], merged[[4]], colour = colour, xlab="Positions", ylab ="Salary", main="H1B Salary 2012") + theme(axis.text.x=element_text(angle=90,vjust=0.5, hjust=1, size=10, color= xcolor, lineheight=10)) + scale_y_continuous(breaks=seq(0,300000, 10000)) + theme(panel.grid.minor = element_line(colour = "red", linetype = "dotted")) + scale_x_discrete(merged[[2]]) 
+2

당신은 당신이 생성하는 데 사용되는 코드를 보여줄 수 –

+0

@ 데이비드은 (바람직하게 재현 예제를?) : 나는 dataframe 붙어있다. 여전히 데이터에 문제가 있습니까? – unj2

+0

@ kunj2aan, 새로운 R 세션에 붙여 넣은 것을 정확하게 복사하면 오류없이 음모를 얻을 수 있습니까? – Arun

답변

1

이 솔루션은 우리가 원하는 수만큼 다양한 아니라, 또한 매우 어려운 기술이 아니다. 먼저 일부 데이터 : 인기 함수 g_legend (찾을 수는 예컨대 here)이 경우에 유용

y <- c(5, 2, 3, 2) 
x <- factor(c("A", "B", "C", "A")) 
z <- factor(c("D", "E", "F", "E")) 

p <- qplot(x, y, geom = "point") + 
    theme(axis.text.x = element_text(color = z)) 

는 그것이 GROB 같은 플롯에서 범례 소요

(따라서이 해결책은 빠르지).

g_legend<-function(a.gplot){ 
    tmp <- ggplot_gtable(ggplot_build(a.gplot)) 
    leg <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box") 
    legend <- tmp$grobs[[leg]] 
    legend 
} 

그래서 우리는 두 전설, 점 (x) 다른 하나는 x 축 (z) 하나를 저장합니다.

legends <- list(g_legend(p + geom_point(aes(color = x))), 
       g_legend(p + geom_point(aes(color = z)) + 
          scale_color_manual(values = palette()[as.numeric(z)]))) 

두 번째 범례의 차이점에 유의하십시오. palette()이 여기에 사용됩니다. z <- factor(c(1, 2, 3))이면 element_text(color = z)geom_point(aes(color = z))과 다른 색을 사용합니다. 즉 element_text(color = z)은 기본 플롯의 색상을 예 : 2 in plot(1, col = 2).

마지막으로, 모든 것을 함께 넣어 :

library(gridExtra) 
grid.arrange(p + geom_point(aes(color = x)) + guides(color = 'none'), 
      do.call(arrangeGrob, legends), nrow = 1, widths = c(0.8, 0.2)) 

enter image description here