Objetivo 1: Segmentación

Published

September 5, 2024

library(readxl)
library(tidyverse)
── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
✔ dplyr     1.1.4     ✔ readr     2.1.5
✔ forcats   1.0.0     ✔ stringr   1.5.1
✔ ggplot2   3.5.1     ✔ tibble    3.2.1
✔ lubridate 1.9.3     ✔ tidyr     1.3.1
✔ purrr     1.0.2     
── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
✖ dplyr::filter() masks stats::filter()
✖ dplyr::lag()    masks stats::lag()
ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(egg)
Cargando paquete requerido: gridExtra

Adjuntando el paquete: 'gridExtra'

The following object is masked from 'package:dplyr':

    combine
library(tidyverse)
library(ggplot2)
library(ggpmisc)
Cargando paquete requerido: ggpp
Registered S3 methods overwritten by 'ggpp':
  method                  from   
  heightDetails.titleGrob ggplot2
  widthDetails.titleGrob  ggplot2

Adjuntando el paquete: 'ggpp'

The following object is masked from 'package:ggplot2':

    annotate
library(broom)
library(ggplot2)
library(patchwork)
library(egg)
library(ggpubr)

Adjuntando el paquete: 'ggpubr'

The following objects are masked from 'package:ggpp':

    as_npc, as_npcx, as_npcy

The following object is masked from 'package:egg':

    ggarrange
library(readxl)
library(tidyverse)
library(egg)
library(tidyverse)
library(ggplot2)
dat_clean0=read.csv("dat_clean_modified_zscore_especies.csv")

dat_clean0$Banda <- factor(dat_clean0$Banda,
  levels = c("35-45","45-90","90-170","170-260"),labels = c("35-45","45-90","90-170","170-260"))


dat_clean0=dat_clean0 %>%
  mutate(Value_linear = 10^(Value/10))  #%>%
  #filter(!is.na(Value_linear))

dat_clean0=dat_clean0 %>%
  rename(Segmentacion = Class)  #%>%

dat_clean=dat_clean0
unique(dat_clean0$Segmentacion)
[1] "Plancton"     "Vinciguerria" "Salpas"       "Múnida"       "Anchoveta"   
names(dat_clean)
 [1] "X"             "Frequency"     "Value"         "Banda"        
 [5] "Depth_school"  "Segmentacion"  "Detect_school" "N_Catch_Year" 
 [9] "group"         "Value_linear" 
ggplot(dat=dat_clean[dat_clean$Segmentacion == "Vinciguerria",])+
  geom_line(aes(x = as.numeric(Frequency), y=Value))

    facet_wrap(facets="N_Catch_Year",scales = "free_y",ncol = 3,strip.position = "left")
<ggproto object: Class FacetWrap, Facet, gg>
    compute_layout: function
    draw_back: function
    draw_front: function
    draw_labels: function
    draw_panels: function
    finish_data: function
    init_scales: function
    map_data: function
    params: list
    setup_data: function
    setup_params: function
    shrink: TRUE
    train_scales: function
    vars: function
    super:  <ggproto object: Class FacetWrap, Facet, gg>
library(ggplot2)

ggplot(dat_clean)+
  geom_boxplot(alpha=0.5,size=0.35, aes(fill=Segmentacion,y = Value, x=Segmentacion, alpha=0.5), show.legend = F)+
  theme_presentation(base_size = 12) +
  ylab("Sv (dB)")+

  scale_color_viridis_d()+
  
  #scale_fill_manual(values =c("#5f5f5f","#000080","#008000","#ff00bf","#a6533c"))+ 
 #scale_fill_viridis_d(option = "C",direction = -1,begin = 0.30,end = 1,alpha = 0.5)+
  labs(x="Categoría")+
  scale_x_discrete()+
  theme(legend.position = "top")+
  theme(panel.grid.major.y = element_line(color = "gray", linetype = "dashed"))

