2016-06-28 75 views
0

繼提供的很好的示例here後,我試着做出下面的填充等值線圖。如何在ggplot2的圖例中重新排列圖例中的離散顏色

x<-seq(1,11,.03)     # note finer grid 
y<-seq(1,11,.03) 
xyz.func<-function(x,y) {(x^2+y^2)} 
gg <- expand.grid(x=x,y=y) 
gg$z <- with(gg,xyz.func(x,y))  # need long format for ggplot 
brks <- cut(gg$z,breaks=c(1, 2, 5, 10, 30, 50, 100, 200)) 
brks <- gsub(","," - ",brks,fixed=TRUE) 
gg$brks <- gsub("\\(|\\]","",brks) # reformat guide labels 
ggplot(gg,aes(x,y)) + 
    geom_tile(aes(fill=brks))+ 
    scale_fill_manual("Z",values=brewer.pal(7,"YlOrRd"))+ 
    scale_x_continuous(expand=c(0,0))+ 
    scale_y_continuous(expand=c(0,0))+ 
    coord_fixed() 

結果看起來是這樣的:

Not what I expected

的事情是,輪廓是由字母順序排列,而不是由升值。

你會如何改變顏色的順序是通過升z值?首先,我想在值的前面添加「0」。我試過類似的東西:

brks <- gsub(pattern = "(\b[0-9]\b)", replacement = "0$1", x = brks) 

但它不起作用。

而且,它只會增加在個位數前一個零和100仍然是前02

其實,我並不完全滿意這種解決方法,因爲001 - 002美麗。

回答

1

讓你休息的有序因素:

x<-seq(1,11,.03)     # note finer grid 
y<-seq(1,11,.03) 
xyz.func<-function(x,y) {(x^2+y^2)} 
gg <- expand.grid(x=x,y=y) 
gg$z <- with(gg,xyz.func(x,y))  # need long format for ggplot 

brks <- cut(gg$z,breaks=c(1, 2, 5, 10, 30, 50, 100, 200), ordered_result = T) 
levels(brks) <- gsub(","," - ", levels(brks), fixed=TRUE) 
levels(brks) <- gsub("\\(|\\]","", levels(brks)) 

gg$brks <- brks # reformat guide labels 
ggplot(gg,aes(x,y)) + 
    geom_tile(aes(fill=brks))+ 
    scale_fill_manual("Z",values=brewer.pal(7,"YlOrRd"))+ 
    scale_x_continuous(expand=c(0,0))+ 
    scale_y_continuous(expand=c(0,0))+ 
    coord_fixed() 
相關問題