如何在ggplot2

时间:2016-06-28 08:19:04

标签: r ggplot2

按照here提供的非常好的例子,我尝试制作以下填充轮廓图。

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 个答案:

答案 0 :(得分: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()