ggplot(dat_clean)+
  geom_boxplot(alpha=0.5,size=0.35, aes(fill=Segmentacion,y = Value, x=Segmentacion, alpha=0.5), show.legend = F)+
  theme_presentation(base_size = 12) +
  ylab("Sv (dB)")+
  scale_color_viridis_d()+
  
  
  #scale_fill_manual(values =c("#5f5f5f","#000080","#008000","#ff00bf","#a6533c"))+ 
 #scale_fill_viridis_d(option = "C",direction = -1,begin = 0.30,end = 1,alpha = 0.5)+
  labs(x="Categoría")+
  scale_x_discrete()+
  theme(legend.position = "top")+
  theme(panel.grid.major.y = element_line(color = "gray", linetype = "dashed"))+
  facet_wrap(~Banda)

Figuras

ggplot(dat_clean, aes(y = Value, x=as.numeric(Frequency)))+
  geom_line(alpha=0.5, aes(color=Segmentacion),lwd=1, show.legend = F)+
  geom_smooth(size=1,method = "gam", color="black", show.legend = F)+
  theme_presentation(base_size = 12) +
  xlab("Frecuencia (kHz)") +
  ylab("Sv (dB)")+
  scale_x_continuous(breaks = c(38,70,90,120,170,200,260))+
  geom_vline(xintercept = c(38,45,90,170,260),linetype = c("dashed"),color="gray")+
  geom_hline(yintercept = c(-80,-70,-60,-50,-40,-30,-20),linetype = c("dashed"),color="gray")+
  
  scale_color_viridis_d()+
  
theme(legend.title=element_blank())+
  facet_wrap(~Segmentacion, ncol=5)

  #facet_wrap(c("Year", "Class), labeller = "label_both")


######################################################

ggplot(dat_clean, aes(y = Value, x=as.numeric(Frequency)))+
  #geom_line(alpha=0.5, aes(color=N_Catch_Year),lwd=3)+
  geom_smooth(size=1,method = "gam", aes(color=Segmentacion), show.legend = F)+

  theme_presentation(base_size = 12) +
  xlab("Frecuencia (kHz)") +
  ylab("Sv (dB)")+
  
  scale_x_continuous(breaks = c(38,70,90,120,170,200,260))+
  geom_vline(xintercept = c(38,45,90,170,260),linetype = c("dashed"),color="gray")+
  geom_hline(yintercept = c(-80,-70,-60,-50,-40,-30,-20),linetype = c("dashed"),color="gray")+
  
  scale_color_viridis_d()+
  theme(legend.title=element_blank())+
  facet_wrap(~Segmentacion, ncol=5)

  #facet_wrap(c("Year", "Class), labeller = "label_both")


######################################################


ggplot(dat_clean, aes(y = Value, x=as.numeric(Frequency)))+
  geom_line(alpha=0.5, aes(color=Segmentacion),lwd=1, show.legend = F)+
  geom_smooth(size=1,method = "lm", color="black", show.legend = F)+
  stat_regline_equation()+
  theme_presentation(base_size = 12) +
  
  xlab("Frecuencia (kHz)") +
  ylab("Sv (dB)")+
  
  scale_x_continuous(breaks = c(38,70,90,120,170,200,260))+
  geom_vline(xintercept = c(38,45,90,170,260),linetype = c("dashed"),color="gray")+
  geom_hline(yintercept = c(-80,-70,-60,-50,-40,-30,-20),linetype = c("dashed"),color="gray")+

  
  scale_color_viridis_d()+
  
theme(legend.title=element_blank())+
  facet_wrap(~Segmentacion,ncol=5)

  #facet_wrap(c("Year", "Class), labeller = "label_both")


######################################################

ggplot(dat_clean, aes(y = Value, x=as.numeric(Frequency)))+
  #geom_line(alpha=0.5, aes(color=N_Catch_Year),lwd=3)+
  geom_smooth(size=1,method = "lm", aes(color=Segmentacion),show.legend = F)+
  stat_regline_equation()+
  theme_presentation(base_size = 12) +
  xlab("Frecuencia (kHz)") +
  ylab("Sv (dB)")+
  
  scale_x_continuous(breaks = c(38,70,90,120,170,200,260))+
  geom_vline(xintercept = c(38,45,90,170,260),linetype = c("dashed"),color="gray")+
  geom_hline(yintercept = c(-80,-70,-60,-50,-40,-30,-20),linetype = c("dashed"),color="gray")+
  
  scale_color_viridis_d()+
  #ggtitle("")+
  theme(legend.title=element_blank())+
  facet_wrap(~Segmentacion, ncol=5)

  #facet_wrap(c("Year", "Class), labeller = "label_both")


