gpt4 book ai didi

r - 一起使用facet_wrap和geom_tile时,改变填充比例

转载 作者:行者123 更新时间:2023-12-04 11:51:31 24 4
gpt4 key购买 nike

在ggplot2中同时使用函数geom_tilefacet_wrap时,如何设置美学fill的不同限制,作为可以在scales中设置为free/free_y/free_xfacet_wrap选项?

以下是显示问题的示例。对于data.frame type中不同的dfz的范围可能会如此不同。如果我们使用美学fill的相同限制,则z部分具有很小值(value)的一些panle将很难看到细节。

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")

最佳答案

我知道这是一个老问题,但是最近我遇到了同样的问题,并提出了我想分享的解决方案。诀窍是使用geom_tile()中的nest()在嵌套数据框中收集单个tidyr图所需的数据集,然后使用map2()包中的purrr函数和包装函数来创建单个图:

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)

Grid-plot of maps with different color scale

嵌套的数据框包含两个列表列,其中包含数据集和图:
> 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()来微调绘图。

关于r - 一起使用facet_wrap和geom_tile时,改变填充比例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17006251/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com