在ggplot2中用不同的轴尺度对geom_tile进行分面会产生带状图像

问题描述 投票:0回答:1

我在 ggplot 中使用

geom_tile()
facet
ing 出现一些意外行为。

这是经典的“火山”瓷砖:

library(ggplot2)
library(reshape2)
volcano %>%
  reshape2::melt() %>%
  ggplot() + geom_tile(aes(x = Var1, y = Var2, fill = value))

好。现在让我们添加索引列和

facet
图像...

volcano %>%
  reshape2::melt() %>%
  cross_join(tibble(idx = c(1,2,3))) %>%
  ggplot() + geom_tile(aes(x = Var1, y = Var2, fill = value)) +
    facet_wrap(vars(idx))

好的。那很好。现在我将在 x 轴上创建不同的比例并使用

scales = "free"
参数...

volcano %>%
  reshape2::melt() %>%
  cross_join(tibble(idx = c(1,2,3))) %>%
  mutate(Var1 = Var1/idx) %>%
  ggplot() + geom_tile(aes(x = Var1, y = Var2, fill = value)) +
  facet_wrap(vars(idx), scales = "free")
}

请注意最后一张图和这张图的 x 轴值不同。

这并不是说

ggplot
重新缩放的轴有根本问题。在这里,我单独绘制了前一个图像的第三个面板,没有
facet
ing。

volcano %>%
  reshape2::melt() %>%
  cross_join(tibble(idx = c(1,2,3))) %>%
  mutate(Var1 = Var1/idx) %>%
  filter(idx == 3) %>%
  ggplot() + geom_tile(aes(x = Var1, y = Var2, fill = value))

问题是

facet
使用不同的尺度。即使我不使用
scales = "free"
参数,问题仍然存在...

volcano %>%
  reshape2::melt() %>%
  cross_join(tibble(idx = c(1,2,3))) %>%
  mutate(Var1 = Var1/idx) %>%
  ggplot() + geom_tile(aes(x = Var1, y = Var2, fill = value)) +
  facet_wrap(vars(idx))

对我来说似乎是一个错误,但当我在 github tidyverse/ggplot 上搜索“geom_tile facet”时,我没有看到问题报告。

有人知道如何在没有条带的情况下获得正确的情节吗?

更新:这是一个小例子,更详细地展示了正在发生的事情。

ggplot
似乎正在使用一个比例计算图块中每一列的宽度,并将该宽度应用于所有绘图......

# make some data
data.frame(x = 1:10, y = rep(1:10, each=10), value = runif(100)) %>%

  # duplicate the data and alter the scale of the second set
  bind_rows(., mutate(., x=x/3), .id = "idx") %>%

  # plot with faceting
  ggplot() + geom_tile(aes(x=x, y=y, fill = value)) + facet_wrap("idx")

r ggplot2 facet facet-wrap geom-tile
1个回答
0
投票

您可以按面改变瓷砖宽度:

volcano %>%
  reshape2::melt() %>%
  cross_join(tibble(idx = c(1,2,3))) %>%
  mutate(width = max(diff(Var1), na.rm = TRUE), .by = idx) |>
   ggplot() + 
  geom_tile(aes(x = Var1, y = Var2, fill = value, width = width)) +
  facet_wrap(vars(idx), scales = "free")

© www.soinside.com 2019 - 2024. All rights reserved.