######################################################

ggplot(dat_clean, aes(y = Value, x=as.numeric(Frequency)))+
  #geom_line(alpha=0.5, aes(color=N_Catch_Year),lwd=3)+
  geom_smooth(size=1,method = "glm", aes(color=Segmentacion),show.legend = F)+
  stat_regline_equation()+
  theme_presentation(base_size = 12) +
  xlab("Frecuencia (kHz)") +
  ylab("Sv (dB)")+
  
  scale_x_continuous(breaks = c(38,70,90,120,170,200,260))+
  geom_vline(xintercept = c(38,45,90,170,260),linetype = c("dashed"),color="gray")+
  geom_hline(yintercept = c(-80,-70,-60,-50,-40,-30,-20),linetype = c("dashed"),color="gray")+
  
  scale_color_viridis_d()+
  #ggtitle("")+
  theme(legend.title=element_blank())+
  facet_wrap(~Segmentacion, ncol=5)

  #facet_wrap(c("Year", "Class), labeller = "label_both")

Regresión en dB

# Texto a añadir
texts <- data.frame(
  Segmentacion = c('Anchoveta', 'Múnida', 'Plancton', 'Salpas', 'Vinciguerria'),
  x = rep(100, 5),  # Coordenada x del texto en cada facet
  y = rep(-30, 5),  # Coordenada y del texto en cada facet
  label = c('y= -45.23 - 1*10^-7x', 'y= -60.86 + 1.7*10^-8x', 'y= -67.96 + 2.4*10^-9x', 'y= -65.53 - 5.9*10^11x', 'y= -58.86 + 8*10^-10x')
)


plot_lineal_ecuacion=ggplot(dat_clean, aes(y = Value, x=as.numeric(Frequency)))+
  geom_line(alpha=0.5, aes(color=Segmentacion),lwd=1.5, show.legend = F)+
  geom_smooth(size=1,method = "lm", color="black", show.legend = F)+
    xlab("Frecuencia (kHz)") +
  ylab("Sv (dB)")+
  
  scale_x_continuous(breaks = c(38,70,90,120,170,200,260))+
  geom_vline(xintercept = c(38,45,90,170,260),linetype = c("dashed"),color="gray")+
  geom_hline(yintercept = c(-80,-70,-60,-50,-40,-30,-20),linetype = c("dashed"),color="gray")+
      
    scale_color_viridis_d()+
  
  #stat_regline_equation(size=10)+
  theme_presentation() +
  facet_wrap(~Segmentacion, ncol=2)+
  geom_text(data = texts, aes(x = 120, y = -35, label = label), size = 7.5, color = "black")


ggsave(filename = "7.FM_modas_LM.png",
  plot = plot_lineal_ecuacion,     
  height = 10,             # Specifies the height of the plot in inches
       width = 10,              # Specifies the width of the plot in inches
       dpi = 1000,             # Specifies the resolution in dots per inch
       path = "F:/Tesis abordo/Tesis abordo/Figuras/Objetivo01/",device = "png") 







ggplot(dat_clean, aes(y = 10^(Value/10), x=as.numeric(Frequency)))+
  geom_line(alpha=0.5, aes(color=Segmentacion),lwd=1.5, show.legend = F)+
  geom_smooth(size=1,method = "lm", color="black", show.legend = F)+
    xlab("Frecuencia (kHz)") +
  
  labs(y=expression("10"^"Sv (dB)"))+
  
  scale_x_continuous(breaks = c(38,70,90,120,170,200,260))+
  geom_vline(xintercept = c(38,45,90,170,260),linetype = c("dashed"),color="gray")+
  #geom_hline(yintercept = c(-80,-70,-60,-50,-40,-30,-20),linetype = c("dashed"),color="gray")+
      
    scale_color_viridis_d()+
  
  stat_regline_equation(size=6)+
  theme_presentation() +
  facet_wrap(~Segmentacion, ncol=2,scales = "free_y")

