你能否在ggplot离散比例尺中移除轴与数据之间的空格?

3

在ggplot(点图)中,是否可能减少离散比例尺下轴与数据之间的空间。我看到了很多关于离散比例尺的方法,但似乎在这种情况下(轴上只有一个值的离散比例尺),无法使其起作用。

ggplot with discrete axis - too much space between axis and text

我尝试将其转换为数字,并使用基于this response的expand(c(0,0)。 当应用于x轴时,它有效,但不适用于y轴(可能是因为y轴上只有一个分割点?)

library(tidyverse)

df <- tibble(Site = rep("A", 4), 
             Basin = rep("B1", 4), 
             Variable = c("V1", "V2", "V3", "V4"), 
             cls = c("up", "down", "ns", "up"))

#basic plot (output above)
p <- ggplot(df , aes(x=Variable, y=Site)) +
  geom_point(size=3, aes(color=cls, shape=cls, fill=cls)) + 
  facet_grid(Basin~., scales="free", space="free")
p

#attempting to convert discrete scale to continuous and apply limits to axis
p2 <- ggplot(df , aes(x=Variable, y=c(as.numeric(factor(df$Site)))) +
  geom_point(size=3, aes(color=cls, shape=cls, fill=cls)) + 
  scale_y_continuous(limits=c(0.95,1.05),breaks=1,labels=levels(factor(df$Site)), expand=c(0,0))+
  facet_grid(Basin ~ ., scales="free", space="free")

#I have also tried using 
  scale_y_discrete(expand=expand_scale(mult = c(0.01, .01)))



#when same method is applied to the axis it seems to work - is this because there is more than 1 break/variable
 p3 <- ggplot(df , aes(x=as.numeric(df$Variable), y=as.numeric(factor(df$Site)))) +
  geom_point(size=3, aes(color=cls, shape=cls, fill=cls)) + 
  scale_x_continuous(limits=c(0.95,4.05),breaks=seq(1:length(unique(df$Variable))),labels=levels(factor(df$Variable)),
                      expand=c(0,0))+
  facet_grid(Basin~., scales="free", space="free")
1个回答

3
您可以使用expand_scale()来调整轴的限制。参数mult将按您给定的百分比乘以当前比例尺的最小值和最大值。mult=c(0.2, 1)表示将底部距离缩短到其当前距离的20%,并保持顶部距离不变。
ggplot(df, aes(x = Variable, y = Site)) +
  geom_point(aes(color = cls, shape = cls, fill = cls), size = 3) +
  facet_grid(Basin ~ ., scales = "free", space = "free") +
  scale_y_discrete(expand = expand_scale(mult = c(0.2, 1)))

enter image description here


能否去掉X变量之间的空格,使数据点看起来更加紧凑? - Ecg
2
您可以使用 + theme(aspect.ratio = ...) 来调整绘图的宽度。 - yake84

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接