使用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")
直到这里我明白为什么会这样。为了前进,我可以将x and y
转换为因子水平以消除空间!但是这次我丢失了geom_vline
和geom_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")
当我将因子水平添加到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")
答案 0 :(得分:2)
这是两种可能的解决方案。第一个是调整图块的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")
第二个是更改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")
来自
match(6, unique(df$x))
# [1] 3
match(24, unique(df$y))
# [1] 9
也就是说,现在我们需要指定感兴趣的因子水平的数量。在这种情况下,将6和24都用作因子水平,所以我们可以这样做,但是通常这种方法可能行不通,因为您可能希望线不存在因子水平。