ggplot(dat_clean, aes(y = 10^(Value/10), x=as.numeric(Frequency)))+
  #geom_line(alpha=0.5, aes(color=Segmentacion),lwd=1.5, show.legend = F)+
  geom_smooth(size=1,method = "lm", color="black", show.legend = F)+
    xlab("Frecuencia (kHz)") +
  
  labs(y=expression("10"^"Sv (dB)"))+
  
  scale_x_continuous(breaks = c(38,70,90,120,170,200,260))+
  geom_vline(xintercept = c(38,45,90,170,260),linetype = c("dashed"),color="gray")+
  #geom_hline(yintercept = c(-80,-70,-60,-50,-40,-30,-20),linetype = c("dashed"),color="gray")+
      
    scale_color_viridis_d()+
  
  stat_regline_equation(size=6)+
  theme_presentation() +
  facet_wrap(~Segmentacion, ncol=2,scales = "free_y")

ggplot(dat_clean, aes(y = Value, x=log10(as.numeric(Frequency))))+
  geom_line(alpha=0.5, aes(color=Segmentacion),lwd=1.5, show.legend = F)+
  geom_smooth(size=1,method = "glm", color="black", show.legend = F)+
    xlab("Frecuencia (kHz)") +
  ylab("Sv (dB)")+
  
  #scale_x_continuous(breaks = c(38,70,90,120,170,200,260))+
  #geom_vline(xintercept = c(38,45,90,170,260),linetype = c("dashed"),color="gray")+
  geom_hline(yintercept = c(-80,-70,-60,-50,-40,-30,-20),linetype = c("dashed"),color="gray")+

   scale_color_viridis_d()+
  stat_regline_equation(size=10)+
  theme_presentation() +
  facet_wrap(~Segmentacion, ncol=2)

Regresion en dominio lineal

ggplot(dat_clean, aes(y = 10^(Value/10), x=as.numeric(Frequency)))+
  geom_line(alpha=0.5, aes(color=Segmentacion),lwd=1.5, show.legend = F)+
  geom_smooth(size=1,method = "lm", color="black", show.legend = F)+
  
   scale_color_viridis_d()+
  
  stat_regline_equation(size=7)+
  theme_presentation() +
    facet_wrap(~Segmentacion, ncol=2, scale="free")

w=ggplot(dat_clean, aes(y = Value, x=as.numeric(Frequency),color=Segmentacion) )+
  #geom_line(alpha=0.1, aes(color=group),lwd=1, show.legend = T)+
  geom_smooth(size=2.25,method = "lm", show.legend = T,se = T)+
  scale_y_continuous(limits = c(-65,-45))+
      
   scale_color_viridis_d()+
  
  #stat_regline_equation()+
  theme_presentation(base_size = 14) +
  xlab("Frecuencia (kHz)") +
  ylab("Sv (dB)")+
  scale_x_continuous(breaks = c(38,70,90,120,170,200,260))+
  geom_vline(xintercept = c(38,45,90,170,260),linetype = c("dashed"),color="gray")+
  geom_hline(yintercept = c(-70,-60,-50,-40),linetype = c("dashed"),color="gray")+
  #scale_color_viridis_d(option = "C")+
  theme(legend.title=element_blank())+
   theme(panel.grid.major.y = element_line(color = "gray", linetype = "dashed"))+
       theme(panel.grid.major.x = element_line(color = "gray", linetype = "dashed"))



