gpt4 book ai didi

r - 你能用离散尺度删除ggplot中轴和数据之间的空间吗

转载 作者:行者123 更新时间:2023-12-04 15:40:10 25 4
gpt4 key购买 nike

是否可以使用离散比例缩小 ggplot(点)中轴和数据之间的空间。我已经看到很多使用离散比例执行此操作的方法,但似乎无法让它在这种情况下工作(轴上具有 1 个值的离散比例)。

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

最佳答案

您可以使用 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

关于r - 你能用离散尺度删除ggplot中轴和数据之间的空间吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58087258/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com