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

时间:2019-01-24 17:20:38

标签: 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")

enter image description here

直到这里我明白为什么会这样。为了前进,我可以将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")

enter image description here

当我将因子水平添加到geom_vline&geom_hline时出现此错误!

  

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

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

1 个答案:

答案 0 :(得分:2)

这是两种可能的解决方案。第一个是调整图块的widthheight

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

enter image description here

第二个是更改xinterceptyintercept的值:

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

enter image description here

来自

match(6, unique(df$x))
# [1] 3
match(24, unique(df$y))
# [1] 9

也就是说,现在我们需要指定感兴趣的因子水平的数量。在这种情况下,将6和24都用作因子水平,所以我们可以这样做,但是通常这种方法可能行不通,因为您可能希望线不存在因子水平。