k=ggplot(dat_clean, aes(y = Value, x=as.numeric(Frequency),color=Segmentacion) )+
  #geom_line(alpha=0.1, aes(color=group),lwd=1, show.legend = T)+
  geom_smooth(size=2.25,method = "gam", show.legend = F,se=T)+
  
   scale_color_viridis_d()+
  
  #stat_regline_equation()+
  theme_presentation(base_size = 14) +
  xlab("Frecuencia (kHz)") +
  ylab("Sv (dB)")+
  scale_y_continuous(limits = c(-65,-45))+
  scale_x_continuous(breaks = c(38,70,90,120,170,200,260))+
  geom_vline(xintercept = c(38,45,90,170,260),linetype = c("dashed"),color="gray")+
  geom_hline(yintercept = c(-70,-60,-50,-40),linetype = c("dashed"),color="gray")+
  #scale_color_viridis_d(option = "C")+
  theme(legend.title=element_blank())+
   theme(panel.grid.major.y = element_line(color = "gray", linetype = "dashed"))+
     theme(panel.grid.major.x = element_line(color = "gray", linetype = "dashed"))


library(cowplot)

# Crear las gráficas w y k (código que proporcionaste)

# Obtener la leyenda de una de las gráficas (por ejemplo, w)
legend_w <- get_legend(w)

# Combinar las dos gráficas y agregar la leyenda
combined_plot <- plot_grid(
  k + theme(legend.position = "none"),  # Ocultar la leyenda de la gráfica w
  w + theme(legend.position = "none"),  # Ocultar la leyenda de la gráfica k
  legend_w,
  ncol = 3, rel_heights = c(1, 1, 1),rel_widths = c(1,1,0.35),  # Ajustar las alturas relativas
  labels = c("(a)", "(b)", ""),  # Etiquetas de enumeración
  align = "h"  # Alinear horizontalmente las partes
)

# Ajustar el tamaño de la leyenda
combined_plot <- combined_plot + theme(
  legend.text = element_text(size = 19),  # Tamaño del texto de la leyenda
  legend.title = element_text(size = 19)  # Tamaño del título de la leyenda
)

# Imprimir la figura combinada
print(combined_plot)

library(coin)
Cargando paquete requerido: survival
#oneway_test(Value ~ group, data = dat)

Análisis Espectral

Análisis de datos espectrales (uni-muenchen.de)

www.phonetik.uni-muenchen.de/~jmh/lehre/sem/ws1920/WP_4.1/SpectralAnalysis.html

library(emuR)

Adjuntando el paquete: 'emuR'
The following object is masked from 'package:base':

    norm
library(tidyverse)


ggplot(dat_clean, aes(y = Value, x=as.numeric(Frequency)))+
  geom_line(alpha=0.5, aes(color=Segmentacion),lwd=1, show.legend = F)+facet_wrap(~Segmentacion, ncol=5)

ggplot(dat_clean)+
aes(color=Segmentacion,x=as.numeric(Frequency),y = Value)+
  geom_area()+
  facet_wrap(~Segmentacion, ncol=5)

##########################################
dat_mean=dat_clean %>%
  group_by(Segmentacion, Frequency) %>%
  summarise(track_value = mean(10^(Value/10)))
`summarise()` has grouped output by 'Segmentacion'. You can override using the
`.groups` argument.
ggplot(dat_mean) +
  aes(x = as.numeric(Frequency), y = 10*log10(track_value), color = Segmentacion) +
  geom_line() 

bloqueos <- data.frame(
  xmin = c(40,85, 155,250),
  xmax = c(55,100, 171,270)
)

ggplot(dat_mean) +
  geom_line(size=2,aes(x = as.numeric(Frequency), y = 10*log10(track_value), color = Segmentacion) ) +
  geom_rect(data = bloqueos, aes(xmin = xmin, xmax = xmax, ymin = -Inf, ymax = Inf), fill = "gray", alpha = 0.75) +  # Ajusta color y transparencia según necesites
  labs(x = "Frecuencia", y = "10*log10(Value)") +

     scale_color_viridis_d()

names(dat_mean)
[1] "Segmentacion" "Frequency"    "track_value" 

1 ¿Cómo cuantificar las diferencias entre espectros?

