删除 geom_tile 中的空白并匹配 geom_vline&hline 位置

Ale*_*der 4 r ggplot2

使用函数时,我无法删除矩形之间的空白geom_tile

df <- data.frame(
  x = c(seq(2,16,2),seq(17,39,2)),
  y = c(rep(c(seq(8,26,2),seq(27,45,2)),each=20)),
  z = c(1:400))

library(ggplot2)
ggplot(df, aes(x, y)) +
  geom_tile(aes(fill = factor(z)), colour = "grey50")+
  geom_vline(aes(xintercept=6),linetype="dashed",colour="red",size=1)+
  geom_hline(aes(yintercept=24),linetype="dashed",colour="red",size=1)+
  scale_x_continuous(expand = c(0, 0),breaks=seq(0,50,1))+
  scale_y_continuous(expand = c(0, 0),breaks=seq(0,50,1))+
  theme(legend.position = "none")
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

直到这里我明白为什么会发生这种情况。为了继续前进,我可以转换x and y为因子水平以消除空间!但这次我失去了geom_vlinegeom_hline台词。这可能是转换x and y因子水平发生的。

ggplot(df, aes(factor(x), factor(y))) +
  geom_tile(aes(fill = factor(z)), colour = "grey50")+
  geom_vline(aes(xintercept=6),linetype="dashed",colour="red",size=1)+
  geom_hline(aes(yintercept=24),linetype="dashed",colour="red",size=1)+
  #scale_x_continuous(expand = c(0, 0),breaks=seq(0,50,1))+
  #scale_y_continuous(expand = c(0, 0),breaks=seq(0,50,1))+
  theme(legend.position = "none")
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

当我添加因子级别来geom_vline&geom_hline得到这个错误时!

UseMethod("rescale") 中的错误:没有适用于“factor”类对象的“rescale”方法

  ggplot(df, aes(factor(x), factor(y))) +
  geom_tile(aes(fill = factor(z)), colour = "grey50")+
  geom_vline(aes(xintercept=factor(6)),linetype="dashed",colour="red",size=1)+         geom_hline(aes(yintercept=factor(24)),linetype="dashed",colour="red",size=1)+
  #scale_x_continuous(expand = c(0, 0),breaks=seq(0,50,1))+
  #scale_y_continuous(expand = c(0, 0),breaks=seq(0,50,1))+
  theme(legend.position = "none")
Run Code Online (Sandbox Code Playgroud)

Jul*_*ora 6

这里有两种可能的解决方案。第一个是调整瓷砖的width和:height

library(ggplot2)
ggplot(df, aes(x, y)) +
  geom_tile(aes(fill = factor(z)), colour = "grey50", width = 2, height = 2)+
  geom_vline(aes(xintercept=6),linetype="dashed",colour="red",size=1)+
  geom_hline(aes(yintercept=24),linetype="dashed",colour="red",size=1)+
  scale_x_continuous(expand = c(0, 0),breaks=seq(0,50,1))+
  scale_y_continuous(expand = c(0, 0),breaks=seq(0,50,1))+
  theme(legend.position = "none")
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

xintercept第二个是更改和的值yintercept

ggplot(df, aes(factor(x), factor(y))) +
  geom_tile(aes(fill = factor(z)), colour = "grey50")+
  geom_vline(aes(xintercept=3),linetype="dashed",colour="red",size=1)+
  geom_hline(aes(yintercept=9),linetype="dashed",colour="red",size=1)+
  theme(legend.position = "none")
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

哪些来自

match(6, unique(df$x))
# [1] 3
match(24, unique(df$y))
# [1] 9
Run Code Online (Sandbox Code Playgroud)

也就是说,现在我们需要指定感兴趣的因子级别的数量。在本例中,6 和 24 都用作因子水平,因此我们可以这样做,但一般来说,此方法可能不起作用,因为您可能需要一条不存在的因子水平的线。