在不使用自由比例尺的情况下自定义 ggplots2 中的 y 轴

问题描述

我正在尝试绘制一个 facet_wrap 来单独设置 y 轴限制。我已经在论坛中寻找解决方案,但没有找到。

我的数据看起来像这样,

structure(list(fecha = c(2000,2000,2001,2002,2003),cientifico = c("Gaidropsarus macrophthalmus","Gadiculus argenteus","microchirus variegatus","Arnoglossus laterna","Blennius ocellaris","Eutrigla gurnardus","Argentina sphyraena","Micromesistius poutassou","Lesueurigobius friesii","Callionymus maculatus","Lepidorhombus boscii","Capros aper","Chelidonichthys cuculus","Helicolenus dactylopterus","Callionymus lyra","Arnoglossus imperialis","Chelidonichthys obscurus","Trisopterus minutus","Buglossidium luteum","Trachinus draco","Serranus cabrilla","Scorpaena loppei","Gaidropsarus macrophthalmus","Arnoglossus laterna"),q95 = c(16,11,15,12,24,20,7,10,26,14,25,33,27,29,13,22,17,21,23,28,13
)),row.names = c(1L,3L,4L,5L,6L,8L,11L,12L,15L,16L,17L,18L,20L,22L,24L,28L,32L,36L,38L,39L,42L,43L,44L,46L,47L,48L,49L,51L,52L,53L,55L,57L,58L,60L,63L,64L,70L,72L,79L,80L,81L,82L,83L,86L,87L,88L,89L,90L,91L,92L,93L,94L,98L,101L,103L,104L,106L,107L,116L,117L,120L,121L,123L,126L,127L,128L,131L),class = "data.frame")

并使用以下代码

  p <- ggplot(peques,aes(x = fecha,y = q95)) + geom_point(color="black") +
  geom_line(color="blue") +
  facet_wrap(~cientifico,ncol=3,scales="free") + 
  labs(x="Año",y="Q95 (cm)",face="bold") +
  theme_bw()+ 
  annotate("segment",x=-Inf,xend=Inf,y=-Inf,yend=-Inf,size=1)+ 
  annotate("segment",xend=-Inf,yend=Inf,size=1)+
  theme(axis.ticks.length=unit(.15,"cm"),strip.text = element_text(face = "italic"),axis.title.x = element_text(face="bold",vjust=2.95,size=14),axis.title.y = element_text(face="bold",vjust= 1.95,size=12),axis.text.x = element_text(size=8),axis.text.y = element_text(size=8)) +
  scale_x_continuous(breaks = seq(1990,2020,by=1),labels = c(1990,rep("",4),1995,2005,2010,2015,2020 )+
scale_y_continuous(limits=c(min[i],max[i)]),breaks=intervalo[i]),labels=labels[i])) 

我得到这张图

enter image description here

但我想定义 y 轴的间隔,将所有数字设置为整数而不是小数... 我正在 ggplot 之前尝试使用以下代码来定义每个物种的最小值、最大值和间隔,但没有运气。

min <- list()
max <- list()
intervalo <- list()
sp <- list()

for (i in 1:length(especies_peques)){
  sp[[i]] <- subset(peques,cientifico ==especies[i])
  
min[[i]] <- min(sp[i]$q95)
max[[i]] <- max(sp[i]$q95)
intervalo[[i]] <- seq(min[i],max[i],by=2)
labels[[i]] <- as.character(intervalo[i])
labels[!(intervalo %% 2 == 0)] <- ""

我希望我已经很好地解释了自己。任何解决我的问题的提示都将受到欢迎。 谢谢

解决方法

您的代码对我不起作用,因此这可能无济于事,但减少 y 轴“混乱”的潜在解决方案是使用 scales::pretty_breaks() 函数,例如

library(tidyverse)
library(palmerpenguins)

penguins %>% 
  na.omit() %>% 
  ggplot(aes(x = species,y = flipper_length_mm)) +
  geom_boxplot() +
  facet_wrap(~year + island)

example_1.png

并且,使用 scales::pretty_breaks()

penguins %>% 
  na.omit() %>% 
  ggplot(aes(x = species,y = flipper_length_mm)) +
  geom_boxplot() +
  facet_wrap(~year + island) +
  scale_y_continuous(breaks = scales::pretty_breaks(4))

example_2.png