Cuando observamos la figura anterior, que muestra los espectros promedio en los puntos medios temporales de dos categorías fricativas, parece que una manera fácil de distinguir entre las dos sería concentrarse en las diferencias en las amplitudes en el rango de 2000 a 3000 Hz. Podríamos, por ejemplo, tomar la media en ese rango de frecuencia en todos los tokens de los dos tipos para comprobar si es consistente el caso de que el alveolar contiene mucha menos energía en ese rango de frecuencia que su contraparte postalveolar:

1.1 Transformada discreta de coseno (DCT)

(Véase también este documento.)

Una transformada discreta de coseno (DCT) expresa una secuencia finita de n puntos de datos en términos de una suma de funciones de coseno que oscilan a diferentes frecuencias.

Las amplitudes de las funciones del coseno, k0, k1, k2, … kn-1, se denominan coeficientes DCT.

  • k0: la amplitud de un coseno con una frecuencia de 0

  • k1: la amplitud de un coseno con una frecuencia de 0,5

  • k2: la amplitud de un coseno con una frecuencia de 1

  • kn-1: la amplitud de un coseno con una frecuencia de 0,5*(n-1)

Si suma todos estos coeficientes DCT, reconstruirá exactamente la misma señal que se ingresó para el análisis DCT.

Los coeficientes DCT más altos corresponden a los detalles de la “secuencia finita de n puntos de datos”, mientras que los coeficientes más bajos representan las características más generales. Al menos las tres más bajas, k0, k1 y k2, corresponden (pero no son iguales) a las siguientes tres características descriptivas estadísticas: k0 está relacionada linealmente con la media de la secuencia, k1 con la pendiente de la secuencia y k2 con su curvatura. Véase, por ejemplo:

dat_mean2= dat_mean %>%
  group_by(Segmentacion)%>%
  mutate(reconstructed = emuR::dct(track_value,fit=T))


ggplot(dat_mean2) +
  geom_line(size=2,aes(x = as.numeric(Frequency), y = 10*log10(reconstructed ), color = Segmentacion) ) +
  geom_rect(data = bloqueos, aes(xmin = xmin, xmax = xmax, ymin = -Inf, ymax = Inf), fill = "gray", alpha = 0.75) +  # Ajusta color y transparencia según necesites
  labs(x = "Frecuencia", y = "10*log10(Value)") +
  
   scale_color_viridis_d()

sS_dftlong.mean = dat_mean %>%
  group_by(Segmentacion,) %>%
  mutate(#you can't use m=0 in order to calculate k0 only
    smoothed_k0tok1 = emuR::dct(track_value,m=1,fit=T),
    smoothed_k0tok2 = emuR::dct(track_value,m=2,fit=T),
    smoothed_k0tok3 = emuR::dct(track_value,m=3,fit=T),
    smoothed_k0tok4 = emuR::dct(track_value,m=4,fit=T),
    smoothed_k0tok5 = emuR::dct(track_value,m=5,fit=T),
    smoothed_k0tok6 = emuR::dct(track_value,m=6,fit=T))
ggplot(sS_dftlong.mean) +
  geom_line(size=2,aes(x = as.numeric(Frequency), y = 10*log10(smoothed_k0tok1), color = Segmentacion) ) +
  geom_rect(data = bloqueos, aes(xmin = xmin, xmax = xmax, ymin = -Inf, ymax = Inf), fill = "gray", alpha = 0.75) +  # Ajusta color y transparencia según necesites
  labs(x = "Frecuencia", y = "10*log10(Value)") +
  
   scale_color_viridis_d()

#############

ggplot(sS_dftlong.mean) +
  geom_line(size=2,aes(x = as.numeric(Frequency), y = 10*log10(smoothed_k0tok2), color = Segmentacion) ) +
  geom_rect(data = bloqueos, aes(xmin = xmin, xmax = xmax, ymin = -Inf, ymax = Inf), fill = "gray", alpha = 0.75) +  # Ajusta color y transparencia según necesites
  labs(x = "Frecuencia", y = "10*log10(Value)") +
  
   scale_color_viridis_d()

#############

