在ggplot2中同时使用函数geom_tile
和facet_wrap
时,如何设置美学fill
的不同限制,作为可以在free/free_y/free_x
中设置为facet_wrap
的选项scales
下面是一个例子来说明这个问题。对于data.frame df
中的不同type
,z
的范围可能会非常不同。如果我们使用相同的美学fill
限制,z
部分中哪一个的值很小,就很难看到细节。
pp <- function (n,r=4) {
x <- seq(-r*pi, r*pi, len=n)
df <- expand.grid(x=x, y=x)
df$r <- sqrt(df$x^2 + df$y^2)
df$z <- cos(df$r^2)*exp(-df$r/6)
df
}
tmp <- pp(20)
tmp$type <- rep(1:4,each=nrow(tmp)/4)
tmp$z <- tmp$z*(10^(tmp$type))
ggplot(tmp,aes(x,y))+geom_tile(aes(fill=z))+facet_wrap(~type,scales="free")
发布于 2017-03-21 17:52:42
我知道这是一个老问题,但我最近遇到了同样的问题,并提出了这个解决方案,我想与大家分享一下。诀窍是使用来自geom_tile()
的nest()
在嵌套的数据帧中收集各个tidyr
绘图所需的数据集,然后使用purrr
包中的map2()
函数和一个包装器函数创建各个绘图:
library(tidyverse)
pp <- function (n,r=4) {
x <- seq(-r*pi, r*pi, len=n)
df <- expand.grid(x=x, y=x)
df$r <- sqrt(df$x^2 + df$y^2)
df$z <- cos(df$r^2)*exp(-df$r/6)
df
}
tmp <- pp(20)
tmp$type <- rep(1:4,each=nrow(tmp)/4)
tmp$z <- tmp$z*(10^(tmp$type))
plot_func <- function(df, name) {
ggplot(data = df, aes(x = x, y = y, fill = z)) +
geom_tile() +
scale_fill_continuous(name = name)
}
nested_tmp <- tmp %>%
group_by(type) %>%
nest() %>%
mutate(plots = map2(data, type, plot_func))
gridExtra::grid.arrange(grobs = nested_tmp$plots)
嵌套的dataframe包含两个列表列,其中包含数据集和图:
> nested_tmp
# A tibble: 4 × 3
type data plots
<int> <list> <list>
1 1 <tibble [100 × 4]> <S3: gg>
2 2 <tibble [100 × 4]> <S3: gg>
3 3 <tibble [100 × 4]> <S3: gg>
4 4 <tibble [100 × 4]> <S3: gg>
从这里可以很容易地修改plot_func()
来微调绘图。
发布于 2014-09-16 05:12:24
解决这个问题的一种方法是标准化fill变量,这样所有方面的规模都是相似的。
library(dplyr)
tmp1 <- group_by(tmp,type) # grouping the data by type
tmp2 <- mutate(tmp1, z1 = (z-mean(z))/sd(z)) #groupwise standardization
ggplot(tmp2,aes(x,y))+geom_tile(aes(fill=z1))+facet_wrap(~type,scales="free")
我希望有像fill=std(z)
这样的东西,这样我就不需要手动标准化了。
https://stackoverflow.com/questions/17006251
复制相似问题