2013-02-27 57 views
4

我有一個data.frame有72個離散類別。當我通過這些類別進行着色時,我會在圖例中獲得72個不同的按鍵。我寧願只使用每個第二或第三個鍵。ggplot2:使用每個第N個圖例密鑰標籤

任何想法如何減少圖例中的行數?

再現我的問題,謝謝 H.

代碼如下。

t=seq(0,2*pi,length.out=10) 
RR=rep(cos(t),72)+0.1*rnorm(720) 
dim(RR)=c(10,72) 
stuff=data.frame(alt,RR) 
names(stuff)=c("altitude", 
       paste(rep(15:20,each=12), 
       rep(c("00","05",as.character(seq(from=10,to=55,by=5))),6), 
       sep=":")) 

bb=melt(stuff,id.vars=c(1)) 
names(bb)[2:3]=c("period","velocity") 
ggplot(data=bb,aes(altitude,velocity))+geom_point(aes(color=period))+geom_smooth() 
+0

你想排除某些類別或把它們合併起來? – 2013-02-27 05:54:15

回答

3

可以在geom_point()對待你period值數值。這將使顏色成爲漸變(從1到72的值對應於層數)。然後通過scale_colour_gradient()您可以設置您需要的休息次數,並將標籤添加爲您的實際週期值。

ggplot(data=bb,aes(altitude,velocity))+ 
    geom_point(aes(color=as.numeric(period)))+ 
    geom_smooth()+ 
    scale_colour_gradient("Period",low="red", high="blue", 
      breaks=c(seq(1,72,12),72),labels=unique(bb$period)[c(seq(1,72,12),72)]) 

enter image description here

+0

謝謝你,這種方法工作得很好。 – 2013-02-27 20:08:35

1

它看起來很難在這裏自定義圖例的discrete_color_scale!所以,我提出了一個格子的解決方案。您只需要將正確的文本提供給auto.key列表。

libarry(latticeExtra) 
labels.time <- unique(bb$period)[rep(c(F,F,T),each=3)] ## recycling here to get third label 
g <- xyplot(velocity~altitude, data=bb,groups=period, 
     auto.key=list(text=as.character(labels.time), 
        columns=length(labels.time)/3), 
     par.settings = ggplot2like(), axis = axis.grid, 
     panel = function(x,y,...){ 
     panel.xyplot(x,y,...) 
     panel.smoother(x,y,...) 
     }) 

enter image description here

相關問題