ggplot(sS_dftlong.mean) +
  geom_line(size=2,aes(x = as.numeric(Frequency), y = 10*log10(smoothed_k0tok3), color = Segmentacion) ) +
  geom_rect(data = bloqueos, aes(xmin = xmin, xmax = xmax, ymin = -Inf, ymax = Inf), fill = "gray", alpha = 0.75) +  # Ajusta color y transparencia según necesites
  labs(x = "Frecuencia", y = "10*log10(Value)") +
  
   scale_color_viridis_d()

#############

ggplot(sS_dftlong.mean) +
  geom_line(size=2,aes(x = as.numeric(Frequency), y = 10*log10(smoothed_k0tok4), color = Segmentacion) ) +
  geom_rect(data = bloqueos, aes(xmin = xmin, xmax = xmax, ymin = -Inf, ymax = Inf), fill = "gray", alpha = 0.75) +  # Ajusta color y transparencia según necesites
  labs(x = "Frecuencia", y = "10*log10(Value)") +
  
   scale_color_viridis_d()
Warning in FUN(X[[i]], ...): Se han producido NaNs

#############

ggplot(sS_dftlong.mean) +
  geom_line(size=2,aes(x = as.numeric(Frequency), y = 10*log10(smoothed_k0tok5), color = Segmentacion) ) +
  geom_rect(data = bloqueos, aes(xmin = xmin, xmax = xmax, ymin = -Inf, ymax = Inf), fill = "gray", alpha = 0.75) +  # Ajusta color y transparencia según necesites
  labs(x = "Frecuencia", y = "10*log10(Value)") +
  
   scale_color_viridis_d()

#############

ggplot(sS_dftlong.mean) +
  geom_line(size=2,aes(x = as.numeric(Frequency), y = 10*log10(smoothed_k0tok6), color = Segmentacion) ) +
  geom_rect(data = bloqueos, aes(xmin = xmin, xmax = xmax, ymin = -Inf, ymax = Inf), fill = "gray", alpha = 0.75) +  # Ajusta color y transparencia según necesites
  labs(x = "Frecuencia", y = "10*log10(Value)") +
  
   scale_color_viridis_d()

Recuerde que la última figura muestra solo dos funciones de coseno (invertidas) de una cierta amplitud con frecuencia 0.5. Obviamente, esta no es la mejor representación de los espectros de /s/ y /ʃ/. Tenemos que encontrar un compromiso entre demasiada y muy poca información. En este caso específico, (= 5 coeficientes DCT) parece ser el mejor compromiso.m = 4

Podemos, por supuesto, aplicar la función -también a los datos no promediados:dct

texts2 <- data.frame(
  Segmentacion = c('Anchoveta', 'Múnida', 'Plancton', 'Salpas', 'Vinciguerria'),
  x = rep(100, 5),  # Coordenada x del texto en cada facet
  y = rep(-30, 5),  # Coordenada y del texto en cada facet
  label = c(
    "K0: -46.75",
    "K0: -56.70",
    "K0: -61.16",
    "K0: -64.20",
    "K0: -56.59"
  )
)

texts3 <- data.frame(
  Segmentacion = c('Anchoveta', 'Múnida', 'Plancton', 'Salpas', 'Vinciguerria'),
  x = rep(100, 5),  # Coordenada x del texto en cada facet
  y = rep(-30, 5),  # Coordenada y del texto en cada facet
  label = c(
    "K1:+",
    "K1:+",
    "K1:-",
    "K1:-",
    "K1:+"
  )
)

  
  
segmentacion=ggplot(dat_clean, aes(y = Value, x=as.numeric(Frequency)))+
  geom_line(alpha=0.5, aes(color=Segmentacion),lwd=1.5, show.legend = F)+

