2015-11-03 24 views
-1

我有一個大致類似於df的數據框,如下所示。它接近我所需要的,但有一個傳說是打印所有四個原始分組類別,而不是兩個。下面,我想有一個圖例反映df1的「紅色」和「藍色」分組類別的線條,然後是反映「綠色」和「橙色」分組類別的線條的單獨圖例如何爲ggplot中的單獨圖層獲取單獨的圖例?

我的動機是雙重的。首先,我想創建一個情節,表明可以爲在線出版物提供顏色,併爲印刷版提供黑白的信息。其次,我的真實數據集有5個分組類別,實際上只有兩個(紅色和藍色)是最豐富的。

所以我在下面試圖複製的解決方案是挑選出紅色和藍色,使這些線條變粗,改變線條的類型,並使它們成爲紅色和藍色。然後我想添加第二層,其他信息較少的類別,並使它們更薄,並通過線型來改變它們。謝謝。

test<-rep(c('red', 'blue', 'green', 'orange'), 6) 
test1<-rnorm(24, mean=10, sd=2) 
test2<-seq(1,24,2) 
df<-data.frame(test, test1, test2) 
df1<-subset(df, test=='red'|test=='blue') 
df2<-subset(df, test!='red'&test!='blue') 

library(ggplot2) 
test.plot <- ggplot(df1, aes(x=test2, y=test1, group=test)) + geom_line(aes(col=test,linetype=test), size=2) + scale_color_manual(values=c('red'='red3', 'blue'='darkblue')) 
test.plot + geom_line(data=df2, aes(x=test2, y=test1, linetype=test)) 
+0

但是你要分開的傳說,或一個傳奇? – Heroka

回答

1

一般來說,表示同一事物的圖形方面需要在同一個圖例中。這是否解決您的問題?它使用三種手動縮放比例(顏色,線型和尺寸)來獲取一個圖例中的所有測試,並使用特定的可識別線條。

library(grid) #for unit 
library(ggplot2) 

#make proper factor levelling in data, easier than setting breaks 
df$test <- factor(df$test, levels=c("blue","red","green","orange")) 

#plot with a lot of manual scales (but no second sets) 
p2 <- ggplot(df, aes(x=test2,y=test1, group=test, col=test)) + 
    geom_line(aes(linetype=test,size=test)) + 
    scale_color_manual(values=c('red'='red3','blue'='darkblue','green'='black','orange'='black')) + 
    scale_linetype_manual(values=c('red'='dashed','blue'='solid','green'='dashed','orange'='dotted')) + 
    scale_size_manual(values=c('red'=2,'blue'=2,'green'=0.5,'orange'=0.5)) + 
    theme(legend.key.width=unit(3,"lines")) #to show dashes in red 
p2 

enter image description here

數據使用(seed=123):

df <- structure(list(test = structure(c(2L, 1L, 3L, 4L, 2L, 1L, 3L, 
4L, 2L, 1L, 3L, 4L, 2L, 1L, 3L, 4L, 2L, 1L, 3L, 4L, 2L, 1L, 3L, 
4L), .Label = c("blue", "red", "green", "orange"), class = "factor"), 
    test1 = c(8.87904870689557, 9.53964502103344, 13.1174166282982, 
    10.1410167828492, 10.2585754703219, 13.4301299737666, 10.9218324119784, 
    7.46987753078693, 8.62629429621295, 9.10867605980008, 12.4481635948789, 
    10.7196276541147, 10.8015429011881, 10.2213654318902, 8.88831773049185, 
    13.5738262736062, 10.9957009564585, 6.06676568674072, 11.4027118031274, 
    9.05441718454413, 7.86435258802631, 9.56405017068341, 7.94799110338552, 
    8.54221754141772), test2 = c(1, 3, 5, 7, 9, 11, 13, 15, 17, 
    19, 21, 23, 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23)), .Names = c("test", 
"test1", "test2"), row.names = c(NA, -24L), class = "data.frame") 
+0

這工作得很好,除了奇怪的主題(legend.key.width = unit(3,'lines')參數給我的錯誤:「找不到功能單元」 – spindoctor

+0

得到它答案是加載庫(格) – spindoctor