2013-03-09 36 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

你能告訴你用於生成這個代碼 – 2013-03-09 21:47:18

+0

@大衛(最好是在重複的例子?):我重視數據幀。你仍然對數據有問題嗎? – unj2 2013-03-09 22:02:59

+0

@ kunj2aan,當你正確地複製了你在新的R-session上粘貼的內容時,你是否能夠毫無錯誤地得到這個情節? – Arun 2013-03-09 22:16:33

回答

1

這個解決方案是不一樣多功能我們可能想要的,但也並不是很困難的技術。第一一些數據:

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)) 

一個流行的功能g_legend(可以發現例如here)在這種情況下是有用的,它需要一個圖例從情節作爲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在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

相關問題