geom_line(data=sS_dftlong.mean,aes(x = as.numeric(Frequency), y = 10*log10(smoothed_k0tok3), color = "black"),lwd = 1.25, color="black") +
  #geom_smooth(size=1,method = "lm", color="black", show.legend = F)+
    xlab("Frecuencia (kHz)") +
  ylab("Sv (dB)")+
  scale_x_continuous(breaks = c(38,70,90,120,170,200,260))+
  geom_vline(xintercept = c(38,45,90,170,260),linetype = c("dashed"),color="gray")+
  geom_hline(yintercept = c(-80,-70,-60,-50,-40,-30,-20),linetype = c("dashed"),color="gray")+
  
     scale_color_viridis_d()+
  
  #stat_regline_equation(size=10)+
  theme_presentation() +
      #ggtitle("Smoothed with 4 DCT-coefficients (m=3)")+
  theme(legend.position = "none")+
  facet_wrap(~Segmentacion, ncol=2,scales = "free_y")+
    geom_text(data = texts2, aes(x = 78, y = -25, label = label), size = 7.5, color = "black")+
      geom_text(data = texts3, aes(x = 55, y = -35, label = label), size = 7.5, color = "black")

segmentacion

ggsave(filename = "9.Smoothed_4DCT.png",
  plot = segmentacion,     
  height = 10,             # Specifies the height of the plot in inches
       width = 10,              # Specifies the width of the plot in inches
       dpi = 1000,             # Specifies the resolution in dots per inch
       path = "F:/Tesis abordo/Tesis abordo/Figuras/Objetivo01/",device = "png") 
# dat_mean=dat %>%
#   group_by(Segmentacion, Frequency) %>%
#   summarise(track_value = mean(10^(Value/10)))

dat_mean_school= dat_clean %>%
  group_by(Segmentacion,Detect_school)%>%
  summarise(track_value = mean(10^(Value/10)))
`summarise()` has grouped output by 'Segmentacion'. You can override using the
`.groups` argument.
#Suavizado para cada school
sS_dftlong.mean_school = dat_mean_school %>%
  group_by(Segmentacion) %>%
  mutate(smoothed_k0tok3 = emuR::dct(track_value,m=3,fit=T))


sS_dctCoefficients =
sS_dftlong.mean_school  %>%
  group_by(Segmentacion) %>%
  do(tibble(DCT = emuR::dct(.$track_value, m = 1, fit = F)))%>%
  mutate(DCTCOEF = paste0("k", 0:1))%>%
  tidyr::spread(DCTCOEF, DCT)




tabla <- sS_dctCoefficients %>%
  mutate(k0db = round(10 * 
      log10(k0), 2)) %>%
  mutate(k1db = round(10 * log10(abs(k1)), 2))

tabla
# A tibble: 5 × 5
# Groups:   Segmentacion [5]
  Segmentacion          k0            k1  k0db  k1db
  <chr>              <dbl>         <dbl> <dbl> <dbl>
1 Anchoveta    0.0000211    0.00000639   -46.8 -52.0
2 Múnida       0.00000269   0.0000000807 -55.7 -70.9
3 Plancton     0.000000765 -0.000000329  -61.2 -64.8
4 Salpas       0.000000380 -0.0000000281 -64.2 -75.5
5 Vinciguerria 0.00000219   0.000000148  -56.6 -68.3
library(ggplot2)

# Graficar figura de barras
ggplot(tabla, aes(x = Segmentacion, y = k0db, fill = Segmentacion)) +
  geom_bar(stat = "identity", position = "dodge", width = 0.7) +
  labs(x = "Segmentacion", y = "k0 en dB") +
  theme_minimal()

ggplot(tabla, aes(x = Segmentacion, y = k1db, fill = Segmentacion)) +
  geom_bar(stat = "identity", position = "dodge", width = 0.7) +
  labs(x = "Segmentacion", y = "k1 en dB") +
  theme_minimal()

ggplot(tabla, aes(x = Segmentacion, y = k0, fill = Segmentacion)) +
  geom_bar(stat = "identity", position = "dodge", width = 0.7) +
  labs(x = "Segmentacion", y = "k0 en dB") +
  theme_minimal()

ggplot(tabla, aes(x = Segmentacion, y = k1, fill = Segmentacion)) +
  geom_bar(stat = "identity", position = "dodge", width = 0.7) +
  labs(x = "Segmentacion", y = "k1 en dB") +
  theme_minimal()